answer
stringlengths
17
10.2M
package gr.ntua.vision.monitoring.rules; import gr.ntua.vision.monitoring.events.MonitoringEvent; import gr.ntua.vision.monitoring.resources.ThresholdRuleBean; import gr.ntua.vision.monitoring.resources.ThresholdRuleValidationError; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ThresholdRule extends Rule { private enum ThresholdPredicate { GE(">=") { @Override public boolean perform(final double x, final double y) { return x >= y; } }, GT(">") { @Override public boolean perform(final double x, final double y) { return x > y; } }, LE("<=") { @Override public boolean perform(final double x, final double y) { return x <= y; } }, LT("<") { @Override public boolean perform(final double x, final double y) { return x < y; } }; public final String op; /** * Constructor. * * @param op */ private ThresholdPredicate(final String op) { this.op = op; } /** * @param x * @param y * @return the evaluation result of the operation. */ public abstract boolean perform(final double x, final double y); } /** the log target. */ private static final Logger log = LoggerFactory.getLogger(Rule.class); private static final String[] UNITS = { "tenant", "user", "container", "object" }; private final String aggregationUnit; private final String metric; private final String operation; private final ThresholdPredicate pred; private final double thresholdValue; private final String topic; private final String uuid = UUID.randomUUID().toString(); /** * Constructor. * * @param engine * @param bean */ public ThresholdRule(final VismoRulesEngine engine, final ThresholdRuleBean bean) { super(engine); this.topic = requireNotNull(bean.getTopic()); this.pred = fromString(bean.getPredicate()); this.operation = bean.getOperation(); this.metric = requireNotNull(bean.getMetric()); this.aggregationUnit = bean.getAggregationUnit(); this.thresholdValue = bean.getThreshold(); } /** * @see gr.ntua.vision.monitoring.rules.RuleProc#id() */ @Override public String id() { return uuid; } /** * @see gr.ntua.vision.monitoring.rules.RuleProc#performWith(java.lang.Object) */ @Override public void performWith(final MonitoringEvent e) { log.trace("got event: {}", e); if (!isApplicable(e)) return; final double eventValue = (Double) e.get(metric); if (thresholdExceededBy(eventValue)) { log.debug("have violation on metric '{}', offending value {}", metric, eventValue); send(new ThresholdEvent(uuid, e.originatingService(), topic, eventValue)); } } /** * When <code>aggregationUnit</code> is unspecified by the user, this method returns <code>true</code>, since it means that it * applies to all units. * * @param e * @return <code>true</code> if the event comes from a matching unit. */ private boolean checkAggregationUnit(final MonitoringEvent e) { if (aggregationUnit == null || aggregationUnit.isEmpty()) return true; final String[] fs = aggregationUnit.split(","); for (int i = 0; i < UNITS.length; ++i) { if (i >= fs.length) continue; final String val = fs[i]; final String unit = UNITS[i]; final Object o = e.get(unit); if (o == null) continue; log.trace(String.format("unit %s => %s matching %s", unit, o, val)); if (!o.equals(val)) return false; } return true; } /** * When <code>operation</code> is unspecified by the user, this method returns <code>true</code>, since it means that it * applies to all operations. * * @param e * @return <code>true</code> if the event comes from a matching operation. */ private boolean checkOperation(final MonitoringEvent e) { if (operation == null || operation.isEmpty()) return true; if (operation.equals(e.get("operation"))) return true; return false; } /** * @param e * @return <code>true</code> if this is an event that matches <code>this</code> rule. */ private boolean isApplicable(final MonitoringEvent e) { return e.get(metric) != null && checkOperation(e) && checkAggregationUnit(e); } /** * @param eventValue * @return <code>true</code> when <code>eventValue</code> has exceeded <code>thresholdValue</code>. */ private boolean thresholdExceededBy(final double eventValue) { return pred.perform(eventValue, thresholdValue); } /** * @param op * @return a {@link ThresholdPredicate}. * @throws ThresholdRuleValidationError */ private static ThresholdPredicate fromString(final String op) throws ThresholdRuleValidationError { for (final ThresholdPredicate p : ThresholdPredicate.values()) if (p.op.equals(op)) return p; throw new ThresholdRuleValidationError("unsupported predicate: " + op); } /** * @param s * @return <code>s</code> if the string can be considered non empty. * @throws ThresholdRuleValidationError * when the string is empty. */ private static String requireNotNull(final String s) { if (s == null || s.isEmpty()) throw new ThresholdRuleValidationError("empty"); return s; } }
package org.wikidata.wdtk.dumpfiles; import java.math.BigDecimal; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.wikidata.wdtk.datamodel.implementation.DataObjectFactoryImpl; import org.wikidata.wdtk.datamodel.interfaces.Claim; import org.wikidata.wdtk.datamodel.interfaces.DataObjectFactory; import org.wikidata.wdtk.datamodel.interfaces.DatatypeIdValue; import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue; import org.wikidata.wdtk.datamodel.interfaces.GlobeCoordinatesValue; import org.wikidata.wdtk.datamodel.interfaces.ItemIdValue; import org.wikidata.wdtk.datamodel.interfaces.ItemDocument; import org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue; import org.wikidata.wdtk.datamodel.interfaces.NoValueSnak; import org.wikidata.wdtk.datamodel.interfaces.PropertyDocument; import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue; import org.wikidata.wdtk.datamodel.interfaces.QuantityValue; import org.wikidata.wdtk.datamodel.interfaces.Reference; import org.wikidata.wdtk.datamodel.interfaces.SiteLink; import org.wikidata.wdtk.datamodel.interfaces.Snak; import org.wikidata.wdtk.datamodel.interfaces.SomeValueSnak; import org.wikidata.wdtk.datamodel.interfaces.Statement; import org.wikidata.wdtk.datamodel.interfaces.StatementGroup; import org.wikidata.wdtk.datamodel.interfaces.StatementRank; import org.wikidata.wdtk.datamodel.interfaces.StringValue; import org.wikidata.wdtk.datamodel.interfaces.TimeValue; import org.wikidata.wdtk.datamodel.interfaces.Value; import org.wikidata.wdtk.datamodel.interfaces.ValueSnak; // IDEA introduce a verbose-flag to enable/disable logging // IDEA move MonolingualTextValue inlines into a method // TODO permanent: check if documentation is up-to-date /** * This class provides methods to convert dump-file JSON objects into * representations according to the WDTK data model. Since the converted JSON * normally belongs to the same domain, the base IRI is represented as an * attribute. * * @author Fredo Erxleben * */ public class JsonConverter { // TODO remove deprecated methods private static final String itemPrefix = "Q"; private static final String propertyPrefix = "P"; // TODO refactor to form KEY_FOO private static final String labelString = "label"; private static final String entityString = "entity"; private static final String descriptionString = "description"; private static final String aliasString = "alias"; private static final String datatypeString = "datatype"; private DataObjectFactory factory = new DataObjectFactoryImpl(); private String baseIri = ""; /** * Creates a new instance of the JsonConverter. For the <i>baseIri</i> see * also {@link org.wikidata.wdtk.datamodel.interfaces.ItemId} The item * prefix defaults to "Q". The property prefix defaults to "P". * * @param baseIri * the initial IRI to be used for the processed JSON. */ public JsonConverter(String baseIri) { this.setBaseIri(baseIri); } /** * Attempts to parse a given JSON object into an instance of * PropertyDocument. * * @param toConvert * the JSON object to convert. Must represent a property document * and therefore contain the keys "entity", "label", * "description", "aliases" and "datatype". * @return the PropertyDocument as described in the JSON. * @throws NullPointerException * if toConvert was null. * @throws JSONException * if the JSON object did not contain a key it should have had. */ PropertyDocument convertToPropertyDocument(JSONObject toConvert) throws JSONException { // sanity check if (toConvert == null) { throw new NullPointerException(); } if (toConvert.length() == 0) { // if the JSON object is empty throw new JSONException("The JSON to convert was empty"); } PropertyDocument result; // get the property id JSONArray jsonEntity = toConvert.getJSONArray(entityString); PropertyIdValue propertyId = this.getPropertyId(jsonEntity); // get the labels List<MonolingualTextValue> labels = this.getMltv(labelString, toConvert); // get the descriptions List<MonolingualTextValue> descriptions = this.getMltv(descriptionString, toConvert); // get the aliases List<MonolingualTextValue> aliases = this.getMltv(aliasString, toConvert); // get the datatype id String jsonDataTypeId = toConvert.getString(datatypeString); DatatypeIdValue datatypeId = this.getDataTypeId(jsonDataTypeId); result = this.factory.getPropertyDocument(propertyId, labels, descriptions, aliases, datatypeId); return result; } /** * Transforms a given string into a DatatypeIdValue. * * @param jsonDataTypeId * is the string to be converted. Must not be null. * @return the appropriate DatatypeIdValue-instance. */ private DatatypeIdValue getDataTypeId(String jsonDataTypeId) { assert jsonDataTypeId != null : "Given JSON datatype id was null"; return this.factory.getDatatypeIdValue(jsonDataTypeId); } /** * Converts a given JSON array into a PropertyIdValue. The appropriate * prefix for properties will be used. * * @param jsonEntity * is a JSON array denoting the property id. Must be of the form <br/> * ["property", <i>propertyID</i>]<br/> * Must not be null. * @return the appropriate PropertyIdValue-instance. * @throws JSONException * if the format requirements are not met. */ private PropertyIdValue getPropertyId(JSONArray jsonEntity) throws JSONException { assert jsonEntity != null : "Entity JSON was null."; assert jsonEntity.getString(0).equals("property") : "Entity JSON did not denote a property"; return this.getPropertyIdValue(jsonEntity.getInt(1)); } /** * Creates a PropertyIdValue from a given integer and the set property * prefix. * * @param intValue * is the integer id of the property. * @return a PropertyIdValue-instance. */ private PropertyIdValue getPropertyIdValue(int intValue) { String id = propertyPrefix + intValue; return this.factory.getPropertyIdValue(id, this.baseIri); } /** * Attempts to parse a given JSON object into an instance of ItemDocument. * * @param toConvert * the JSON object to convert. Must represent an item document * and therefore contain the keys "entity", "label", * "description", "aliases", "claims" and "links". * @return the ItemDocument as described in the JSON. * @throws NullPointerException * if toConvert was null. * @throws JSONException * if the JSON object did not contain a key it should have had. */ public ItemDocument convertToItemRecord(JSONObject toConvert) throws JSONException, NullPointerException { // sanity check if (toConvert == null) { throw new NullPointerException(); } if (toConvert.length() == 0) { // if the JSON object is empty throw new JSONException("The JSON to convert was empty"); } // get the item Id // NOTE that in old dumps the entity is not an array // but a string with appropriate prefix in lowercase ItemIdValue itemId; JSONArray jsonEntity = toConvert.optJSONArray(entityString); if (jsonEntity != null) { itemId = this.getItemId(jsonEntity); } else { String stringItemId = toConvert.getString(entityString).toUpperCase(); itemId = this.factory.getItemIdValue(stringItemId, baseIri); } // get the labels List<MonolingualTextValue> labels = this.getMltv(labelString, toConvert); // get the description List<MonolingualTextValue> descriptions = this.getMltv(descriptionString, toConvert); // get the aliases // NOTE empty aliases are an JSON array // non-empty aliases are JSON objects List<MonolingualTextValue> aliases = this.getMltv(aliasString, toConvert); // get the statements JSONArray jsonStatements = toConvert.getJSONArray("claims"); List<StatementGroup> statements = this.getStatements(jsonStatements, itemId); // get the site links JSONObject jsonLinks = toConvert.getJSONObject("links"); Map<String, SiteLink> siteLinks = this.getSiteLinks(jsonLinks); // now put it all together ItemDocument result = factory.getItemDocument(itemId, labels, descriptions, aliases, statements, siteLinks); return result; } /** * Converts a JSON array containing statements into a list of statement * groups a represented by the WDTK data model. * * @param jsonStatements * contains all the statements about an item. must consist of * JSON objects containing the keys "m", "q", "g", "refs" and * "rank" each. * * @return a list of statement groups as specified by the WDTK data model. * @throws JSONException * if one of the JSON objects in the array did not contain all * required keys. */ private List<StatementGroup> getStatements(JSONArray jsonStatements, EntityIdValue subject) throws JSONException { assert jsonStatements != null : "statements JSON array was null"; // structure is [{"m":object, "q":[], "g":string, "rank":int, // "q" => qualifiers // "m" => main snak // "g" => statement id List<StatementGroup> result = new LinkedList<StatementGroup>(); List<Statement> statementsFromJson = new LinkedList<Statement>(); // iterate over all the statements in the item and decompose them for (int i = 0; i < jsonStatements.length(); i++) { JSONObject currentStatement = jsonStatements.getJSONObject(i); // get a list of statements in the order they are in the JSON // get the claim Claim currentClaim = this.getClaim(currentStatement, subject); // get the references JSONArray jsonRefs = currentStatement.getJSONArray("refs"); List<? extends Reference> references = this.getReferences(jsonRefs); // get the statement rank int rankAsInt = currentStatement.getInt("rank"); StatementRank rank = this.getStatementRank(rankAsInt); // get the statement id String statementId = currentStatement.getString("g"); // combine into statement Statement statement = factory.getStatement(currentClaim, references, rank, statementId); statementsFromJson.add(statement); } // process the list of statements into a list of statement groups StatementGroupBuilder builder = new StatementGroupBuilder(this.factory); result = builder.buildFromStatementList(statementsFromJson); return result; } /** * Converts the given JSON array into a list of Reference-objects. A * reference is an array of reference statements which in turn are value * snaks. * * @param jsonReferences * is an JSON array of JSON arrays of value snaks * @return the appropriate List of references. */ private List<? extends Reference> getReferences(JSONArray jsonReferences) { // References are [singeRef] // singleRef are [refStatements] // refStatements are value snaks List<Reference> result = new LinkedList<>(); // process the single references for (int i = 0; i < jsonReferences.length(); i++) { try { JSONArray jsonSingleRef = jsonReferences.getJSONArray(i); List<ValueSnak> valueSnaks = new LinkedList<>(); // process the reference statements for (int j = 0; j < jsonSingleRef.length(); j++) { try { JSONArray jsonValueSnak = jsonSingleRef.getJSONArray(j); ValueSnak currentValueSnak = this .getValueSnak(jsonValueSnak); valueSnaks.add(currentValueSnak); } catch (JSONException e) { // skip over invalid references continue; } } Reference singleReference = factory.getReference(valueSnaks); result.add(singleReference); } catch (JSONException e) { // skip over invalid references continue; } } return result; } /** * Converts the given JSON array into a ValueSnak. * * @param jsonValueSnak * is a JSON array of the form <br/> * ["value", <i>propertyID</i>, <i>value type</i>, <i>value</i>] * where the structure of the value depends on the value type. * Must not be null. * @return a ValueSnak-instance according to the given JSON representation. * @throws JSONException * if the required format was not matched. */ private ValueSnak getValueSnak(JSONArray jsonValueSnak) throws JSONException { // a value snak is // ["value", propertyID, value-type, value] assert jsonValueSnak != null : "jsonValueSnak was null"; assert jsonValueSnak.getString(0).equals("value") : "given JSON was not a value snak"; ValueSnak result; // get the property id int intId = jsonValueSnak.getInt(1); PropertyIdValue propertyId = this.getPropertyIdValue(intId); // get the value String valueString = jsonValueSnak.getString(2); Value value; switch (valueString) { case "time": value = this.getTimeValue(jsonValueSnak.getJSONObject(3)); break; case "wikibase-entityid": value = this.getEntityIdValue(jsonValueSnak.getJSONObject(3)); break; case "string": value = this.getStringIdValue(jsonValueSnak.getString(3)); break; case "globecoordinate": value = this.getGlobeCoordinatesValue(jsonValueSnak .getJSONObject(3)); break; case "quantity": value = this.getQuantityValue(jsonValueSnak.getJSONObject(3)); break; default: throw new JSONException("Unknown value type " + valueString + "in value snak JSON"); } // put it all together result = this.factory.getValueSnak(propertyId, value); return result; } /** * Converts a JSON-objects into QuantityValues. * * @param jsonQuantityValue * is a JSON-object containing the labels "amount", "upperBound" * and "lowerBound". All other labels will be ignored. Must not * be null. * @return an appropriate QuantityValue-instance. * @throws JSONException */ private QuantityValue getQuantityValue(JSONObject jsonQuantityValue) throws JSONException { // example: // {"amount":"+34196", // "unit":"1", // "upperBound":"+34197", // "lowerBound":"+34195"} // NOTE ignore unit for now // it will be reviewed later BigDecimal numericValue = new BigDecimal( jsonQuantityValue.getString("amount")); BigDecimal lowerBound = new BigDecimal( jsonQuantityValue.getString("lowerBound")); BigDecimal upperBound = new BigDecimal( jsonQuantityValue.getString("upperBound")); QuantityValue result = this.factory.getQuantityValue(numericValue, lowerBound, upperBound); return result; } /** * Converts a JSON-object into a GlobeCordinatesValue. * * @param jsonGlobeCoordinate * is a JSON-object containing the labels "latitude", * "longitude", "precision" and "globe". All other labels will be * ignored. Must not be null. * @return an appropriate GlobeCoordinatesValue * @throws JSONException * if a required label was missing. */ private GlobeCoordinatesValue getGlobeCoordinatesValue( JSONObject jsonGlobeCoordinate) throws JSONException { assert jsonGlobeCoordinate != null : "Globe coordinate JSON was null"; // example: // {"latitude":51.835, // "longitude":10.785277777778, // "altitude":null, // "precision":0.00027777777777778, // NOTE as for now, ignore "altitude". // The key will be reviewed in the future. // NOTE the precision is denoted in float as a part of the degree // conversion into long necessary // NOTE sometimes the latitude and longitude are provided as int in // degree // convert latitude and longitude into nanodegrees // TODO check conversion for precision issues // TODO check conversion when handling older dump formats long latitude; long longitude; // try if the coordinates are already in int (with degree precision?) int invalid = 0xFFFFFF; // needed because the org.json parser handles // optInt() inconsistently int intLatitude = jsonGlobeCoordinate.optInt("latitude", invalid); if (intLatitude == invalid) { double doubleLatitude = jsonGlobeCoordinate.getDouble("latitude"); latitude = (long) (doubleLatitude * GlobeCoordinatesValue.PREC_DEGREE); } else { latitude = (long) intLatitude * GlobeCoordinatesValue.PREC_DEGREE; } int intLongitude = jsonGlobeCoordinate.optInt("longitude", invalid); if (intLongitude == invalid) { double doubleLongitude = jsonGlobeCoordinate.getDouble("longitude"); longitude = (long) (doubleLongitude * GlobeCoordinatesValue.PREC_DEGREE); } else { longitude = (long) intLongitude * GlobeCoordinatesValue.PREC_DEGREE; } // getting the precision // if the precision is available as double it needs to be converted // NOTE this is done by hand, since otherwise one would get rounding // errors // if the precision is available as int it needs to be multiplied with // PREC_DEGREE // also in older dumps the precision might be null // in this case the precision might default to PREC_DEGREE long precision; if (jsonGlobeCoordinate.isNull("precision")) { precision = GlobeCoordinatesValue.PREC_DEGREE; } else { int intPrecision = jsonGlobeCoordinate.optInt("precision", invalid); if (intPrecision == invalid || intPrecision == 0) { Double doublePrecision = jsonGlobeCoordinate .getDouble("precision"); // Yes you have to check all // possible representations since they do not equal // in their internal representation if (doublePrecision.equals(10)) { precision = GlobeCoordinatesValue.PREC_TEN_DEGREE; } else if (doublePrecision.equals(1.0)) { precision = GlobeCoordinatesValue.PREC_DEGREE; } else if (doublePrecision.equals(0.1)) { precision = GlobeCoordinatesValue.PREC_DECI_DEGREE; } else if (doublePrecision.equals(0.016666666666667)) { precision = GlobeCoordinatesValue.PREC_ARCMINUTE; } else if (doublePrecision.equals(0.01)) { precision = GlobeCoordinatesValue.PREC_CENTI_DEGREE; } else if (doublePrecision.equals(0.001)) { precision = GlobeCoordinatesValue.PREC_MILLI_DEGREE; } else if (doublePrecision.equals(0.00027777777777778) || doublePrecision.equals(2.7777777777778e-4)) { precision = GlobeCoordinatesValue.PREC_ARCSECOND; } else if (doublePrecision.equals(0.0001) || doublePrecision.equals(1.0e-4)) { precision = GlobeCoordinatesValue.PREC_HUNDRED_MICRO_DEGREE; } else if (doublePrecision.equals(0.00002777777777778) || doublePrecision.equals(2.7777777777778e-5)) { precision = GlobeCoordinatesValue.PREC_DECI_ARCSECOND; } else if (doublePrecision.equals(0.00001) || doublePrecision.equals(1.0e-5)) { precision = GlobeCoordinatesValue.PREC_TEN_MICRO_DEGREE; } else if (doublePrecision.equals(0.00000277777777778) || doublePrecision.equals(2.7777777777778e-6)) { precision = GlobeCoordinatesValue.PREC_CENTI_ARCSECOND; } else if (doublePrecision.equals(0.000001)) { precision = GlobeCoordinatesValue.PREC_MICRO_DEGREE; } else if (doublePrecision.equals(0.00000027777777778) || doublePrecision.equals(2.7777777777778e-7)) { precision = GlobeCoordinatesValue.PREC_MILLI_ARCSECOND; } else { throw new JSONException("Unknown precision " + doublePrecision + "in global coordinates."); } } else { precision = ((long) intPrecision) * GlobeCoordinatesValue.PREC_DEGREE; } } String globeIri = jsonGlobeCoordinate.getString("globe"); GlobeCoordinatesValue result = this.factory.getGlobeCoordinatesValue( latitude, longitude, precision, globeIri); return result; } /** * Acquires the StringValue for a given String. * * @param string * @return */ private StringValue getStringIdValue(String string) { assert string != null : "String to be converted to a StringValue was null"; // NOTE I decided against inlining, so // if the StringValue changes somehow in the future // one has only to change this method return this.factory.getStringValue(string); } /** * Converts a given JSON-object to an EntityIdValue. * * @param jsonObject * an JSON object denoting an entity id. It must contain the * labels "entity-type" and "numeric-id". * @return * @throws JSONException * if a required key was not available. */ private EntityIdValue getEntityIdValue(JSONObject jsonObject) throws JSONException { // example: // {"entity-type":"item", // "numeric-id":842256} // NOTE there be any other entity-type then "item" in later releases EntityIdValue result; String entityType = jsonObject.getString("entity-type"); // check the entity type switch (entityType) { case "item": result = this.getItemIdValue(jsonObject.getInt("numeric-id")); break; default: throw new JSONException("Unknown entity type " + entityType + " in entity id value JSON."); } return result; } /** * Creates a ItemIdValue from a given integer and the set item prefix. * * @param intValue * is the integer id of the item. * @return a ItemIdValue-instance. */ private ItemIdValue getItemIdValue(int intValue) { String id = itemPrefix + intValue; return this.factory.getItemIdValue(id, this.baseIri); } /** * Converts a JSON-object into a TimeValue. * * @param jsonTimeValue * is a JSON-object with the keys "time", "timezone", "before", * "after", "precision" and "calendarmodel". * @return the TimeValue as described by the JSON-object. * @throws JSONException * if a required label was missing. */ private TimeValue getTimeValue(JSONObject jsonTimeValue) throws JSONException { // example: // {"time":"+00000002012-06-30T00:00:00Z", // "timezone":0, // "before":0, // "after":0, // "precision":11, TimeValue result; // TODO include negative years in test // NOTE suggested regex is // "(?<!\\A)[\\-\\:TZ]" // if one woule prefer regex instead if substrings String stringTime = jsonTimeValue.getString("time"); // get the year long year = Long.parseLong(stringTime.substring(0, 12)); // get the month byte month = Byte.parseByte(stringTime.substring(13, 15)); // get the day byte day = Byte.parseByte(stringTime.substring(16, 18)); // get the hour byte hour = Byte.parseByte(stringTime.substring(19, 21)); // get the minute byte minute = Byte.parseByte(stringTime.substring(22, 24)); // get the second byte second = Byte.parseByte(stringTime.substring(25, 27)); // get the precision byte precision = (byte) jsonTimeValue.getInt("precision"); // get the tolerances int beforeTolerance = jsonTimeValue.getInt("before"); int afterTolerance = jsonTimeValue.getInt("after"); // get the timezone offset int timezoneOffset = jsonTimeValue.getInt("timezone"); // get the calendar model String calendarModel = jsonTimeValue.getString("calendarmodel"); result = this.factory.getTimeValue(year, month, day, hour, minute, second, precision, beforeTolerance, afterTolerance, timezoneOffset, calendarModel); return result; } /** * Transforms a statement rank from an integer representation to an * enumerated value as requested by the WDTK data model. <br/> * The number 0 maps to DEPRECATED. <br/> * The number 1 maps to NORMAL. <br/> * The number 2 maps to PREFERRED. <br/> * * To accommodate for possible other values that may occur any number below * 0 also maps to DEPRECATED and any number above 2 also maps to PREFERRED. * * @param intRank * the rank as integer. * @return an appropriate StatementRank-value */ private StatementRank getStatementRank(int intRank) { // this is the default case StatementRank result = StatementRank.NORMAL; if (intRank < 1) { result = StatementRank.DEPRECATED; } else if (intRank > 1) { result = StatementRank.PREFERRED; } return result; } /** * Gets the claim from a statement in JSON. A Claim consists out of the * EntityIdValue of the subject, the subjects main snak and its qualifiers. * * @param currentStatement * a JSON object representing a whole statement from which the * claim is to be extracted. * @return * @throws JSONException * when a required key was not found or the snak type could not * be identified. */ private Claim getClaim(JSONObject currentStatement, EntityIdValue subject) throws JSONException { // m: main snak // q: qualifiers // get the main snak JSONArray jsonMainSnak = currentStatement.getJSONArray("m"); Snak mainSnak = getSnak(jsonMainSnak); // get the qualifiers JSONArray jsonQualifiers = currentStatement.getJSONArray("q"); List<Snak> qualifiers = this.getQualifiers(jsonQualifiers); // build it together Claim result = this.factory.getClaim(subject, mainSnak, qualifiers); return result; } /** * Converts the given JSON array into a Snak. This might either be a * ValueSnak, NoValueSnak or SomeValueSnak. * * @param jsonMainSnak * is the JSON array to be converted. Must not be null. * @return A Snak corresponding to the given JSON array. * @throws JSONException * if the snack type could not determined. */ private Snak getSnak(JSONArray jsonMainSnak) throws JSONException { Snak result; switch (jsonMainSnak.getString(0)) { case "value": result = this.getValueSnak(jsonMainSnak); break; case "somevalue": result = this.getSomeValueSnak(jsonMainSnak); break; case "novalue": result = this.getNoValueSnak(jsonMainSnak); break; default: // could not determine snak type... throw new JSONException("Unknown snack type: " + jsonMainSnak.getString(0)); } return result; } /** * Converts a JSON array into a SomeValueSnak. * * @param jsonSomeValueSnak * is an JSON array that denotes a some-value snak. It has the * form<br/> * ["somevalue", <i>propertyID</i>] * * @return an appropriate SomeValueSnak-instance * @throws JSONException * if the format does not match the required one. */ private SomeValueSnak getSomeValueSnak(JSONArray jsonSomeValueSnak) throws JSONException { // example: // ["somevalue",22], where P22 is the property "father" assert jsonSomeValueSnak != null : "jsonSomeValueSnak was null."; assert jsonSomeValueSnak.getString(0).equals("somevalue") : "Argument was not a SomeValueSnak."; int intPropertyId = jsonSomeValueSnak.getInt(1); PropertyIdValue propertyId = this.getPropertyIdValue(intPropertyId); SomeValueSnak result = this.factory.getSomeValueSnak(propertyId); return result; } /** * Converts a JSON array into a NoValueSnak. * * @param jsonNoValueSnak * is an JSON array that denotes a no-value snak. It has the form<br/> * ["novalue", <i>propertyID</i>] * * @return an appropriate NoValueSnak-instance * @throws JSONException * if the format does not match the required one. */ private NoValueSnak getNoValueSnak(JSONArray jsonNoValueSnak) throws JSONException { // example: // ["novalue",40], where P40 is the property "children" assert jsonNoValueSnak != null : "jsonSomeValueSnak was null."; assert jsonNoValueSnak.getString(0).equals("novalue") : "Argument was not a SomeValueSnak."; int intPropertyId = jsonNoValueSnak.getInt(1); PropertyIdValue propertyId = this.getPropertyIdValue(intPropertyId); NoValueSnak result = this.factory.getNoValueSnak(propertyId); return result; } /** * Converts the qualifiers from a JSON array to a list of value snaks. * * @param jsonQualifiers * is a JSON array containing several snaks. * @return a list of snaks corresponding to the given JSON array. */ private List<Snak> getQualifiers(JSONArray jsonQualifiers) { // effectively a list of value snaks List<Snak> result = new LinkedList<Snak>(); for (int i = 0; i < jsonQualifiers.length(); i++) { try { JSONArray currentValueSnak = jsonQualifiers.getJSONArray(i); result.add(this.getSnak(currentValueSnak)); } catch (JSONException e) { // skip the snak on error continue; } } return result; } /** * Converts a JSON object into a mapping from site keys to * SiteLink-instances. * * @param jsonLinks * a JSON object representing the site links. * @return A mapping with a String representing a site key e.g. "enwiki" as * key and a SiteLink-object as value. * @throws JSONException */ private Map<String, SiteLink> getSiteLinks(JSONObject jsonLinks) throws JSONException { assert jsonLinks != null : "Link JSON object was null"; // links are siteKey:{"name":string,"badges":[string] } // the siteKey is the key for the returned map Map<String, SiteLink> result = new HashMap<String, SiteLink>(); @SuppressWarnings("unchecked") Iterator<String> linkIterator = jsonLinks.keys(); while (linkIterator.hasNext()) { String siteKey = linkIterator.next(); JSONObject currentLink = jsonLinks.getJSONObject(siteKey); String title = currentLink.getString("name"); JSONArray badgeArray = currentLink.getJSONArray("badges"); // convert badges to List<String> List<String> badges = new LinkedList<String>(); for (int i = 0; i < badgeArray.length(); i++) { badges.add(badgeArray.getString(i)); } // create the SiteLink instance SiteLink siteLink = factory.getSiteLink(title, siteKey, this.baseIri, badges); result.put(siteKey, siteLink); } return result; } /** * Constructs the item id of a JSON object denoting an item. * * @param jsonEntity * a JSON array containing information about the entity or * property. The array shoud have the structure ["item", itemId] * or ["property", propertyId]. * @return An item id value prefixed accordingly. * @throws JSONException * if the entity does not contain an "item"-entry or the entry * is not followed by an integer denoting the item id. */ private ItemIdValue getItemId(JSONArray jsonEntity) throws JSONException { assert jsonEntity != null : "Entity JSONArray was null"; assert jsonEntity.getString(0).equals("item") : "JSONArray did not denote an item id."; return this.getItemIdValue(jsonEntity.getInt(1)); } public String getBaseIri() { return baseIri; } /** * Converts a JSONObject into a list of mono-lingual text values. The object * to be converted is the value associated with the given key in the top * level object. So if there is a JSONObject <i>topLevel</i> and the key * "label" are given, only the JSONObject found in the <i>topLevel</i> under * the key "label" will be converted, not the whole <i>topLevel</i>. * * MLTV is the abbreviation for MonoLingualTextValue. * * @param key * is the key of the object to be converted in the topLevel. If * the key is not present or not an object an empty list will be * returned. * @param topLevel * is the JSONObject that contains the object to be converted * under a given key. * @return a list of extracted mono-lingual text values. Might be empty, but * not null. */ private List<MonolingualTextValue> getMltv(String key, JSONObject topLevel) { MltvHandler handler = new MltvHandler(this.factory); JSONObject toConvert = topLevel.optJSONObject(key); if (toConvert != null) { return handler.convertToMltv(toConvert); } return new LinkedList<>(); } /** * For the <i>baseIri</i> see also * {@link org.wikidata.wdtk.datamodel.interfaces.ItemId} * * @param baseIri * the new baseIRI to be set. If the given string is null, * nothing will be done. */ public void setBaseIri(String baseIri) { if (baseIri == null) return; this.baseIri = baseIri; } public String getItemPrefix() { return itemPrefix; } public String getPropertyPrefix() { return propertyPrefix; } }
package org.codehaus.xfire.aegis.type; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collection; import java.util.Map; import javax.xml.namespace.QName; import org.codehaus.xfire.XFireRuntimeException; import org.codehaus.xfire.aegis.type.basic.ArrayType; import org.codehaus.xfire.aegis.type.collection.CollectionType; import org.codehaus.xfire.aegis.type.collection.MapType; import org.codehaus.xfire.util.NamespaceHelper; import org.codehaus.xfire.util.ServiceUtils; public abstract class AbstractTypeCreator implements TypeCreator { protected TypeMapping tm; protected AbstractTypeCreator nextCreator; public TypeMapping getTypeMapping() { return tm; } public void setTypeMapping(TypeMapping typeMapping) { this.tm = typeMapping; } public void setNextCreator(AbstractTypeCreator creator) { this.nextCreator = creator; } protected TypeClassInfo createClassInfo(Field f) { TypeClassInfo info = createBasicClassInfo(f.getType()); info.setDescription("field " + f.getName() + " in " + f.getDeclaringClass()); return info; } protected TypeClassInfo createBasicClassInfo(Class typeClass) { TypeClassInfo info = new TypeClassInfo(); info.setDescription("class '" + typeClass.getName() + '\''); info.setTypeClass(typeClass); return info; } protected Type createTypeForClass(TypeClassInfo info) { Class javaType = info.getTypeClass(); if (info.getType() != null) { return createUserType(info); } if(javaType.isArray()) { return createArrayType(info); } else if(isMap(javaType)) { return createMapType(info); } else if(isCollection(javaType)) { return createCollectionType(info); } else if(isEnum(javaType)) { return createEnumType(info); } else { Type type = getTypeMapping().getType(javaType); if (type == null) { type = createDefaultType(info); } return type; } } protected Type createUserType(TypeClassInfo info) { try { Type type = (Type) info.getType().newInstance(); type.setSchemaType(createQName(info.getTypeClass())); type.setTypeClass(info.getTypeClass()); type.setTypeMapping(getTypeMapping()); return type; } catch (InstantiationException e) { throw new XFireRuntimeException("Couldn't instantiate type classs " + info.getType().getName(), e); } catch (IllegalAccessException e) { throw new XFireRuntimeException("Couldn't access type classs " + info.getType().getName(), e); } } protected QName createArrayQName(TypeClassInfo info) { Class javaType = info.getTypeClass(); return createCollectionQName(info, javaType.getComponentType()); } protected Type createArrayType(TypeClassInfo info) { ArrayType type = new ArrayType(); type.setSchemaType(createArrayQName(info)); type.setTypeClass(info.getTypeClass()); return type; } protected QName createQName(Class javaType) { String clsName = javaType.getName(); String ns = NamespaceHelper.makeNamespaceFromClassName(clsName, "http"); String localName = ServiceUtils.makeServiceNameFromClassName(javaType); return new QName(ns, localName); } protected boolean isCollection(Class javaType) { return Collection.class.isAssignableFrom(javaType); } protected Type createCollectionType(TypeClassInfo info, Class component) { CollectionType type = new CollectionType(component); type.setTypeMapping(getTypeMapping()); QName name = info.getTypeName(); if (name == null) name = createCollectionQName(info, component); type.setSchemaType(name); type.setTypeClass(info.getTypeClass()); return type; } protected Type createMapType(TypeClassInfo info) { QName schemaType = createMapQName(info); Class keyType = (Class) info.getKeyType(); Class valueType = (Class) info.getGenericType(); MapType type = new MapType(schemaType, keyType, valueType); type.setTypeMapping(getTypeMapping()); type.setTypeClass(info.getTypeClass()); return type; } protected QName createMapQName(TypeClassInfo info) { Class keyClass = (Class) info.getKeyType(); Class componentClass = (Class) info.getGenericType(); if(keyClass == null) { throw new XFireRuntimeException("Cannot create mapping for map, unspecified key type" + (info.getDescription() != null ? " for " + info.getDescription() : "")); } if(componentClass == null) { throw new XFireRuntimeException("Cannot create mapping for map, unspecified component type" + (info.getDescription() != null ? " for " + info.getDescription() : "")); } Type keyType = tm.getType(keyClass); if(keyType == null) { keyType = createType(keyClass); getTypeMapping().register(keyType); } Type componentType = tm.getType(componentClass); if(componentType == null) { componentType = createType(componentClass); getTypeMapping().register(componentType); } String name = keyType.getSchemaType().getLocalPart() + '2' + componentType.getSchemaType().getLocalPart() + "Map"; // TODO: Get namespace from XML? return new QName(tm.getEncodingStyleURI(), name); } protected boolean isMap(Class javaType) { return Map.class.isAssignableFrom(javaType); } public abstract TypeClassInfo createClassInfo(PropertyDescriptor pd); protected boolean isEnum(Class javaType) { return false; } public Type createEnumType(TypeClassInfo info) { return null; } public abstract Type createCollectionType(TypeClassInfo info); public abstract Type createDefaultType(TypeClassInfo info); protected QName createCollectionQName(TypeClassInfo info, Class componentType) { Class javaType = info.getTypeClass(); if(componentType == null) { throw new XFireRuntimeException("Cannot create mapping for " + javaType.getName() + ", unspecified component type" + (info.getDescription() != null ? " for " + info.getDescription() : "")); } Type type = tm.getType(componentType); if(type == null) { type = createType(componentType); getTypeMapping().register(type); } String ns; if(type.isComplex()) { ns = type.getSchemaType().getNamespaceURI(); } else { ns = tm.getEncodingStyleURI(); } String first = type.getSchemaType().getLocalPart().substring(0, 1); String last = type.getSchemaType().getLocalPart().substring(1); String localName = "ArrayOf" + first.toUpperCase() + last; return new QName(ns, localName); } public abstract TypeClassInfo createClassInfo(Method m, int index); /** * Create a Type for a Method parameter. * * @param m the method to create a type for * @param index The parameter index. If the index is less than zero, the return type is used. */ public Type createType(Method m, int index) { TypeClassInfo info = createClassInfo(m, index); info.setDescription((index == -1 ? "return type" : "parameter " + index) + " of method " + m.getName() + " in " + m.getDeclaringClass()); return createTypeForClass(info); } /** * Create type information for a PropertyDescriptor. * * @param pd the propertydescriptor */ public Type createType(PropertyDescriptor pd) { TypeClassInfo info = createClassInfo(pd); info.setDescription("property " + pd.getName()); return createTypeForClass(info); } /** * Create type information for a <code>Field</code>. * * @param f the field to create a type from */ public Type createType(Field f) { TypeClassInfo info = createClassInfo(f); info.setDescription("field " + f.getName() + " in " + f.getDeclaringClass()); return createTypeForClass(info); } public Type createType(Class clazz) { TypeClassInfo info = createBasicClassInfo(clazz); info.setDescription(clazz.toString()); return createTypeForClass(info); } public static class TypeClassInfo { Class typeClass; Object[] annotations; Object genericType; Object keyType; String mappedName; QName typeName; Class type; String description; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Object[] getAnnotations() { return annotations; } public void setAnnotations(Object[] annotations) { this.annotations = annotations; } public Object getGenericType() { return genericType; } public void setGenericType(Object genericType) { this.genericType = genericType; } public Object getKeyType() { return keyType; } public void setKeyType(Object keyType) { this.keyType = keyType; } public Class getTypeClass() { return typeClass; } public void setTypeClass(Class typeClass) { this.typeClass = typeClass; } public QName getTypeName() { return typeName; } public void setTypeName(QName name) { this.typeName = name; } public String getMappedName() { return mappedName; } public void setMappedName(String mappedName) { this.mappedName = mappedName; } public Class getType() { return type; } public void setType(Class type) { this.type = type; } } }
package com.xpn.xwiki.plugin.ldap; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.io.UnsupportedEncodingException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.novell.ldap.LDAPAttribute; import com.novell.ldap.LDAPAttributeSet; import com.novell.ldap.LDAPConnection; import com.novell.ldap.LDAPEntry; import com.novell.ldap.LDAPException; import com.novell.ldap.LDAPJSSESecureSocketFactory; import com.novell.ldap.LDAPSearchConstraints; import com.novell.ldap.LDAPSearchResults; import com.novell.ldap.LDAPSocketFactory; import com.xpn.xwiki.XWikiContext; import java.security.Security; /** * LDAP communication tool. * * @version $Id$ * @since 1.3 M2 */ public class XWikiLDAPConnection { /** * Logging tool. */ private static final Log LOG = LogFactory.getLog(XWikiLDAPConnection.class); /** * The LDAP connection. */ private LDAPConnection connection; /** * @return the {@link LDAPConnection}. */ public LDAPConnection getConnection() { return connection; } /** * Open a LDAP connection. * * @param ldapUserName the user name to connect to LDAP server. * @param password the password to connect to LDAP server. * @param context the XWiki context. * @return true if connection succeed, false otherwise. * @throws XWikiLDAPException error when trying to open connection. */ public boolean open(String ldapUserName, String password, XWikiContext context) throws XWikiLDAPException { XWikiLDAPConfig config = XWikiLDAPConfig.getInstance(); // open LDAP int ldapPort = config.getLDAPPort(context); String ldapHost = config.getLDAPParam("ldap_server", "localhost", context); String bindDNFormat = config.getLDAPParam("ldap_bind_DN", "{0}", context); String bindPasswordFormat = config.getLDAPParam("ldap_bind_pass", "{1}", context); Object[] arguments = {ldapUserName, password}; // allow to use the given user and password also as the LDAP bind user and password String bindDN = MessageFormat.format(bindDNFormat, arguments); String bindPassword = MessageFormat.format(bindPasswordFormat, arguments); boolean bind; if ("1".equals(config.getLDAPParam("ldap_ssl", "0", context))) { String keyStore = config.getLDAPParam("ldap_ssl.keystore", "", context); if (LOG.isDebugEnabled()) { LOG.debug("Connecting to LDAP using SSL"); } bind = open(ldapHost, ldapPort, bindDN, bindPassword, keyStore, true, context); } else { bind = open(ldapHost, ldapPort, bindDN, bindPassword, null, false, context); } return bind; } /** * Open LDAP connection. * * @param ldapHost the host of the server to connect to. * @param ldapPort the port of the server to connect to. * @param loginDN the user DN to connect to LDAP server. * @param password the password to connect to LDAP server. * @param pathToKeys the patch to SSL keystore to use. * @param ssl if true connect using SSL. * @param context the XWiki context. * @return true if the connection succeed, false otherwise. * @throws XWikiLDAPException error when trying to open connection. */ public boolean open(String ldapHost, int ldapPort, String loginDN, String password, String pathToKeys, boolean ssl, XWikiContext context) throws XWikiLDAPException { boolean succeed = false; int port = ldapPort; if (port <= 0) { port = ssl ? LDAPConnection.DEFAULT_SSL_PORT : LDAPConnection.DEFAULT_PORT; } try { if (ssl) { XWikiLDAPConfig config = XWikiLDAPConfig.getInstance(); // Dynamically set JSSE as a security provider Security.addProvider(config.getSecureProvider(context)); if (pathToKeys != null && pathToKeys.length() > 0) { // Dynamically set the property that JSSE uses to identify // the keystore that holds trusted root certificates System.setProperty("javax.net.ssl.trustStore", pathToKeys); // obviously unnecessary: sun default pwd = "changeit" // System.setProperty("javax.net.ssl.trustStorePassword", sslpwd); } LDAPSocketFactory ssf = new LDAPJSSESecureSocketFactory(); // Set the socket factory as the default for all future connections // LDAPConnection.setSocketFactory(ssf); // Note: the socket factory can also be passed in as a parameter // to the constructor to set it for this connection only. this.connection = new LDAPConnection(ssf); } else { this.connection = new LDAPConnection(); } connect(ldapHost, port); bind(loginDN, password); succeed = this.connection.isConnected() && this.connection.isConnectionAlive() && this.connection.isBound(); } catch (UnsupportedEncodingException e) { throw new XWikiLDAPException("LDAP bind failed with UnsupportedEncodingException.", e); } catch (LDAPException e) { throw new XWikiLDAPException("LDAP bind failed with LDAPException.", e); } return succeed; } /** * Connect to server. * * @param ldapHost the host of the server to connect to. * @param port the port of the server to connect to. * @throws LDAPException error when trying to connect. */ private void connect(String ldapHost, int port) throws LDAPException { if (LOG.isDebugEnabled()) { LOG.debug("Connection to LDAP server [" + ldapHost + ":" + port + "]"); } // connect to the server this.connection.connect(ldapHost, port); } /** * Bind to LDAP server. * * @param loginDN the user DN to connect to LDAP server. * @param password the password to connect to LDAP server. * @throws UnsupportedEncodingException error when converting provided password to UTF-8 table. * @throws LDAPException error when trying to bind. */ private void bind(String loginDN, String password) throws UnsupportedEncodingException, LDAPException { if (LOG.isDebugEnabled()) { LOG.debug("Binding to LDAP server with credentials login=[" + loginDN + "] password=[" + password + "]"); } // authenticate to the server this.connection.bind(LDAPConnection.LDAP_V3, loginDN, password.getBytes("UTF8")); } /** * Close LDAP connection. */ public void close() { try { if (this.connection != null) { this.connection.disconnect(); } } catch (LDAPException e) { if (LOG.isDebugEnabled()) { LOG.debug("LDAP close failed.", e); } } } /** * Check if provided password is correct provided users's password. * * @param userDN the user. * @param password the password. * @return true if the password is valid, false otherwise. */ public boolean checkPassword(String userDN, String password) { return checkPassword(userDN, password, "userPassword"); } /** * Check if provided password is correct provided users's password. * * @param userDN the user. * @param password the password. * @param passwordField the name of the LDAP field containing the password. * @return true if the password is valid, false otherwise. */ public boolean checkPassword(String userDN, String password, String passwordField) { try { LDAPAttribute attribute = new LDAPAttribute(passwordField, password); return this.connection.compare(userDN, attribute); } catch (LDAPException e) { if (e.getResultCode() == LDAPException.NO_SUCH_OBJECT) { if (LOG.isDebugEnabled()) { LOG.debug("Unable to locate user_dn:" + userDN, e); } } else if (e.getResultCode() == LDAPException.NO_SUCH_ATTRIBUTE) { if (LOG.isDebugEnabled()) { LOG.debug("Unable to verify password because userPassword attribute not found.", e); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Unable to verify password", e); } } } return false; } /** * Execute a LDAP search query. * * @param baseDN the root DN where to search. * @param query the LDAP query. * @param attr the attributes names of values to return. * @param ldapScope {@link LDAPConnection#SCOPE_SUB} oder {@link LDAPConnection#SCOPE_BASE}. * @return the found LDAP attributes. */ public List<XWikiLDAPSearchAttribute> searchLDAP(String baseDN, String query, String[] attr, int ldapScope) { List<XWikiLDAPSearchAttribute> searchAttributeList = null; LDAPSearchResults searchResults = null; try { LDAPSearchConstraints cons = new LDAPSearchConstraints(); cons.setTimeLimit(1000); if (LOG.isDebugEnabled()) { LOG.debug("LDAP search: baseDN=[" + baseDN + "] query=[" + query + "] attr=[" + Arrays.asList(attr) + "] ldapScope=[" + ldapScope + "]"); } // filter return all attributes return attrs and values time out value searchResults = this.connection.search(baseDN, ldapScope, query, attr, false, cons); if (!searchResults.hasMore()) { return null; } LDAPEntry nextEntry = searchResults.next(); String foundDN = nextEntry.getDN(); searchAttributeList = new ArrayList<XWikiLDAPSearchAttribute>(); searchAttributeList.add(new XWikiLDAPSearchAttribute("dn", foundDN)); LDAPAttributeSet attributeSet = nextEntry.getAttributeSet(); ldapToXWikiAttribute(searchAttributeList, attributeSet); } catch (LDAPException e) { if (LOG.isDebugEnabled()) { LOG.debug("LDAP Search failed", e); } } finally { if (searchResults != null) { try { this.connection.abandon(searchResults); } catch (LDAPException e) { if (LOG.isDebugEnabled()) { LOG.debug("LDAP Search clean up failed", e); } } } } if (LOG.isDebugEnabled()) { LOG.debug("LDAP search found attributes: " + searchAttributeList); } return searchAttributeList; } /** * Fill provided <code>searchAttributeList</code> with provided LDAP attributes. * * @param searchAttributeList the XWiki attributes. * @param attributeSet the LDAP attributes. */ protected void ldapToXWikiAttribute(List<XWikiLDAPSearchAttribute> searchAttributeList, LDAPAttributeSet attributeSet) { for (Object attributeItem : attributeSet) { LDAPAttribute attribute = (LDAPAttribute) attributeItem; String attributeName = attribute.getName(); if (LOG.isDebugEnabled()) { LOG.debug(" - values for attribute \"" + attributeName + "\""); } Enumeration allValues = attribute.getStringValues(); if (allValues != null) { while (allValues.hasMoreElements()) { String value = (String) allValues.nextElement(); if (LOG.isDebugEnabled()) { LOG.debug(" |- [" + value + "]"); } searchAttributeList.add(new XWikiLDAPSearchAttribute(attributeName, value)); } } } } }
package com.nutiteq.layers.raster; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.gdal.gdal.Band; import org.gdal.gdal.ColorTable; import org.gdal.gdal.Dataset; import org.gdal.gdal.gdal; import org.gdal.gdalconst.gdalconst; import org.gdal.gdalconst.gdalconstConstants; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.nutiteq.MapView; import com.nutiteq.components.Components; import com.nutiteq.components.Envelope; import com.nutiteq.components.MapTile; import com.nutiteq.log.Log; import com.nutiteq.tasks.FetchTileTask; import com.nutiteq.utils.Utils; public class GdalFetchTileTask extends FetchTileTask{ private MapTile tile; private long tileIdOffset; private Envelope requestedBounds; private Dataset hDataset; private Envelope dataBounds; private MapView mapView; private static final int TILE_SIZE = 256; private static final float BRIGHTNESS = 2.0f; // used for grayscale only public GdalFetchTileTask(MapTile tile, Components components, Envelope requestedBounds, long tileIdOffset, Dataset hDataset, Envelope dataBounds, MapView mapView) { super(tile, components, tileIdOffset); this.tile = tile; this.tileIdOffset = tileIdOffset; this.requestedBounds = requestedBounds; this.hDataset=hDataset; this.dataBounds = dataBounds; this.components = components; this.mapView = mapView; } @Override public void run() { super.run(); finished(getData(requestedBounds, components, tileIdOffset, hDataset, dataBounds)); } @Override protected void finished(byte[] data) { super.finished(data); if (data == null) { Log.error(getClass().getName() + " : No data."); } else { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inScaled = false; Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts); if (bitmap == null) { // If the compressed image is corrupt, delete it Log.error(getClass().getName() + " : Failed to decode the image."); } else { // Add the compressed image to persistentCache components.persistentCache.add(tileIdOffset + tile.id, data); // Add the compressed image to compressedMemoryCache components.compressedMemoryCache.add(tileIdOffset + tile.id, data); // If not corrupt, add to the textureMemoryCache components.textureMemoryCache.add(tileIdOffset + tile.id, bitmap); mapView.requestRender(); } } } public static byte[] getData(Envelope requestedBounds, Components components, long tileIdOffset, Dataset hDataset, Envelope dataBounds) { long time = System.nanoTime(); // 1. calculate pixel ranges of source image with geotransformation double[] adfGeoTransform = new double[6]; hDataset.GetGeoTransform(adfGeoTransform); // Log.debug("geoTransform:" + Arrays.toString(adfGeoTransform)); int[] pixelsSrcMin = convertGeoLocationToPixelLocation( requestedBounds.getMinX(), requestedBounds.getMaxY(), adfGeoTransform); Log.debug("minxy:" + pixelsSrcMin[0] + " " + pixelsSrcMin[1]); int[] pixelsSrcMax = convertGeoLocationToPixelLocation( requestedBounds.getMaxX(), requestedBounds.getMinY(), adfGeoTransform); Log.debug("maxxy:" + pixelsSrcMax[0] + " " + pixelsSrcMax[1]); // tile dimensions int xSizeBuf = TILE_SIZE; int ySizeBuf = TILE_SIZE; int xOffsetBuf = 0; int yOffsetBuf = 0; int xMaxBuf = TILE_SIZE; int yMaxBuf = TILE_SIZE; float xScale = (pixelsSrcMax[0]-pixelsSrcMin[0]) / (float)xSizeBuf; // unit: srcPix/screenPix float yScale = (pixelsSrcMax[1]-pixelsSrcMin[1]) / (float)ySizeBuf; // 3. handle border tiles which have only partial data if(pixelsSrcMax[0] > hDataset.getRasterXSize()){ // x over real size, reduce both buffer and loaded data proportionally xMaxBuf = (int) ((hDataset.getRasterXSize()- pixelsSrcMin[0]) / xScale); xSizeBuf = xMaxBuf; pixelsSrcMax[0] = hDataset.getRasterXSize(); Log.debug ("adjusted maxxy xSizeBuf=xMaxBuf to "+xSizeBuf+" pixelsMax "+pixelsSrcMax[0]); } if(pixelsSrcMax[1] > hDataset.getRasterYSize()){ // y over real size, reduce both buffer and loaded data proportionally yMaxBuf = (int) ((hDataset.getRasterYSize()- pixelsSrcMin[1]) / yScale); ySizeBuf = yMaxBuf; pixelsSrcMax[1] = hDataset.getRasterYSize(); Log.debug ("adjusted maxxy ySizeBuf=yMaxBuf to "+ySizeBuf+" pixelsMax "+pixelsSrcMax[1]); } if(pixelsSrcMin[0] < 0){ // x below 0, reduce both buffer and loaded data proportionally xOffsetBuf = (int) - (pixelsSrcMin[0] / xScale); xSizeBuf -= xOffsetBuf; pixelsSrcMin[0] = 0; Log.debug ("adjusted neg maxxy xSizeBuf to "+xSizeBuf+" pixelsSrcMax "+pixelsSrcMax[0]+" offset "+xOffsetBuf); } if(pixelsSrcMin[1] < 0){ // y below 0, reduce both buffer and loaded data proportionally yOffsetBuf = (int) - (pixelsSrcMin[1] / yScale); ySizeBuf -= yOffsetBuf; pixelsSrcMin[1] = 0; Log.debug ("adjusted neg maxxy ySizeBuf to "+ySizeBuf+" pixelsMax "+pixelsSrcMax[1]+" offset "+yOffsetBuf); } if(xSizeBuf<0 || ySizeBuf<0){ Log.debug("negative tile size, probably out of area"); return null; } // 4. Read data int xSizeData = (pixelsSrcMax[0] - pixelsSrcMin[0]); int ySizeData = (pixelsSrcMax[1] - pixelsSrcMin[1]); // Log.debug("xy size:" + xSizeData + "x" + ySizeData); int[] tileData = new int[TILE_SIZE * TILE_SIZE]; for (int iBand = 0; iBand < hDataset.getRasterCount(); iBand++) { Band band = hDataset.GetRasterBand(iBand+1); // TODO jaak: it could be 8 times (bits2bytes) too large in some(?) cases byte[] byteBuffer = new byte[gdal .GetDataTypeSize(band.getDataType()) * xSizeBuf * ySizeBuf]; Log.debug(String.format("reading pixels %d %d dataSize %d %d bufSize %d %d pixelBits %d dataType %d", pixelsSrcMin[0], pixelsSrcMin[1], xSizeData, ySizeData, xSizeBuf, ySizeBuf,gdal .GetDataTypeSize(band.getDataType()),band.getDataType())); // read data to byte array int res = band.ReadRaster(pixelsSrcMin[0], pixelsSrcMin[1], xSizeData, ySizeData, xSizeBuf, ySizeBuf, band.getDataType(), byteBuffer); if (res == gdalconstConstants.CE_Failure) { Log.error("error reading raster"); return null; } Log.debug("gdalfetchtile time for reading band " + iBand+ ": " + (System.nanoTime() - time) / 1000000 + " ms"); // copy colortable to Java array for faster access int colorType = band.GetRasterColorInterpretation(); ColorTable ct = band.GetRasterColorTable(); int[] colorTable = null; int numColors = 0; if(ct != null){ numColors = ct.GetCount(); colorTable = new int[numColors]; for (int i = 1; i < numColors; i++) { colorTable[i] = ct.GetColorEntry(i); } } int pixelSizeBits=8; // bits if(gdal.GetDataTypeSize(band.getDataType()) == 8){ // single byte - GDT_Byte usually pixelSizeBits = 8; }else if(gdal.GetDataTypeSize(band.getDataType()) == 16){ // 2 bytes - e.g. GDT_UInt16 pixelSizeBits = 16; } // TODO: more bytes? // value range Double[] pass1 = new Double[1], pass2 = new Double[1]; band.GetMinimum(pass1); // minimum ignored now band.GetMaximum(pass2); double bandValueMax = pass2[0]; int val = 0; int decoded = 0; // copy data to tile buffer tileData, and apply color table or combine bands for (int y = 0; y < TILE_SIZE; y++) { for (int x = 0; x < TILE_SIZE; x++) { if(x >= xOffsetBuf && y >= yOffsetBuf && x<=xMaxBuf && y<=yMaxBuf){ switch (pixelSizeBits){ case 8: val = Utils.unsigned(byteBuffer[((y-yOffsetBuf) * xSizeBuf) + (x-xOffsetBuf)]); break; case 16: // assume little endian val = Utils.unsigned(byteBuffer[(((y-yOffsetBuf) * xSizeBuf) + (x-xOffsetBuf))*2]) | (Utils.unsigned(byteBuffer[(((y-yOffsetBuf) * xSizeBuf) + (x-xOffsetBuf))*2 + 1]) << 8); break; } // decode color // 1) if indexed color if(colorType == gdalconst.GCI_PaletteIndex && colorTable != null){ if(val<numColors && val>=0){ decoded = colorTable[val]; }else{ // no colortable match found value, should not happen decoded = android.graphics.Color.CYAN & 0x88ffffff; Log.debug("no colortable found for value "+val); } // 2) ARGB bands to int }else if (colorType == gdalconst.GCI_AlphaBand){ decoded = (int) val & 0xff << 24; }else if(colorType == gdalconst.GCI_RedBand){ decoded = ((int) val & 0xff) << 16; }else if (colorType == gdalconst.GCI_GreenBand){ decoded = ((int) val & 0xff) << 8; }else if (colorType == gdalconst.GCI_BlueBand){ decoded = (int) val & 0xff; }else if (colorType == gdalconst.GCI_GrayIndex){ // normalize to single byte first // apply brightness, you may want to add pixel value adjustments: histogram modifications, contrast etc here val = (int)((val * 255.0f) / bandValueMax * BRIGHTNESS); decoded = (((int) val & 0xff) << 16 | ((int) val & 0xff) << 8 | (int) val & 0xff); } // TODO Handle other color schemas: RGB in one band etc. Test data needed // following forces alpha=FF for the case where alphaband is missing. Better solution needed to support dataset what really has alpha tileData[y * TILE_SIZE + x] |= decoded | 0xFF000000; }else{ // outside of tile bounds. Normally keep transparent, tint green just for debugging //tileData[y * TILE_SIZE + x] = android.graphics.Color.GREEN & 0x88ffffff; } } } } // loop for over bands // Log.debug("gdalfetchtile time = " + (System.nanoTime() - time) // / 1000000 + " ms"); // finally compress bitmap as PNG Bitmap bitmap = Bitmap.createBitmap(tileData, 256, 256, Bitmap.Config.ARGB_8888); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 90, bos); try { bos.close(); } catch (IOException e) { e.printStackTrace(); } Log.debug("finising gdalfetchtile total time = " + (System.nanoTime() - time) / 1000000 + " ms"); return bos.toByteArray(); } private static int[] convertGeoLocationToPixelLocation(double xGeo, double yGeo, double[] g) { int xPixel = 0, yPixel = 0; if (g[2] == 0) { xPixel = (int) ((xGeo - g[0]) / g[1]); yPixel = (int) ((yGeo - g[3] - xPixel * g[4]) / g[5]); } else { xPixel = (int) ((yGeo * g[2] - xGeo * g[5] + g[0] * g[5] - g[2] * g[3]) / (g[2] * g[4] - g[1] * g[5])); yPixel = (int) ((xGeo - g[0] - xPixel * g[1]) / g[2]); } return new int[] { xPixel, yPixel }; } }
package com.nutiteq.layers.raster; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.gdal.gdal.Band; import org.gdal.gdal.ColorTable; import org.gdal.gdal.Dataset; import org.gdal.gdal.gdal; import org.gdal.gdalconst.gdalconst; import org.gdal.gdalconst.gdalconstConstants; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.nutiteq.MapView; import com.nutiteq.components.Components; import com.nutiteq.components.Envelope; import com.nutiteq.components.MapTile; import com.nutiteq.log.Log; import com.nutiteq.tasks.FetchTileTask; import com.nutiteq.utils.Utils; public class GdalFetchTileTask extends FetchTileTask{ private MapTile tile; private long tileIdOffset; private Envelope requestedBounds; private Dataset hDataset; private Envelope dataBounds; private MapView mapView; private static final int TILE_SIZE = 256; private static final float BRIGHTNESS = 1.0f; // used for grayscale only public GdalFetchTileTask(MapTile tile, Components components, Envelope requestedBounds, long tileIdOffset, Dataset hDataset, Envelope dataBounds, MapView mapView) { super(tile, components, tileIdOffset); this.tile = tile; this.tileIdOffset = tileIdOffset; this.requestedBounds = requestedBounds; this.hDataset=hDataset; this.dataBounds = dataBounds; this.components = components; this.mapView = mapView; } @Override public void run() { super.run(); finished(getData(requestedBounds, components, tileIdOffset, hDataset, dataBounds)); } @Override protected void finished(byte[] data) { if (data == null) { Log.error(getClass().getName() + " : No data."); } else { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inScaled = false; Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts); if (bitmap == null) { // If the compressed image is corrupt, delete it Log.error(getClass().getName() + " : Failed to decode the image."); } else { // Add the compressed image to persistentCache components.persistentCache.add(tileIdOffset + tile.id, data); // Add the compressed image to compressedMemoryCache components.compressedMemoryCache.add(tileIdOffset + tile.id, data); // If not corrupt, add to the textureMemoryCache components.textureMemoryCache.add(tileIdOffset + tile.id, bitmap); mapView.requestRender(); } } } public static byte[] getData(Envelope requestedBounds, Components components, long tileIdOffset, Dataset hDataset, Envelope dataBounds) { long time = System.nanoTime(); // 1. calculate pixel ranges of source image with geotransformation double[] adfGeoTransform = new double[6]; hDataset.GetGeoTransform(adfGeoTransform); // Log.debug("geoTransform:" + Arrays.toString(adfGeoTransform)); int[] pixelsSrcMin = convertGeoLocationToPixelLocation( requestedBounds.getMinX(), requestedBounds.getMaxY(), adfGeoTransform); Log.debug("minxy:" + pixelsSrcMin[0] + " " + pixelsSrcMin[1]); int[] pixelsSrcMax = convertGeoLocationToPixelLocation( requestedBounds.getMaxX(), requestedBounds.getMinY(), adfGeoTransform); Log.debug("maxxy:" + pixelsSrcMax[0] + " " + pixelsSrcMax[1]); // tile dimensions int xSizeBuf = TILE_SIZE; int ySizeBuf = TILE_SIZE; int xOffsetBuf = 0; int yOffsetBuf = 0; int xMaxBuf = TILE_SIZE; int yMaxBuf = TILE_SIZE; float xScale = (pixelsSrcMax[0]-pixelsSrcMin[0]) / (float)xSizeBuf; // unit: srcPix/screenPix float yScale = (pixelsSrcMax[1]-pixelsSrcMin[1]) / (float)ySizeBuf; // 3. handle border tiles which have only partial data if(pixelsSrcMax[0] > hDataset.getRasterXSize()){ // x over real size, reduce both buffer and loaded data proportionally xMaxBuf = (int) ((hDataset.getRasterXSize()- pixelsSrcMin[0]) / xScale); xSizeBuf = xMaxBuf; pixelsSrcMax[0] = hDataset.getRasterXSize(); Log.debug ("adjusted maxxy xSizeBuf=xMaxBuf to "+xSizeBuf+" pixelsMax "+pixelsSrcMax[0]); } if(pixelsSrcMax[1] > hDataset.getRasterYSize()){ // y over real size, reduce both buffer and loaded data proportionally yMaxBuf = (int) ((hDataset.getRasterYSize()- pixelsSrcMin[1]) / yScale); ySizeBuf = yMaxBuf; pixelsSrcMax[1] = hDataset.getRasterYSize(); Log.debug ("adjusted maxxy ySizeBuf=yMaxBuf to "+ySizeBuf+" pixelsMax "+pixelsSrcMax[1]); } if(pixelsSrcMin[0] < 0){ // x below 0, reduce both buffer and loaded data proportionally xOffsetBuf = (int) - (pixelsSrcMin[0] / xScale); xSizeBuf -= xOffsetBuf; pixelsSrcMin[0] = 0; Log.debug ("adjusted neg maxxy xSizeBuf to "+xSizeBuf+" pixelsSrcMax "+pixelsSrcMax[0]+" offset "+xOffsetBuf); } if(pixelsSrcMin[1] < 0){ // y below 0, reduce both buffer and loaded data proportionally yOffsetBuf = (int) - (pixelsSrcMin[1] / yScale); ySizeBuf -= yOffsetBuf; pixelsSrcMin[1] = 0; Log.debug ("adjusted neg maxxy ySizeBuf to "+ySizeBuf+" pixelsMax "+pixelsSrcMax[1]+" offset "+yOffsetBuf); } if(xSizeBuf<0 || ySizeBuf<0){ Log.debug("negative tile size, probably out of area"); return null; } // 4. Read data int xSizeData = (pixelsSrcMax[0] - pixelsSrcMin[0]); int ySizeData = (pixelsSrcMax[1] - pixelsSrcMin[1]); // Log.debug("xy size:" + xSizeData + "x" + ySizeData); int[] tileData = new int[TILE_SIZE * TILE_SIZE]; for (int iBand = 0; iBand < hDataset.getRasterCount(); iBand++) { Band band = hDataset.GetRasterBand(iBand+1); // TODO jaak: it could be 8 times (bits2bytes) too large in some(?) cases byte[] byteBuffer = new byte[gdal .GetDataTypeSize(band.getDataType()) * xSizeBuf * ySizeBuf]; Log.debug(String.format("reading pixels %d %d dataSize %d %d bufSize %d %d pixelBits %d dataType %d", pixelsSrcMin[0], pixelsSrcMin[1], xSizeData, ySizeData, xSizeBuf, ySizeBuf,gdal .GetDataTypeSize(band.getDataType()),band.getDataType())); // read data to byte array int res = band.ReadRaster(pixelsSrcMin[0], pixelsSrcMin[1], xSizeData, ySizeData, xSizeBuf, ySizeBuf, band.getDataType(), byteBuffer); if (res == gdalconstConstants.CE_Failure) { Log.error("error reading raster"); return null; } Log.debug("gdalfetchtile time for reading band " + iBand+ ": " + (System.nanoTime() - time) / 1000000 + " ms"); // copy colortable to Java array for faster access int colorType = band.GetRasterColorInterpretation(); // quick check if colortype is implemented below if(!(colorType == gdalconst.GCI_PaletteIndex || colorType == gdalconst.GCI_RedBand || colorType == gdalconst.GCI_GreenBand || colorType == gdalconst.GCI_BlueBand || colorType == gdalconst.GCI_GrayIndex || colorType == gdalconst.GCI_AlphaBand)) { Log.debug("colorType "+colorType+" not implemented, skipping band"); break; } ColorTable ct = band.GetRasterColorTable(); int[] colorTable = null; int numColors = 0; if(ct != null){ numColors = ct.GetCount(); colorTable = new int[numColors]; for (int i = 1; i < numColors; i++) { colorTable[i] = ct.GetColorEntry(i); } } int pixelSizeBits=8; // bits if(gdal.GetDataTypeSize(band.getDataType()) == 8){ // single byte - GDT_Byte usually pixelSizeBits = 8; }else if(gdal.GetDataTypeSize(band.getDataType()) == 16){ // 2 bytes - e.g. GDT_UInt16 pixelSizeBits = 16; } // TODO: more bytes? // value range Double[] pass1 = new Double[1], pass2 = new Double[1]; band.GetMinimum(pass1); // minimum ignored now band.GetMaximum(pass2); Double bandValueMax = (double) (1<<pixelSizeBits); if(pass2 != null && pass2[0] != null){ bandValueMax = pass2[0]; } int val = 0; int decoded = 0; // copy data to tile buffer tileData, and apply color table or combine bands int valMin = Integer.MAX_VALUE; int valMax = Integer.MIN_VALUE; for (int y = 0; y < TILE_SIZE; y++) { for (int x = 0; x < TILE_SIZE; x++) { if(x >= xOffsetBuf && y >= yOffsetBuf && x<=xMaxBuf && y<=yMaxBuf){ switch (pixelSizeBits){ case 8: val = Utils.unsigned(byteBuffer[((y-yOffsetBuf) * xSizeBuf) + (x-xOffsetBuf)]); break; case 16: // assume little endian val = Utils.unsigned(byteBuffer[(((y-yOffsetBuf) * xSizeBuf) + (x-xOffsetBuf))*2]) | (Utils.unsigned(byteBuffer[(((y-yOffsetBuf) * xSizeBuf) + (x-xOffsetBuf))*2 + 1]) << 8); break; } valMin=Math.min(valMin, val); valMax=Math.max(valMax, val); // decode color // 1) if indexed color if(colorType == gdalconst.GCI_PaletteIndex && colorTable != null){ if(val<numColors && val>=0){ decoded = colorTable[val]; }else{ // no colortable match found value, should not happen decoded = android.graphics.Color.CYAN & 0x88ffffff; Log.debug("no colortable found for value "+val); } // 2) ARGB direct color bands to int ARGB }else{ if (colorType == gdalconst.GCI_AlphaBand){ decoded = (int) val & 0xff << 24; }else if(colorType == gdalconst.GCI_RedBand){ decoded = ((int) val & 0xff) << 16; }else if (colorType == gdalconst.GCI_GreenBand){ decoded = ((int) val & 0xff) << 8; }else if (colorType == gdalconst.GCI_BlueBand){ decoded = (int) val & 0xff; }else if (colorType == gdalconst.GCI_GrayIndex){ // normalize to single byte value range if multibyte // apply brightness, you may want to add pixel value adjustments: histogram modifications, contrast etc here if(pixelSizeBits > 8){ val = (int)((val * 255.0f) / bandValueMax * BRIGHTNESS); } decoded = (((int) val & 0xff) << 16 | ((int) val & 0xff) << 8 | (int) val & 0xff); } } // TODO Handle other color schemas: RGB in one band etc. Test data needed // following forces alpha=FF for the case where alphaband is missing. Better solution needed to support dataset what really has alpha tileData[y * TILE_SIZE + x] |= decoded | 0xFF000000; }else{ // outside of tile bounds. Normally keep transparent, tint green just for debugging //tileData[y * TILE_SIZE + x] = android.graphics.Color.GREEN & 0x88ffffff; } } } Log.debug("band "+iBand+". min="+valMin+" max="+valMax); } // loop for over bands // Log.debug("gdalfetchtile time = " + (System.nanoTime() - time) // / 1000000 + " ms"); // finally compress bitmap as PNG Bitmap bitmap = Bitmap.createBitmap(tileData, 256, 256, Bitmap.Config.ARGB_8888); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 90, bos); try { bos.close(); } catch (IOException e) { e.printStackTrace(); } Log.debug("finising gdalfetchtile total time = " + (System.nanoTime() - time) / 1000000 + " ms"); return bos.toByteArray(); } private static int[] convertGeoLocationToPixelLocation(double xGeo, double yGeo, double[] g) { int xPixel = 0, yPixel = 0; if (g[2] == 0) { xPixel = (int) ((xGeo - g[0]) / g[1]); yPixel = (int) ((yGeo - g[3] - xPixel * g[4]) / g[5]); } else { xPixel = (int) ((yGeo * g[2] - xGeo * g[5] + g[0] * g[5] - g[2] * g[3]) / (g[2] * g[4] - g[1] * g[5])); yPixel = (int) ((xGeo - g[0] - xPixel * g[1]) / g[2]); } return new int[] { xPixel, yPixel }; } }
package net.somethingdreadful.MAL.adapters; import android.content.Context; import android.graphics.Color; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.crashlytics.android.Crashlytics; import com.squareup.picasso.Picasso; import net.somethingdreadful.MAL.DateTools; import net.somethingdreadful.MAL.R; import net.somethingdreadful.MAL.RoundedTransformation; import net.somethingdreadful.MAL.Theme; import net.somethingdreadful.MAL.account.AccountService; import net.somethingdreadful.MAL.api.BaseModels.Profile; import org.apache.commons.lang3.text.WordUtils; import java.util.ArrayList; import java.util.Collection; public class FriendsGridviewAdapter<T> extends ArrayAdapter<T> { private Context context; private ArrayList<Profile> list; public FriendsGridviewAdapter(Context context, ArrayList<Profile> list) { super(context, R.layout.record_friends_gridview); this.context = context; this.list = list; } public View getView(int position, View view, ViewGroup parent) { final Profile record = (list.get(position)); ViewHolder viewHolder; if (view == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.record_friends_gridview, parent, false); viewHolder = new ViewHolder(); viewHolder.username = (TextView) view.findViewById(R.id.userName); viewHolder.last_online = (TextView) view.findViewById(R.id.lastonline); viewHolder.avatar = (ImageView) view.findViewById(R.id.profileImg); if (Theme.darkTheme) { viewHolder.username.setTextColor(context.getResources().getColor(R.color.text_dark)); Theme.setBackground(context, view); } if (!AccountService.isMAL()) viewHolder.last_online.setText(context.getString(R.string.unknown)); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } try { String username = record.getUsername(); viewHolder.username.setText(WordUtils.capitalize(username)); if (Profile.isDeveloper(username)) viewHolder.username.setTextColor(context.getResources().getColor(R.color.primary)); //Developer else viewHolder.username.setTextColor(Theme.darkTheme ? context.getResources().getColor(R.color.text_dark) : Color.parseColor("#212121")); if (record.getDetails() != null && record.getDetails().getLastOnline() != null) { String last_online = record.getDetails().getLastOnline(); last_online = DateTools.parseDate(last_online, true); viewHolder.last_online.setText(last_online.equals("") ? record.getDetails().getLastOnline() : last_online); } Picasso.with(context).load(record.getImageUrl()) .error(R.drawable.cover_error) .placeholder(R.drawable.cover_loading) .transform(new RoundedTransformation(record.getUsername())) .into(viewHolder.avatar); } catch (Exception e) { Crashlytics.log(Log.ERROR, "MALX", "FriendsActivity.ListViewAdapter(): " + e.getMessage()); Crashlytics.logException(e); } return view; } public void supportAddAll(Collection<? extends T> collection) { this.clear(); list = (ArrayList<Profile>) collection; for (T record : collection) { this.add(record); } } static class ViewHolder { TextView username; TextView last_online; ImageView avatar; } }
package com.ebay.build.profiler.profile; import java.util.Date; import org.apache.maven.eventspy.EventSpy.Context; import org.apache.maven.execution.ExecutionEvent; import org.apache.maven.plugin.MojoExecution; import com.ebay.build.profiler.model.Plugin; import com.ebay.build.profiler.util.Timer; /** * * This Class holds the Mojo profiling information * * @author kmuralidharan * */ public class MojoProfile extends Profile { private MojoExecution mojoExecution; private String status; private String executionMsg; private String pluginGroupID; private String pluginArtifactID; private String pluginVersion; private String pluginExecutionId; private Plugin plugin = new Plugin(); public MojoProfile(Context c, MojoExecution mojoExecution, ExecutionEvent event) { super(new Timer(), event, c); this.mojoExecution = mojoExecution; this.pluginGroupID = mojoExecution.getGroupId(); this.pluginArtifactID = mojoExecution.getArtifactId(); this.pluginVersion = mojoExecution.getVersion(); this.pluginExecutionId = mojoExecution.getExecutionId(); this.event = event; String configuration = ""; if (mojoExecution.getPlugin().getConfiguration() != null && mojoExecution.getPlugin().getGroupId().contains("ebay")) { configuration = mojoExecution.getPlugin().getConfiguration().toString(); } String payload = " (" + pluginExecutionId + ") " + configuration; if (getSession() != null) { plugin.setGroupId(pluginGroupID); plugin.setArtifactId(pluginArtifactID); plugin.setVersion(pluginVersion); plugin.setPluginKey(mojoExecution.getPlugin().getId()); plugin.setStartTime(new Date(this.getTimer().getStartTime())); plugin.setPayload(payload); plugin.setExecutionId(pluginExecutionId); if (getSession().getCurrentProject().getPhases().size() > 0) { getSession().getCurrentProject().getLastPhase().getPlugins().add(plugin); } } } public String getPluginGroupID() { return pluginGroupID; } public String getPluginArtifactID() { return pluginArtifactID; } public String getPluginVersion() { return pluginVersion; } public String getPluginExecutionId() { return pluginExecutionId; } public String getStatus() { return status; } public void setStatus(String executionStatus) { this.status = executionStatus; } public void setExecutionMsg(String executionMsg) { this.executionMsg = executionMsg; } public String getExecutionMsg() { return executionMsg; } public String getId() { return new StringBuilder().append(pluginGroupID).append(":") .append(pluginArtifactID).append(":").append(pluginVersion) .append(" (").append(pluginExecutionId).append(") ").toString(); } @Override public void stop() { super.stop(); String status = this.endTransaction(); plugin.setDuration(this.getElapsedTime()); plugin.setStatus(status); } }
package ca.ualberta.cmput301w14t08.geochan.test; import java.util.ArrayList; import java.util.Date; import android.app.Activity; import android.location.Location; import android.location.LocationManager; import android.os.SystemClock; import android.test.ActivityInstrumentationTestCase2; import ca.ualberta.cmput301w14t08.geochan.activities.MainActivity; import ca.ualberta.cmput301w14t08.geochan.helpers.LocationListenerService; import ca.ualberta.cmput301w14t08.geochan.helpers.SortTypes; import ca.ualberta.cmput301w14t08.geochan.models.Comment; import ca.ualberta.cmput301w14t08.geochan.models.GeoLocation; import ca.ualberta.cmput301w14t08.geochan.models.ThreadComment; import ca.ualberta.cmput301w14t08.geochan.models.ThreadList; public class ThreadListTest extends ActivityInstrumentationTestCase2<MainActivity> { public ThreadListTest(){ super(MainActivity.class); } protected void setUp() throws Exception{ super.setUp(); MainActivity a = (MainActivity) waitForActivity(5000); assertNotNull("fragment not initialized",a); } protected Activity waitForActivity(int timeout) { long endTime = SystemClock.uptimeMillis() + timeout; while (SystemClock.uptimeMillis() <= endTime) { Activity a = getActivity(); if (a != null) { return a; } } return null; } public void testAddThread() { //Null pointer exception being raised in this test because MainActivity //doesn't have time to finished calling onCreate before the test is run. //UserHashManager instance is still null. //Comment comment = new Comment("Test", null); Comment comment = new Comment(); ThreadList.addThread(comment, "Test title"); assertTrue(ThreadList.getThreads().size() == 1); } @SuppressWarnings("static-access") public void testSortThreadsByDateNewest(){ /* * Tests ThreadList.sortThreads("DATE_NEWEST") */ ThreadList.clearThreads(); long extraTime = 1320000; ThreadList tm = new ThreadList(); ThreadComment t1 = new ThreadComment(); ThreadComment t2 = new ThreadComment(); ThreadComment t3 = new ThreadComment(); ThreadComment t4 = new ThreadComment(); ThreadComment t5 = new ThreadComment(); Date currentDate = new Date(); t1.setThreadDate(new Date(currentDate.getTime() + 1*extraTime)); t2.setThreadDate(new Date(currentDate.getTime() + 2*extraTime)); t3.setThreadDate(new Date(currentDate.getTime() + 3*extraTime)); t4.setThreadDate(new Date(currentDate.getTime() + 4*extraTime)); t5.setThreadDate(new Date(currentDate.getTime() + 5*extraTime)); tm.setThreads(new ArrayList<ThreadComment>()); tm.addThread(t1); tm.addThread(t2); tm.addThread(t5); tm.addThread(t3); tm.addThread(t4); tm.sortThreads(SortTypes.SORT_DATE_NEWEST); assertTrue("t5 is at index 0", tm.getThreads().get(0) == t5); assertTrue("t4 is at index 1", tm.getThreads().get(1) == t4); assertTrue("t3 is at index 2", tm.getThreads().get(2) == t3); assertTrue("t2 is at index 3", tm.getThreads().get(3) == t2); assertTrue("t1 is at index 4", tm.getThreads().get(4) == t1); } @SuppressWarnings("static-access") public void testSortThreadsByDateOldest(){ /* * Tests ThreadList.sortThreads("DATE_OLDEST") */ ThreadList.clearThreads(); long extraTime = 1320000; ThreadList tm = new ThreadList(); ThreadComment t1 = new ThreadComment(); ThreadComment t2 = new ThreadComment(); ThreadComment t3 = new ThreadComment(); ThreadComment t4 = new ThreadComment(); ThreadComment t5 = new ThreadComment(); Date currentDate = new Date(); t1.setThreadDate(new Date(currentDate.getTime() + 1*extraTime)); t2.setThreadDate(new Date(currentDate.getTime() + 2*extraTime)); t3.setThreadDate(new Date(currentDate.getTime() + 3*extraTime)); t4.setThreadDate(new Date(currentDate.getTime() + 4*extraTime)); t5.setThreadDate(new Date(currentDate.getTime() + 5*extraTime)); tm.setThreads(new ArrayList<ThreadComment>()); tm.addThread(t1); tm.addThread(t2); tm.addThread(t5); tm.addThread(t3); tm.addThread(t4); tm.sortThreads(SortTypes.SORT_DATE_OLDEST); assertTrue("t1 is at index 0", tm.getThreads().get(0) == t1); assertTrue("t2 is at index 1", tm.getThreads().get(1) == t2); assertTrue("t3 is at index 2", tm.getThreads().get(2) == t3); assertTrue("t4 is at index 3", tm.getThreads().get(3) == t4); assertTrue("t5 is at index 4", tm.getThreads().get(4) == t5); } /** * Tests the sorting of comments in a thread by the score relative to the user. */ @SuppressWarnings("static-access") public void testSortByUserScoreHighest(){ LocationListenerService llc = new LocationListenerService(getActivity()); llc.startListening(); ThreadList.clearThreads(); long extraTime = 1320000; Date currentDate = new Date(); ThreadList T = new ThreadList(); ThreadComment t1 = new ThreadComment(); ThreadComment t2 = new ThreadComment(); ThreadComment t3 = new ThreadComment(); ThreadComment t4 = new ThreadComment(); ThreadComment t5 = new ThreadComment(); Comment c1 = new Comment(); Comment c2 = new Comment(); Comment c3 = new Comment(); Comment c4 = new Comment(); Comment c5 = new Comment(); Location loc1 = new Location(LocationManager.GPS_PROVIDER); Location loc2 = new Location(LocationManager.GPS_PROVIDER); Location loc3 = new Location(LocationManager.GPS_PROVIDER); Location loc4 = new Location(LocationManager.GPS_PROVIDER); Location loc5 = new Location(LocationManager.GPS_PROVIDER); Location locT = new Location(LocationManager.GPS_PROVIDER); GeoLocation g1 = new GeoLocation(llc); GeoLocation g2 = new GeoLocation(llc); GeoLocation g3 = new GeoLocation(llc); GeoLocation g4 = new GeoLocation(llc); GeoLocation g5 = new GeoLocation(llc); GeoLocation gT = new GeoLocation(llc); g1.setLocation(loc1); g2.setLocation(loc2); g3.setLocation(loc3); g4.setLocation(loc4); g5.setLocation(loc5); gT.setLocation(locT); c1.setLocation(g1); c2.setLocation(g2); c3.setLocation(g3); c4.setLocation(g4); c5.setLocation(g5); T.setSortLoc(gT); c1.setTextPost("c1"); c2.setTextPost("c2"); c3.setTextPost("c3"); c4.setTextPost("c4"); c5.setTextPost("c5"); /* t1.setTopComment(c1); t2.setTopComment(c2); t3.setTopComment(c3); t4.setTopComment(c4); t5.setTopComment(c5); */ t1.getBodyComment().getLocation().setCoordinates(1,1); t2.getBodyComment().getLocation().setCoordinates(2,2); t3.getBodyComment().getLocation().setCoordinates(3,3); t4.getBodyComment().getLocation().setCoordinates(4,4); t5.getBodyComment().getLocation().setCoordinates(5,5); t1.setThreadDate(new Date(currentDate.getTime() + extraTime * 1)); t2.setThreadDate(new Date(currentDate.getTime() + extraTime * 2)); t3.setThreadDate(new Date(currentDate.getTime() + extraTime * 3)); t4.setThreadDate(new Date(currentDate.getTime() + extraTime * 4)); t5.setThreadDate(new Date(currentDate.getTime() + extraTime * 5)); T.addThread(t2); T.addThread(t3); T.addThread(t1); T.addThread(t5); T.addThread(t4); T.getSortLoc().setCoordinates(0,0); T.sortThreads(SortTypes.SORT_USER_SCORE_HIGHEST); assertEquals("t1 is at index 0:", t1, T.getThreads().get(0)); assertEquals("t2 is at index 1:", t2, T.getThreads().get(1)); assertEquals("t3 is at index 2:", t3, T.getThreads().get(2)); assertEquals("t4 is at index 3:", t4, T.getThreads().get(3)); assertEquals("t5 is at index 4:", t5, T.getThreads().get(4)); } /** * Tests the sorting of comments in a thread by the score relative to the user. */ @SuppressWarnings("static-access") public void testSortByUserScoreLowest(){ LocationListenerService llc = new LocationListenerService(getActivity()); llc.startListening(); ThreadList.clearThreads(); long extraTime = 1320000; Date currentDate = new Date(); ThreadList T = new ThreadList(); ThreadComment t1 = new ThreadComment(); ThreadComment t2 = new ThreadComment(); ThreadComment t3 = new ThreadComment(); ThreadComment t4 = new ThreadComment(); ThreadComment t5 = new ThreadComment(); Comment c1 = new Comment(); Comment c2 = new Comment(); Comment c3 = new Comment(); Comment c4 = new Comment(); Comment c5 = new Comment(); Location loc1 = new Location(LocationManager.GPS_PROVIDER); Location loc2 = new Location(LocationManager.GPS_PROVIDER); Location loc3 = new Location(LocationManager.GPS_PROVIDER); Location loc4 = new Location(LocationManager.GPS_PROVIDER); Location loc5 = new Location(LocationManager.GPS_PROVIDER); Location locT = new Location(LocationManager.GPS_PROVIDER); GeoLocation g1 = new GeoLocation(llc); GeoLocation g2 = new GeoLocation(llc); GeoLocation g3 = new GeoLocation(llc); GeoLocation g4 = new GeoLocation(llc); GeoLocation g5 = new GeoLocation(llc); GeoLocation gT = new GeoLocation(llc); g1.setLocation(loc1); g2.setLocation(loc2); g3.setLocation(loc3); g4.setLocation(loc4); g5.setLocation(loc5); gT.setLocation(locT); c1.setLocation(g1); c2.setLocation(g2); c3.setLocation(g3); c4.setLocation(g4); c5.setLocation(g5); T.setSortLoc(gT); c1.setTextPost("c1"); c2.setTextPost("c2"); c3.setTextPost("c3"); c4.setTextPost("c4"); c5.setTextPost("c5"); /* t1.setTopComment(c1); t2.setTopComment(c2); t3.setTopComment(c3); t4.setTopComment(c4); t5.setTopComment(c5); */ t1.getBodyComment().getLocation().setCoordinates(1,1); t2.getBodyComment().getLocation().setCoordinates(2,2); t3.getBodyComment().getLocation().setCoordinates(3,3); t4.getBodyComment().getLocation().setCoordinates(4,4); t5.getBodyComment().getLocation().setCoordinates(5,5); t1.setThreadDate(new Date(currentDate.getTime() + extraTime * 1)); t2.setThreadDate(new Date(currentDate.getTime() + extraTime * 2)); t3.setThreadDate(new Date(currentDate.getTime() + extraTime * 3)); t4.setThreadDate(new Date(currentDate.getTime() + extraTime * 4)); t5.setThreadDate(new Date(currentDate.getTime() + extraTime * 5)); T.addThread(t2); T.addThread(t3); T.addThread(t1); T.addThread(t5); T.addThread(t4); T.getSortLoc().setCoordinates(0,0); T.sortThreads(SortTypes.SORT_USER_SCORE_LOWEST); assertEquals("t5 is at index 0:", t5, T.getThreads().get(0)); assertEquals("t4 is at index 1:", t4, T.getThreads().get(1)); assertEquals("t3 is at index 2:", t3, T.getThreads().get(2)); assertEquals("t2 is at index 3:", t2, T.getThreads().get(3)); assertEquals("t1 is at index 4:", t1, T.getThreads().get(4)); } /** * Tests the sorting of comments in a thread by the score relative to the user. */ @SuppressWarnings("static-access") public void testSortByLocation(){ LocationListenerService llc = new LocationListenerService(getActivity()); llc.startListening(); ThreadList.clearThreads(); long extraTime = 1320000; Date currentDate = new Date(); ThreadList T = new ThreadList(); ThreadComment t1 = new ThreadComment(); ThreadComment t2 = new ThreadComment(); ThreadComment t3 = new ThreadComment(); ThreadComment t4 = new ThreadComment(); ThreadComment t5 = new ThreadComment(); Comment c1 = new Comment(); Comment c2 = new Comment(); Comment c3 = new Comment(); Comment c4 = new Comment(); Comment c5 = new Comment(); Location loc1 = new Location(LocationManager.GPS_PROVIDER); Location loc2 = new Location(LocationManager.GPS_PROVIDER); Location loc3 = new Location(LocationManager.GPS_PROVIDER); Location loc4 = new Location(LocationManager.GPS_PROVIDER); Location loc5 = new Location(LocationManager.GPS_PROVIDER); Location locT = new Location(LocationManager.GPS_PROVIDER); GeoLocation g1 = new GeoLocation(llc); GeoLocation g2 = new GeoLocation(llc); GeoLocation g3 = new GeoLocation(llc); GeoLocation g4 = new GeoLocation(llc); GeoLocation g5 = new GeoLocation(llc); GeoLocation gT = new GeoLocation(llc); g1.setLocation(loc1); g2.setLocation(loc2); g3.setLocation(loc3); g4.setLocation(loc4); g5.setLocation(loc5); gT.setLocation(locT); c1.setLocation(g1); c2.setLocation(g2); c3.setLocation(g3); c4.setLocation(g4); c5.setLocation(g5); T.setSortLoc(gT); c1.setTextPost("c1"); c2.setTextPost("c2"); c3.setTextPost("c3"); c4.setTextPost("c4"); c5.setTextPost("c5"); /* t1.setTopComment(c1); t2.setTopComment(c2); t3.setTopComment(c3); t4.setTopComment(c4); t5.setTopComment(c5); */ t1.getBodyComment().getLocation().setCoordinates(1,1); t2.getBodyComment().getLocation().setCoordinates(2,2); t3.getBodyComment().getLocation().setCoordinates(3,3); t4.getBodyComment().getLocation().setCoordinates(4,4); t5.getBodyComment().getLocation().setCoordinates(5,5); t1.setThreadDate(new Date(currentDate.getTime() + extraTime * 1)); t2.setThreadDate(new Date(currentDate.getTime() + extraTime * 2)); t3.setThreadDate(new Date(currentDate.getTime() + extraTime * 3)); t4.setThreadDate(new Date(currentDate.getTime() + extraTime * 4)); t5.setThreadDate(new Date(currentDate.getTime() + extraTime * 5)); T.addThread(t2); T.addThread(t3); T.addThread(t1); T.addThread(t5); T.addThread(t4); T.getSortLoc().setCoordinates(0,0); T.sortThreads(SortTypes.SORT_LOCATION_MISC); assertEquals("t1 is at index 0:", t1, T.getThreads().get(0)); assertEquals("t2 is at index 1:", t2, T.getThreads().get(1)); assertEquals("t3 is at index 2:", t3, T.getThreads().get(2)); assertEquals("t4 is at index 3:", t4, T.getThreads().get(3)); assertEquals("t5 is at index 4:", t5, T.getThreads().get(4)); } }
package edu.govschool.govchat.gui.modals; import javafx.geometry.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.stage.*; /** * * @author bryce */ public class GCConnectionOptionsBox { }
package net.ceos.project.poi.annotated.core; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFClientAnchor; import org.apache.poi.hssf.usermodel.HSSFPatriarch; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.Comment; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.FontUnderline; import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import net.ceos.project.poi.annotated.annotation.XlsDecorator; import net.ceos.project.poi.annotated.definition.ExceptionMessage; import net.ceos.project.poi.annotated.definition.ExtensionFileType; import net.ceos.project.poi.annotated.exception.ConfigurationException; import net.ceos.project.poi.annotated.exception.ElementException; /** * This class manage all the cell style to apply to one cell decoration. * * @version 1.0 * @author Carlos CRISTO ABREU */ public class CellStyleHandler { // cell decorator constants public static final String CELL_DECORATOR_DATE = "date"; public static final String CELL_DECORATOR_BOOLEAN = "boolean"; public static final String CELL_DECORATOR_ENUM = "enum"; public static final String CELL_DECORATOR_NUMERIC = "numeric"; public static final String CELL_DECORATOR_HEADER = "header"; public static final String CELL_DECORATOR_GENERIC = "generic"; // default mask decorators public static final String MASK_DECORATOR_DATE = "yyyy-MM-dd"; public static final String MASK_DECORATOR_INTEGER = "0"; public static final String MASK_DECORATOR_DOUBLE = "0.00"; // default XlsDecorator constants public static final String FONT_NAME = "Arial"; public static final short FONT_SIZE = 10; public static final short FONT_COLOR = 0; public static final boolean FONT_BOLD = false; public static final boolean FONT_ITALIC = false; public static final short FONT_UNDERLINE = 0; public static final short FONT_ALIGNMENT = 0; public static final short FONT_VERTICAL_ALIGNMENT = 0; public static final short CELL_BORDER = 0; public static final short CELL_BACKGROUND_COLOR = 9; public static final short CELL_FOREGROUND_COLOR = 9; public static final boolean CELL_WRAP_TEXT = false; private CellStyleHandler() { /* private constructor to hide the implicit public */ } /** * Apply the data format to the cell style. * * @param wb * the workbook * @param c * the cell * @param cs * the cell style * @param formatMask */ protected static void applyDataFormat(final Workbook wb, final Cell c, final CellStyle cs, final String formatMask) { DataFormat df = initializeDataFormat(wb); cs.setDataFormat(df.getFormat(formatMask)); c.setCellStyle(cs); } /** * Apply the font to the cell style with default values. * * @param wb * the workbook * @param cs * the cell style */ protected static void applyFontDefault(Workbook wb, CellStyle cs) { applyFont(wb, cs, CellStyleHandler.FONT_NAME, CellStyleHandler.FONT_SIZE, CellStyleHandler.FONT_COLOR, CellStyleHandler.FONT_BOLD, CellStyleHandler.FONT_ITALIC, FontUnderline.NONE.getByteValue()); } /** * Apply the font to the cell style. * * @param wb * the workbook * @param cs * the cell style * @param name * the font name * @param size * the font size * @param c * the font color * @param b * is bold format * @param i * is italic format * @param u * is underline format */ protected static void applyFont(final Workbook wb, final CellStyle cs, final String name, final short size, final short c, final boolean b, final boolean i, final byte u) { Font f = initializeFont(wb); f.setFontName(name); f.setFontHeightInPoints(size); f.setColor(c); f.setBold(b); f.setItalic(i); f.setUnderline(u); cs.setFont(f); } /** * Apply the horizontal alignment to the cell style.<br> * By default the vertical alignment is 0. * * @param cs * the cell style * @param a * the horizontal alignment */ protected static void applyAlignment(final CellStyle cs, final short a) { applyAlignment(cs, a, (short) 0); } /** * Apply the horizontal & vertical alignment to the cell style. * * @param cs * the cell style * @param a * the horizontal alignment * @param vA * the vertical alignment */ protected static void applyAlignment(final CellStyle cs, final short a, final short vA) { if (a != 0) { cs.setAlignment(a); } if (vA != 0) { cs.setVerticalAlignment(vA); } } /** * Apply the border to the cell style with default values. * * @param cs * the cell style */ protected static void applyBorderDefault(final CellStyle cs) { applyBorder(cs, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN); } /** * Apply the border to the cell style. * * @param cs * the cell style * @param bL * the cell border left * @param bR * the cell border right * @param bT * the cell border top * @param bB * the cell border bottom */ protected static void applyBorder(final CellStyle cs, final short bL, final short bR, final short bT, final short bB) { cs.setBorderLeft(bL); cs.setBorderRight(bR); cs.setBorderTop(bT); cs.setBorderBottom(bB); } /** * Apply the background color to the cell style. * * @param cs * the cell style * @param bC * the background color */ protected static void applyBackgroundColor(final CellStyle cs, final short bC) { cs.setFillBackgroundColor(bC); } /** * Apply the cell comment to a cell. * * @param wb * the workbook * @param c * the cell * @param t * the text comment * @param e * the extension file */ protected static void applyComment(final ConfigCriteria configCriteria, final Boolean isAuthorizedComment, final Cell c) { if (StringUtils.isBlank(configCriteria.getElement().commentRules()) || StringUtils.isNotBlank(configCriteria.getElement().commentRules()) && isAuthorizedComment) { if (ExtensionFileType.XLS.equals(configCriteria.getExtension())) { final Map<Sheet, HSSFPatriarch> drawingPatriarches = new HashMap<>(); CreationHelper createHelper = c.getSheet().getWorkbook().getCreationHelper(); HSSFSheet sheet = (HSSFSheet) c.getSheet(); HSSFPatriarch drawingPatriarch = drawingPatriarches.get(sheet); if (drawingPatriarch == null) { drawingPatriarch = sheet.createDrawingPatriarch(); drawingPatriarches.put(sheet, drawingPatriarch); } Comment comment = drawingPatriarch .createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5)); comment.setString(createHelper.createRichTextString(configCriteria.getElement().comment())); c.setCellComment(comment); } else if (ExtensionFileType.XLSX.equals(configCriteria.getExtension())) { CreationHelper factory = configCriteria.getWorkbook().getCreationHelper(); Drawing drawing = c.getSheet().createDrawingPatriarch(); ClientAnchor anchor = factory.createClientAnchor(); Comment comment = drawing.createCellComment(anchor); RichTextString str = factory.createRichTextString(configCriteria.getElement().comment()); comment.setString(str); c.setCellComment(comment); } } } /** * Initialize cell style. * * @param wb * the workbook * @return the {@link CellStyle}. */ protected static CellStyle initializeCellStyle(final Workbook wb) { return wb.createCellStyle(); } /** * Apply cell style according the one cell style base and format mask. * * @param configCriteria * the {@link ConfigCriteria} * @param c * the {@link Cell} * @param cellDecoratorType * the cell decorator by default * @param maskDecoratorType * the format mask by default * @throws ElementException */ protected static void applyCellStyle(final ConfigCriteria configCriteria, final Cell c, final String cellDecoratorType, final String maskDecoratorType) throws ElementException { CellStyle cs = configCriteria.getCellStyle(cellDecoratorType); if (maskDecoratorType != null && StringUtils.isNotBlank(configCriteria.getMask(maskDecoratorType)) && cs != null) { /* generate a key based : formatMask + decorator */ String key = configCriteria.generateCellStyleKey(cellDecoratorType, maskDecoratorType); if (!configCriteria.getCellStyleManager().containsKey(key)) { /* clone a cell style */ CellStyle csNew = cloneCellStyle(configCriteria.getWorkbook(), cs); /* initialize/apply a data format */ DataFormat df = initializeDataFormat(configCriteria.getWorkbook()); csNew.setDataFormat(df.getFormat(configCriteria.getMask(maskDecoratorType))); configCriteria.getCellStyleManager().put(key, csNew); cs = csNew; } else { cs = configCriteria.getCellStyleManager().get(key); } /* apply cell style to a cell */ c.setCellStyle(cs); } else { if (cs == null) { /* CASE : if the cell has no cell style base */ cs = initializeCellStyle(configCriteria.getWorkbook()); } if (maskDecoratorType != null && StringUtils.isNotBlank(configCriteria.getMask(maskDecoratorType))) { /* CASE : if the cell has a formatMask */ DataFormat df = initializeDataFormat(configCriteria.getWorkbook()); cs.setDataFormat(df.getFormat(configCriteria.getMask(maskDecoratorType))); } c.setCellStyle(cs); } } /** * Initialize the header cell. * * @param r * {@link Row} to add the cell * @param idxC * position of the new cell * @param value * the value of the cell content * @return the cell created */ protected static Cell initializeHeaderCell(final Map<String, CellStyle> stylesMap, final Row r, final int idxC, final String value) { Cell c = r.createCell(idxC); c.setCellValue(value); c.setCellStyle(stylesMap.get(CellStyleHandler.CELL_DECORATOR_HEADER)); return c; } /** * Initialize default Header Cell Decorator. * * @param wb * the {@link Workbook} in use * @return the {@link CellStyle} header decorator */ protected static CellStyle initializeHeaderCellDecorator(final Workbook wb) { CellStyle cs = CellStyleHandler.initializeCellStyle(wb); /* add the alignment to the cell */ CellStyleHandler.applyAlignment(cs, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER); /* add the border to the cell */ CellStyleHandler.applyBorderDefault(cs); /* add the background to the cell */ cs.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); /* add the wrap mode to the cell */ cs.setWrapText(true); /* add the font style to the cell */ CellStyleHandler.applyFontDefault(wb, cs); return cs; } /** * Initialize default Numeric Cell Decorator. * * @param wb * the {@link Workbook} in use * @return the {@link CellStyle} numeric decorator */ protected static CellStyle initializeNumericCellDecorator(final Workbook wb) { CellStyle cs = CellStyleHandler.initializeCellStyle(wb); /* add the alignment to the cell */ CellStyleHandler.applyAlignment(cs, CellStyle.ALIGN_RIGHT); CellStyleHandler.applyFontDefault(wb, cs); return cs; } /** * Initialize default Date Cell Decorator. * * @param wb * the {@link Workbook} in use * @return the {@link CellStyle} date decorator */ protected static CellStyle initializeDateCellDecorator(final Workbook wb) { CellStyle cs = CellStyleHandler.initializeCellStyle(wb); /* add the alignment to the cell */ CellStyleHandler.applyAlignment(cs, CellStyle.ALIGN_CENTER); CellStyleHandler.applyFontDefault(wb, cs); return cs; } /** * Initialize default Boolean Cell Decorator. * * @param wb * the {@link Workbook} in use * @return the {@link CellStyle} boolean decorator */ protected static CellStyle initializeBooleanCellDecorator(final Workbook wb) { CellStyle cs = CellStyleHandler.initializeCellStyle(wb); /* add the alignment to the cell */ CellStyleHandler.applyAlignment(cs, CellStyle.ALIGN_CENTER); CellStyleHandler.applyFontDefault(wb, cs); return cs; } /** * Initialize default Generic Cell Decorator. * * @param wb * the {@link Workbook} in use * @return the {@link CellStyle} generic decorator */ protected static CellStyle initializeGenericCellDecorator(final Workbook wb) { CellStyle cs = CellStyleHandler.initializeCellStyle(wb); /* add the alignment to the cell */ CellStyleHandler.applyAlignment(cs, CellStyle.ALIGN_LEFT); CellStyleHandler.applyFontDefault(wb, cs); return cs; } /** * Initialize {@link CellStyle} by Cell Decorator. * * @param wb * the {@link Workbook} in use * @param decorator * the {@link CellDecorator} to use * @return the {@link CellStyle} decorator */ protected static CellStyle initializeCellStyleByCellDecorator(final Workbook wb, final CellDecorator decorator) throws ConfigurationException { CellStyle cs = CellStyleHandler.initializeCellStyle(wb); try { /* add the alignment to the cell */ CellStyleHandler.applyAlignment(cs, decorator.getAlignment(), decorator.getVerticalAlignment()); /* add the border to the cell */ borderPropagationManagement(decorator); CellStyleHandler.applyBorder(cs, decorator.getBorderLeft(), decorator.getBorderRight(), decorator.getBorderTop(), decorator.getBorderBottom()); /* add the background to the cell */ cs.setFillForegroundColor(decorator.getForegroundColor()); cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); /* add the wrap mode to the cell */ cs.setWrapText(decorator.isWrapText()); /* add the font style to the cell */ CellStyleHandler.applyFont(wb, cs, decorator.getFontName(), decorator.getFontSize(), decorator.getFontColor(), decorator.isFontBold(), decorator.isFontItalic(), decorator.getFontUnderline()); } catch (Exception e) { throw new ConfigurationException(ExceptionMessage.ConfigurationException_CellStyleMissing.getMessage(), e); } return cs; } /** * Initialize {@link CellStyle} by XlsDecorator. * * @param wb * the {@link Workbook} in use * @param decorator * the {@link CellDecorator} to use * @return the {@link CellStyle} decorator */ protected static CellStyle initializeCellStyleByXlsDecorator(final Workbook wb, final XlsDecorator decorator) throws ConfigurationException { CellStyle cs = CellStyleHandler.initializeCellStyle(wb); try { /* add the alignment to the cell */ CellStyleHandler.applyAlignment(cs, decorator.alignment(), decorator.verticalAlignment()); /* add the border to the cell */ if (decorator.border() != 0 && isBorderPropagationValid(decorator)) { CellStyleHandler.applyBorder(cs, decorator.border(), decorator.border(), decorator.border(), decorator.border()); } else { CellStyleHandler.applyBorder(cs, decorator.borderLeft(), decorator.borderRight(), decorator.borderTop(), decorator.borderBottom()); } /* add the background to the cell */ cs.setFillForegroundColor(decorator.foregroundColor()); cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); /* add the wrap mode to the cell */ cs.setWrapText(decorator.wrapText()); /* add the font style to the cell */ CellStyleHandler.applyFont(wb, cs, decorator.fontName(), decorator.fontSize(), decorator.fontColor(), decorator.fontBold(), decorator.fontItalic(), decorator.fontUnderline()); } catch (Exception e) { throw new ConfigurationException(ExceptionMessage.ConfigurationException_CellStyleMissing.getMessage(), e); } return cs; } /** * Initialize font. * * @param wb * the workbook * @return the {@link Font}. */ private static Font initializeFont(final Workbook wb) { return wb.createFont(); } /** * Initialize the data format. * * @param wb * the workbook * @return the {@link DataFormat}. */ private static DataFormat initializeDataFormat(final Workbook wb) { return wb.createDataFormat(); } /** * Clone a cell style passed as parameter. * * @param wb * the workbook * @param csBase * the cell style base * @return the new cell style */ private static CellStyle cloneCellStyle(final Workbook wb, final CellStyle csBase) { CellStyle cs = initializeCellStyle(wb); cs.setAlignment(csBase.getAlignment()); cs.setVerticalAlignment(csBase.getVerticalAlignment()); cs.setBorderTop(csBase.getBorderTop()); cs.setBorderBottom(csBase.getBorderBottom()); cs.setBorderLeft(csBase.getBorderLeft()); cs.setBorderRight(csBase.getBorderRight()); cs.setFillForegroundColor(csBase.getFillForegroundColor()); cs.setFillPattern(csBase.getFillPattern()); cs.setWrapText(csBase.getWrapText()); cs.setFont(wb.getFontAt(csBase.getFontIndex())); return cs; } /** * if specific border not configured, propagate generic border configuration * to specific border. * * @param decorator * the {@link CellDecorator} to use */ private static void borderPropagationManagement(final CellDecorator decorator) { /* if specific border not configured */ if (decorator.getBorder() != 0 && isBorderPropagationValid(decorator)) { /* propagate generic border configuration to specific border */ decorator.setBorderLeft(decorator.getBorder()); decorator.setBorderRight(decorator.getBorder()); decorator.setBorderTop(decorator.getBorder()); decorator.setBorderBottom(decorator.getBorder()); } } /** * @param decorator * @return */ private static boolean isBorderPropagationValid(final CellDecorator decorator) { return decorator.getBorderLeft() == 0 && decorator.getBorderRight() == 0 && decorator.getBorderTop() == 0 && decorator.getBorderBottom() == 0; } /** * @param decorator * @return */ private static boolean isBorderPropagationValid(final XlsDecorator decorator) { return decorator.borderLeft() == 0 && decorator.borderRight() == 0 && decorator.borderTop() == 0 && decorator.borderBottom() == 0; } }
package info.justaway.fragment.dialog; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.support.v4.util.LongSparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import info.justaway.JustawayApplication; import info.justaway.MainActivity; import info.justaway.PostActivity; import info.justaway.ProfileActivity; import info.justaway.R; import info.justaway.SearchActivity; import info.justaway.fragment.AroundFragment; import info.justaway.fragment.RetweetersFragment; import info.justaway.fragment.TalkFragment; import info.justaway.listener.StatusActionListener; import info.justaway.model.Row; import info.justaway.plugin.TwiccaPlugin; import info.justaway.settings.MuteSettings; import info.justaway.task.DestroyStatusTask; import twitter4j.DirectMessage; import twitter4j.HashtagEntity; import twitter4j.Status; import twitter4j.URLEntity; import twitter4j.User; import twitter4j.UserMentionEntity; public class StatusMenuFragment extends DialogFragment { private FragmentActivity mActivity; private JustawayApplication mApplication; static final int CLOSED_MENU_DELAY = 800; private List<ResolveInfo> mTwiccaPlugins; private StatusActionListener mStatusActionListener; public static StatusMenuFragment newInstance(Row row) { Bundle args = new Bundle(); if (row.isDirectMessage()) { args.putSerializable("directMessage", row.getMessage()); } else { args.putSerializable("status", row.getStatus()); } if (row.isFavorite()) { args.putSerializable("favoriteSourceUser", row.getSource()); } final StatusMenuFragment f = new StatusMenuFragment(); f.setArguments(args); return f; } public StatusMenuFragment() { } public StatusMenuFragment setStatusActionListener(StatusActionListener statusActionListener) { mStatusActionListener = statusActionListener; return this; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { mActivity = getActivity(); mApplication = JustawayApplication.getApplication(); final MenuAdapter adapter = new MenuAdapter(getActivity(), R.layout.row_menu); ListView listView = new ListView(mActivity); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Menu menu = adapter.getItem(i); menu.callback.run(); } }); AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); builder.setView(listView); final DirectMessage directMessage = (DirectMessage) getArguments().getSerializable("directMessage"); if (directMessage != null) { builder.setTitle(directMessage.getSenderScreenName()); adapter.add(new Menu(R.string.context_menu_reply_direct_message, new Runnable() { @Override public void run() { String text = "D " + directMessage.getSenderScreenName() + " "; tweet(text, text.length(), null); dismiss(); } })); adapter.add(new Menu(R.string.context_menu_destroy_direct_message, new Runnable() { @Override public void run() { MainActivity mainActivity = (MainActivity) mActivity; mainActivity.doDestroyDirectMessage(directMessage.getId()); dismiss(); } })); for (final UserMentionEntity mention : directMessage.getUserMentionEntities()) { adapter.add(new Menu("@" + mention.getScreenName(), new Runnable() { @Override public void run() { Intent intent = new Intent(mActivity, ProfileActivity.class); intent.putExtra("screenName", mention.getScreenName()); mActivity.startActivity(intent); } })); } /** * URL */ URLEntity[] urls = directMessage.getURLEntities(); for (final URLEntity url : urls) { adapter.add(new Menu(url.getExpandedURL(), new Runnable() { @Override public void run() { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.getExpandedURL())); mActivity.startActivity(intent); } })); } return builder.create(); } final Status status = (Status) getArguments().getSerializable("status"); if (status == null) { return null; } final Status retweet = status.getRetweetedStatus(); final Status source = retweet != null ? retweet : status; final UserMentionEntity[] mentions = source.getUserMentionEntities(); Boolean isPublic = !source.getUser().isProtected(); builder.setTitle(status.getText()); adapter.add(new Menu(R.string.context_menu_reply, new Runnable() { @Override public void run() { String text; if (source.getUser().getId() == mApplication.getUserId() && mentions.length == 1) { text = "@" + mentions[0].getScreenName() + " "; } else { text = "@" + source.getUser().getScreenName() + " "; } tweet(text, text.length(), status); dismiss(); } })); if (mentions.length > 1 || (mentions.length == 1 && !mentions[0].getScreenName().equals(mApplication.getScreenName()))) { adapter.add(new Menu(R.string.context_menu_reply_all, new Runnable() { @Override public void run() { String text = ""; if (source.getUser().getId() != mApplication.getUserId()) { text = "@" + source.getUser().getScreenName() + " "; } for (UserMentionEntity mention : mentions) { if (source.getUser().getScreenName().equals(mention.getScreenName())) { continue; } if (mApplication.getScreenName().equals(mention.getScreenName())) { continue; } text = text.concat("@" + mention.getScreenName() + " "); } tweet(text, text.length(), status); dismiss(); } })); } if (isPublic) { adapter.add(new Menu(R.string.context_menu_qt, new Runnable() { @Override public void run() { String text = " https://twitter.com/" + source.getUser().getScreenName() + "/status/" + String.valueOf(source.getId()); tweet(text, 0, source); dismiss(); } })); } if (mApplication.isFav(status)) { adapter.add(new Menu(R.string.context_menu_destroy_favorite, new Runnable() { @Override public void run() { mApplication.doDestroyFavorite(status.getId()); mStatusActionListener.notifyDataSetChanged(); dismiss(); } })); } else { adapter.add(new Menu(R.string.context_menu_create_favorite, new Runnable() { @Override public void run() { mApplication.doFavorite(status.getId()); mStatusActionListener.notifyDataSetChanged(); dismiss(); } })); } if (status.getUser().getId() == mApplication.getUserId()) { if (retweet != null) { adapter.add(new Menu(R.string.context_menu_destroy_retweet, new Runnable() { @Override public void run() { mApplication.doDestroyRetweet(status); mStatusActionListener.notifyDataSetChanged(); dismiss(); } })); } else { adapter.add(new Menu(R.string.context_menu_destroy_status, new Runnable() { @Override public void run() { new DestroyStatusTask(status.getId()) .setStatusActionListener(mStatusActionListener) .execute(); dismiss(); } })); } } else if (mApplication.getRtId(status) != null) { adapter.add(new Menu(R.string.context_menu_destroy_retweet, new Runnable() { @Override public void run() { mApplication.doDestroyRetweet(status); mStatusActionListener.notifyDataSetChanged(); dismiss(); } })); } else { if (isPublic) { if (!mApplication.isFav(status)) { adapter.add(new Menu(R.string.context_menu_favorite_and_retweet, new Runnable() { @Override public void run() { mApplication.doFavorite(status.getId()); mApplication.doRetweet(status.getId()); mStatusActionListener.notifyDataSetChanged(); dismiss(); } })); } adapter.add(new Menu(R.string.context_menu_retweet, new Runnable() { @Override public void run() { mApplication.doRetweet(status.getId()); mStatusActionListener.notifyDataSetChanged(); dismiss(); } })); } } if (source.getRetweetCount() > 0) { adapter.add(new Menu(R.string.context_menu_show_retweeters, new Runnable() { @Override public void run() { RetweetersFragment retweetersFragment = new RetweetersFragment(); Bundle retweetsArgs = new Bundle(); retweetsArgs.putLong("statusId", source.getId()); retweetersFragment.setArguments(retweetsArgs); retweetersFragment.show(mActivity.getSupportFragmentManager(), "dialog"); } })); } if (source.getInReplyToStatusId() > 0) { adapter.add(new Menu(R.string.context_menu_talk, new Runnable() { @Override public void run() { TalkFragment dialog = new TalkFragment(); Bundle args = new Bundle(); args.putLong("statusId", source.getId()); dialog.setArguments(args); dialog.show(mActivity.getSupportFragmentManager(), "dialog"); } })); } adapter.add(new Menu(R.string.context_menu_show_around, new Runnable() { @Override public void run() { AroundFragment aroundFragment = new AroundFragment(); Bundle aroundArgs = new Bundle(); aroundArgs.putSerializable("status", source); aroundFragment.setArguments(aroundArgs); aroundFragment.show(mActivity.getSupportFragmentManager(), "dialog"); } })); /** * URL */ URLEntity[] urls = source.getURLEntities(); for (final URLEntity url : urls) { adapter.add(new Menu(url.getExpandedURL(), new Runnable() { @Override public void run() { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.getExpandedURL())); mActivity.startActivity(intent); } })); } /** * URL() */ URLEntity[] medias = source.getMediaEntities(); for (final URLEntity url : medias) { adapter.add(new Menu(url.getExpandedURL(), new Runnable() { @Override public void run() { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.getExpandedURL())); mActivity.startActivity(intent); } })); } HashtagEntity[] hashtags = source.getHashtagEntities(); for (final HashtagEntity hashtag : hashtags) { adapter.add(new Menu("#" + hashtag.getText(), new Runnable() { @Override public void run() { Intent intent = new Intent(mActivity, SearchActivity.class); intent.putExtra("query", "#" + hashtag.getText()); mActivity.startActivity(intent); } })); } LongSparseArray<Boolean> users = new LongSparseArray<Boolean>(); final User favoriteSourceUser = (User) getArguments().getSerializable("favoriteSourceUser"); if (favoriteSourceUser != null) { users.put(favoriteSourceUser.getId(), true); adapter.add(new Menu("@" + favoriteSourceUser.getScreenName(), new Runnable() { @Override public void run() { Intent intent = new Intent(mActivity, ProfileActivity.class); intent.putExtra("screenName", favoriteSourceUser.getScreenName()); mActivity.startActivity(intent); } })); } if (retweet != null && users.get(status.getUser().getId()) == null) { users.put(status.getUser().getId(), true); adapter.add(new Menu("@" + status.getUser().getScreenName(), new Runnable() { @Override public void run() { Intent intent = new Intent(mActivity, ProfileActivity.class); intent.putExtra("screenName", status.getUser().getScreenName()); mActivity.startActivity(intent); } })); } for (final UserMentionEntity mention : mentions) { if (users.get(mention.getId()) != null) { continue; } users.put(mention.getId(), true); adapter.add(new Menu("@" + mention.getScreenName(), new Runnable() { @Override public void run() { Intent intent = new Intent(mActivity, ProfileActivity.class); intent.putExtra("screenName", mention.getScreenName()); mActivity.startActivity(intent); } })); } if (isPublic) { /** * TwiccaPlugin */ if (mTwiccaPlugins == null) { mTwiccaPlugins = TwiccaPlugin.getResolveInfo(mActivity.getPackageManager(), TwiccaPlugin.TWICCA_ACTION_SHOW_TWEET); } if (!mTwiccaPlugins.isEmpty()) { PackageManager pm = mActivity.getPackageManager(); for (final ResolveInfo resolveInfo : mTwiccaPlugins) { if (pm == null || resolveInfo.activityInfo == null) { continue; } String label = (String) resolveInfo.activityInfo.loadLabel(pm); if (label == null) { continue; } adapter.add(new Menu(label, new Runnable() { @Override public void run() { Intent intent = TwiccaPlugin.createIntentShowTweet(status, resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name); mActivity.startActivity(intent); } })); } } adapter.add(new Menu(R.string.context_menu_share_url, new Runnable() { @Override public void run() { Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, "https://twitter.com/" + source.getUser().getScreenName() + "/status/" + String.valueOf(source.getId())); mActivity.startActivity(intent); } })); } /** * via */ adapter.add(new Menu(String.format(mActivity.getString(R.string.context_menu_mute), mApplication.getClientName(source.getSource())), new Runnable() { @Override public void run() { new AlertDialog.Builder(getActivity()) .setTitle(String.format(getString(R.string.context_create_mute), mApplication.getClientName(source.getSource()))) .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { MuteSettings muteSettings = mApplication.getMuteSettings(); muteSettings.addSource(mApplication.getClientName(source.getSource())); muteSettings.saveMuteSettings(); JustawayApplication.showToast(R.string.toast_create_mute); dismiss(); } }) .setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .show(); } })); for (final HashtagEntity hashtag : hashtags) { adapter.add(new Menu(String.format(mActivity.getString(R.string.context_menu_mute), "#".concat(hashtag.getText())), new Runnable() { @Override public void run() { new AlertDialog.Builder(getActivity()) .setTitle(String.format(getString(R.string.context_create_mute), "#".concat(hashtag.getText()))) .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { MuteSettings muteSettings = mApplication.getMuteSettings(); muteSettings.addWord("#" + hashtag.getText()); muteSettings.saveMuteSettings(); JustawayApplication.showToast(R.string.toast_create_mute); dismiss(); } }) .setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .show(); } })); } adapter.add(new Menu(String.format(mActivity.getString(R.string.context_menu_mute), "@".concat(source.getUser().getScreenName())), new Runnable() { @Override public void run() { new AlertDialog.Builder(getActivity()) .setTitle(String.format(getString(R.string.context_create_mute), "@".concat(source.getUser().getScreenName()))) .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { MuteSettings muteSettings = mApplication.getMuteSettings(); muteSettings.addUser(source.getUser().getId(), source.getUser().getScreenName()); muteSettings.saveMuteSettings(); JustawayApplication.showToast(R.string.toast_create_mute); dismiss(); } }) .setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .show(); } })); return builder.create(); } private EditText getQuickTweetEdit() { View singleLineTweet = mActivity.findViewById(R.id.quick_tweet_layout); if (singleLineTweet != null && singleLineTweet.getVisibility() == View.VISIBLE) { return (EditText) mActivity.findViewById(R.id.quick_tweet_edit); } return null; } private void tweet(String text, int selection, Status inReplyToStatus) { EditText editStatus = getQuickTweetEdit(); if (editStatus != null) { editStatus.requestFocus(); editStatus.setText(text); if (selection > 0) { editStatus.setSelection(selection); } if (inReplyToStatus!=null) { ((MainActivity) mActivity).setInReplyToStatus(inReplyToStatus); } mApplication.showKeyboard(editStatus, CLOSED_MENU_DELAY); } else { Intent intent = new Intent(mActivity, PostActivity.class); intent.putExtra("status", text); if (selection > 0) { intent.putExtra("selection", selection); } if (inReplyToStatus!=null) { intent.putExtra("inReplyToStatus", inReplyToStatus); } mActivity.startActivity(intent); } } public class Menu { public Runnable callback; public String label; public Menu(String label, Runnable callback) { this.label = label; this.callback = callback; } public Menu(int resId, Runnable callback) { this.label = getString(resId); this.callback = callback; } } public class MenuAdapter extends ArrayAdapter<Menu> { private ArrayList<Menu> mMenuList = new ArrayList<Menu>(); private LayoutInflater mInflater; private int mLayout; public MenuAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.mLayout = textViewResourceId; } @Override public void add(Menu menu) { super.add(menu); mMenuList.add(menu); } @Override public View getView(final int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { // null view = mInflater.inflate(this.mLayout, null); if (view == null) { return null; } } Menu menu = mMenuList.get(position); ((TextView) view).setText(menu.label); return view; } } }
package com.elmakers.mine.bukkit.api.effect; import com.elmakers.mine.bukkit.api.action.CastContext; import org.bukkit.Color; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.block.Block; import com.elmakers.mine.bukkit.api.block.MaterialAndData; import org.bukkit.entity.Entity; import java.util.Collection; import java.util.Map; public interface EffectPlayer { public void setEffectPlayList(Collection<EffectPlay> plays); public void setEffect(Effect effect); public void setEffectData(int data); public void setScale(float scale); public void setSound(Sound sound); public void setSound(Sound sound, float volume, float pitch); public void setParameterMap(Map<String, String> parameters); public void setDelayTicks(int ticks); public void setParticleOverride(String particleType); public void setMaterial(MaterialAndData material); public void setMaterial(Block block); public void setColor(Color color); public boolean shouldUseHitLocation(); public boolean shouldUseWandLocation(); public boolean shouldUseCastLocation(); public boolean shouldUseEyeLocation(); public boolean shouldUseBlockLocation(); public Location getSourceLocation(CastContext context); public void start(Location origin, Location target); public void start(Entity origin, Entity target); public void start(Location origin, Entity originEntity, Location target, Entity targetEntity); public void start(Location origin, Entity originEntity, Location target, Entity targetEntity, Collection<Entity> targets); }
package com.tcolligan.maximmaker; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.tcolligan.maximmaker.data.Maxim; import java.util.ArrayList; import java.util.List; public class MaximFeedActivity extends AppCompatActivity implements MaximFeedPresenter.MaximFeed, MaximFeedAdapter.MaximViewHolderListener { private ProgressBar progressBar; private TextView messageTextView; private RecyclerView recyclerView; private MaximFeedPresenter maximFeedPresenter; private MaximFeedAdapter maximFeedAdapter; private List<Maxim> maximList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maxim_feed); progressBar = (ProgressBar) findViewById(R.id.progressBar); messageTextView = (TextView) findViewById(R.id.messageTextView); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.addItemDecoration(new MaximFeedItemDecorator()); maximFeedPresenter = new MaximFeedPresenter(getApplicationContext(), this); maximList = new ArrayList<>(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.maxim_feed_menu, menu); MenuItem searchItem = menu.findItem(R.id.search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return true; } @Override public boolean onQueryTextChange(String newText) { maximFeedPresenter.onSearch(newText); return true; } }); MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem item) { maximFeedPresenter.onSearchOpened(); return true; } @Override public boolean onMenuItemActionCollapse(MenuItem item) { maximFeedPresenter.onSearchClosed(); return true; } }); return true; } @Override public void onResume() { super.onResume(); maximFeedPresenter.onResume(); } @Override public void onDestroy() { super.onDestroy(); maximFeedPresenter = null; } public void onAddMaximButtonClicked(View v) { maximFeedPresenter.onAddMaximButtonClicked(this); } private void showDeleteConfirmationDialog(final Maxim maxim) { new AlertDialog.Builder(this) .setMessage(R.string.delete_maxim_dialog_message) .setPositiveButton(R.string.delete_button_text, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { maximFeedPresenter.onDeleteMaxim(maxim); } }) .setNegativeButton(android.R.string.cancel, null) .create() .show(); } @Override public void onLongClick(final Maxim maxim) { new AlertDialog.Builder(this) .setMessage(R.string.edit_of_delete_maxim_message) .setPositiveButton(R.string.edit_button_text, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { maximFeedPresenter.onEditMaxim(MaximFeedActivity.this, maxim); } }) .setNegativeButton(R.string.delete_button_text, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { showDeleteConfirmationDialog(maxim); } }) .create() .show(); } @Override public void showLoadingState() { progressBar.setVisibility(View.VISIBLE); messageTextView.setVisibility(View.GONE); recyclerView.setVisibility(View.GONE); } @Override public void showEmptyState() { messageTextView.setText(R.string.no_maxims_text); progressBar.setVisibility(View.GONE); messageTextView.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.GONE); } @Override public void showLoadingError() { messageTextView.setText(R.string.error_loading_maxims_text); progressBar.setVisibility(View.GONE); messageTextView.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.GONE); } @Override public void showMaxims(List<Maxim> maximList) { this.maximList.clear(); this.maximList.addAll(maximList); if (maximFeedAdapter == null) { maximFeedAdapter = new MaximFeedAdapter(this.maximList, this); recyclerView.setAdapter(maximFeedAdapter); } else { maximFeedAdapter.notifyDataSetChanged(); } progressBar.setVisibility(View.GONE); messageTextView.setVisibility(View.GONE); recyclerView.setVisibility(View.VISIBLE); } }
package com.Webtrekk.SDKTest; import android.support.test.filters.LargeTest; import com.webtrekk.webtrekksdk.Utils.WebtrekkLogging; import com.webtrekk.webtrekksdk.Webtrekk; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; @RunWith(WebtrekkClassRunner.class) @LargeTest public class BadConnectionTest extends WebtrekkBaseMainTest { private Webtrekk mWebtrekk; private static final int TRACKING_CALLS_STACK = 1000; @Rule public final WebtrekkTestRule<EmptyActivity> mActivityRule = new WebtrekkTestRule<>(EmptyActivity.class, this); @Override public void before() throws Exception { super.before(); mWebtrekk = Webtrekk.getInstance(); mWebtrekk.initWebtrekk(mApplication, R.raw.webtrekk_config_connection_broken_request); } @After @Override public void after() throws Exception { super.after(); } @Test public void testLostConnection() { long messageReeivedCounter = mHttpServer.getCurrentRequestNumber(); initWaitingForTrack(new Runnable() { @Override public void run() { for (int i = 0; i < TRACKING_CALLS_STACK; i++) { mWebtrekk.track(); } } }); //Wait for some message starts to send. try { Thread.sleep(1000); } catch (InterruptedException e) { WebtrekkLogging.log("Sleep interruction"); } //stop http server - emulator connection brakes mHttpServer.stop(); WebtrekkLogging.log("Stop HTTP Server"); //wait sometime try { Thread.sleep(5000); } catch (InterruptedException e) { WebtrekkLogging.log("Sleep interruction"); } mWaitMilliseconds = 70000; initWaitingForTrack(new Runnable() { @Override public void run() { try { WebtrekkLogging.log("Start HTTP Server"); synchronized (mHttpServer) { mHttpServer.start(); } } catch (IOException e) { WebtrekkLogging.log("testLostConnection. Can't start server one more time"); } } }, TRACKING_CALLS_STACK - (mHttpServer.getCurrentRequestNumber() - messageReeivedCounter)); waitForTrackedURLs(); } @Test public void testSlowConnection(){ final int delay = 30*1000; // make significant delay in response WebtrekkLogging.log("Setup HTTP request delay"); mHttpServer.setBeforeDelay(delay); try { // do some track mWaitMilliseconds = delay; initWaitingForTrack(new Runnable() { @Override public void run() { mWebtrekk.track(); } }); //Wait for 2 seconds to make SDK start to send message. try { Thread.sleep(2000); } catch (InterruptedException e) { WebtrekkLogging.log("Sleep interruction"); } //make sure you can close activity in less then 5 sec (stop is called) EmptyActivity activity = (EmptyActivity) mActivityRule.getActivity(); activity.finish(); // due to difference time when onStop start to process // on a test server and a local machine at first wait while onStart is started // to call try { WebtrekkLogging.log("start to wait activity stop procedure"); // wait while on start is called while (!activity.isStartedToStopping()) { Thread.yield(); } WebtrekkLogging.log("on stoping is started"); // just wait 5 seconds to check ANR not happened Thread.sleep(5000); } catch (InterruptedException e) { WebtrekkLogging.log("Sleep interruction"); } // check that activity is stopped if not this is ANR assertTrue(activity.isStopped()); // wait for finishing activity mActivityRule.afterActivityFinished(); }finally { //change delay to zero and cancel current delay WebtrekkLogging.log("Cancel HTTP request delay."); mHttpServer.setBeforeDelay(0); mHttpServer.stopBeforeDelay(); } // receive tracks waitForTrackedURLs(); } }
package com.magnet.demo.mmx.soapbox; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.magnet.mmx.client.MMXClient; import com.magnet.mmx.client.MMXTask; import com.magnet.mmx.client.common.MMXErrorMessage; import com.magnet.mmx.client.common.MMXException; import com.magnet.mmx.client.common.MMXMessage; import com.magnet.mmx.client.common.MMXSubscription; import com.magnet.mmx.client.common.MMXTopicInfo; import com.magnet.mmx.client.common.MMXTopicSearchResult; import com.magnet.mmx.client.common.MMXid; import com.magnet.mmx.protocol.MMXTopic; import com.magnet.mmx.protocol.SearchAction; import com.magnet.mmx.protocol.TopicAction; import com.magnet.mmx.protocol.TopicSummary; import java.util.ArrayList; import java.util.Date; import java.util.List; public class TopicListActivity extends Activity { private static final String TAG = TopicListActivity.class.getSimpleName(); public static final String EXTRA_TOPIC_NAME = "topicName"; private static final long MILLIS_IN_ONE_DAY = 24 * 60 * 60 * 1000l; static final int REQUEST_LOGIN = 1; private MMXClient mClient = null; private TopicsManager mTopicsManager = null; private Handler mSearchHandler = new Handler(); private ListView mListView = null; private EditText mSearchFilter = null; private TopicHeaderListAdapter mAdapter = null; private MMXTask<List<MMXSubscription>> mSubscriptionsTask = null; private MMXTask<MMXTopicSearchResult> mTopicsTask = null; private AdapterView.OnItemClickListener mOnItemClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String topicName = (String) view.getTag(); if (topicName != null) { Intent intent = new Intent(TopicListActivity.this, TopicItemListActivity.class); intent.putExtra(EXTRA_TOPIC_NAME, topicName); startActivity(intent); } } }; /** * Use this listener to be notified when we receive a message for a topic that we're subscribed to * so that we can update the counts. NOTE: onPubSubItemReceived() will only be called when messages * are published to subscribed topics. */ private MMXClient.MMXListener mMMXListener = new MMXClient.MMXListener() { public void onConnectionEvent(MMXClient mmxClient, MMXClient.ConnectionEvent connectionEvent) { } public void onMessageReceived(MMXClient mmxClient, MMXMessage mmxMessage, String s) { } public void onSendFailed(MMXClient mmxClient, String s) { } public void onMessageDelivered(MMXClient mmxClient, MMXid mmXid, String s) { } public void onPubsubItemReceived(MMXClient mmxClient, MMXTopic mmxTopic, MMXMessage mmxMessage) { updateTopicList(); } public void onErrorReceived(MMXClient mmxClient, MMXErrorMessage mmxErrorMessage) { } }; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_topic_list); mSearchFilter = (EditText) findViewById(R.id.search); mSearchFilter.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mSearchHandler.removeCallbacks(null); mSearchHandler.postDelayed(new Runnable() { public void run() { updateTopicList(); } }, 700); } @Override public void afterTextChanged(Editable s) { } }); mTopicsManager = TopicsManager.getInstance(this); mAdapter = new TopicHeaderListAdapter(this, mTopicsManager.getSubscribedTopics(mSearchFilter.getText().toString()), mTopicsManager.getOtherTopics(mSearchFilter.getText().toString())); mListView = (ListView) findViewById(R.id.topics_list); mListView.setOnItemClickListener(mOnItemClickListener); mClient = MMXClient.getInstance(this, R.raw.soapbox); MyMMXListener.getInstance(this).registerListener(mMMXListener); } protected void onDestroy() { MyMMXListener.getInstance(this).unregisterListener(mMMXListener); } protected void onResume() { super.onResume(); if (!mClient.isConnected()) { Intent loginIntent = new Intent(this, LoginActivity.class); startActivityForResult(loginIntent, REQUEST_LOGIN); } else { //populate or update the view updateTopicList(); } } private synchronized void updateTopicList() { if (mSubscriptionsTask == null) { mSubscriptionsTask = new MMXTask<List<MMXSubscription>>(mClient) { @Override public List<MMXSubscription> doRun(MMXClient mmxClient) throws Throwable { return mmxClient.getPubSubManager().listAllSubscriptions(); } @Override public void onException(Throwable exception) { Log.e(TAG, "subscriptionsTask() caught exception", exception); Toast.makeText(TopicListActivity.this, "Exception: " + exception.getMessage(), Toast.LENGTH_LONG).show(); synchronized (TopicListActivity.this) { mSubscriptionsTask = null; } } @Override public void onResult(List<MMXSubscription> result) { mTopicsManager.setSubscriptions(result); updateView(); synchronized (TopicListActivity.this) { mSubscriptionsTask = null; } } }; mSubscriptionsTask.execute(); } if (mTopicsTask == null) { mTopicsTask = new MMXTask<MMXTopicSearchResult>(mClient) { @Override public MMXTopicSearchResult doRun(MMXClient mmxClient) throws Throwable { return mmxClient.getPubSubManager().searchBy(SearchAction.Operator.OR, new TopicAction.TopicSearch(), null); } @Override public void onException(Throwable exception) { Log.e(TAG, "subscriptionsTask() caught exception", exception); Toast.makeText(TopicListActivity.this, "Exception: " + exception.getMessage(), Toast.LENGTH_LONG).show(); synchronized (TopicListActivity.this) { mTopicsTask = null; } } @Override public void onResult(MMXTopicSearchResult result) { mTopicsManager.setTopics(result.getResults()); ArrayList<MMXTopic> topicsList = new ArrayList<MMXTopic>(); for (MMXTopicInfo info : result.getResults()) { MMXTopic topic = info.getTopic(); if (topic.getName() != null && !topic.getName().isEmpty()) { topicsList.add(info.getTopic()); } } try { List<TopicSummary> summaries = mClient.getPubSubManager().getTopicSummary(topicsList, new Date(System.currentTimeMillis() - MILLIS_IN_ONE_DAY), null); mTopicsManager.setTopicSummaries(summaries); } catch (MMXException e) { Log.e(TAG, "Unable to retrieve topic summaries", e); } updateView(); synchronized (TopicListActivity.this) { mTopicsTask = null; } } }; mTopicsTask.execute(); } } private void updateView() { runOnUiThread(new Runnable() { public void run() { mAdapter = new TopicHeaderListAdapter(TopicListActivity.this, mTopicsManager.getSubscribedTopics(mSearchFilter.getText().toString()), mTopicsManager.getOtherTopics(mSearchFilter.getText().toString())); mListView.setAdapter(mAdapter); } }); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult() request=" + requestCode + ", result=" + resultCode); if (requestCode == REQUEST_LOGIN) { if (resultCode == RESULT_OK) { updateTopicList(); } else { finish(); } } } public void doLogout(View view) { DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: MMXTask<Void> logoutTask = new MMXTask<Void>(mClient) { @Override public Void doRun(MMXClient mmxClient) throws Throwable { mmxClient.disconnect(); return null; } @Override public void onResult(Void result) { TopicListActivity.this.finish(); } }; logoutTask.execute(); break; case DialogInterface.BUTTON_NEGATIVE: dialog.cancel(); break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Dialog) .setTitle(R.string.dlg_signout_title) .setMessage(R.string.dlg_signout_message) .setPositiveButton(R.string.dlg_signout_ok, clickListener) .setNegativeButton(R.string.dlg_signout_cancel, clickListener); builder.create().show(); } public void doAddTopic(View view) { Intent intent = new Intent(this, TopicAddActivity.class); startActivity(intent); } private static class TopicHeaderListAdapter extends BaseAdapter { private static final int TYPE_HEADER = 0; private static final int TYPE_TOPIC = 1; private Context mContext; private List<MMXTopic> mSubscriptions; private List<MMXTopic> mTopics; private LayoutInflater mLayoutInflater; private int mOtherTopicsHeaderPosition; private TopicsManager mTopicsManager; public TopicHeaderListAdapter(Context context, List<MMXTopic> subscriptions, List<MMXTopic> topics) { super(); mContext = context; mLayoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE); mTopicsManager = TopicsManager.getInstance(mContext); mSubscriptions = subscriptions; mTopics = topics; mOtherTopicsHeaderPosition = mSubscriptions.size() + 1; } @Override public int getCount() { return mSubscriptions.size() + mTopics.size() + 2; //two header rows } @Override public Object getItem(int position) { if (position == 0) { return mContext.getString(R.string.topic_list_header_subscriptions) + " (" + mSubscriptions.size() + ")"; } else if (position == mOtherTopicsHeaderPosition) { return mContext.getString(R.string.topic_list_header_other_topics) + " (" + mTopics.size() + ")"; } else { if (position < mOtherTopicsHeaderPosition) { int subscriptionsIndex = position - 1; return mSubscriptions.get(subscriptionsIndex); } else { //look into other topics int otherTopicsIndex = position - mSubscriptions.size() - 2; return mTopics.get(otherTopicsIndex); } } } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { int viewType = getItemViewType(position); switch (viewType) { case TYPE_HEADER: if (convertView == null) { convertView = mLayoutInflater.inflate(R.layout.topic_list_header, null); } String headerStr = (String) getItem(position); TextView headerText = (TextView) convertView.findViewById(R.id.headerText); headerText.setText(headerStr); convertView.setTag(null); convertView.setEnabled(false); break; case TYPE_TOPIC: if (convertView == null) { convertView = mLayoutInflater.inflate(R.layout.topic_list_item, null); } MMXTopic topic = (MMXTopic) getItem(position); populateTopicView(convertView, topic); break; } return convertView; } @Override public int getItemViewType(int position) { //H T T T T T H T T T T if (position == 0 || position == mOtherTopicsHeaderPosition) { return TYPE_HEADER; } return TYPE_TOPIC; } @Override public int getViewTypeCount() { //header view and topic view return 2; } private void populateTopicView(View view, MMXTopic topic) { TextView topicNameView = (TextView) view.findViewById(R.id.topic_name); String topicName = topic.getName(); topicNameView.setText(topicName); TextView countView = (TextView) view.findViewById(R.id.new_item_count); TopicSummary summary = mTopicsManager.getTopicSummary(topic); int count = summary == null ? 0 : summary.getCount(); if (count > 0) { countView.setVisibility(View.VISIBLE); countView.setText(String.valueOf(count)); } else { countView.setVisibility(View.INVISIBLE); countView.setText(null); } view.setTag(topicName); } } }
package com.krishagni.catissueplus.core.biospecimen.domain; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.StringUtils; import org.hibernate.envers.Audited; import org.hibernate.envers.NotAudited; import org.hibernate.envers.RelationTargetAuditMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.beans.factory.annotation.Qualifier; import com.krishagni.catissueplus.core.administrative.domain.DistributionOrderItem; import com.krishagni.catissueplus.core.administrative.domain.DistributionProtocol; import com.krishagni.catissueplus.core.administrative.domain.SpecimenReservedEvent; import com.krishagni.catissueplus.core.administrative.domain.StorageContainer; import com.krishagni.catissueplus.core.administrative.domain.StorageContainerPosition; import com.krishagni.catissueplus.core.administrative.domain.User; import com.krishagni.catissueplus.core.biospecimen.domain.factory.SpecimenErrorCode; import com.krishagni.catissueplus.core.biospecimen.domain.factory.SpecimenReturnEvent; import com.krishagni.catissueplus.core.biospecimen.domain.factory.VisitErrorCode; import com.krishagni.catissueplus.core.biospecimen.repository.DaoFactory; import com.krishagni.catissueplus.core.common.access.AccessCtrlMgr; import com.krishagni.catissueplus.core.common.domain.PrintItem; import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException; import com.krishagni.catissueplus.core.common.events.DependentEntityDetail; import com.krishagni.catissueplus.core.common.service.LabelGenerator; import com.krishagni.catissueplus.core.common.service.LabelPrinter; import com.krishagni.catissueplus.core.common.service.impl.EventPublisher; import com.krishagni.catissueplus.core.common.util.AuthUtil; import com.krishagni.catissueplus.core.common.util.NumUtil; import com.krishagni.catissueplus.core.common.util.Status; import com.krishagni.catissueplus.core.common.util.Utility; import com.krishagni.catissueplus.core.de.services.impl.FormUtil; @Configurable @Audited public class Specimen extends BaseExtensionEntity { public static final String NEW = "New"; public static final String ALIQUOT = "Aliquot"; public static final String DERIVED = "Derived"; public static final String COLLECTED = "Collected"; public static final String PENDING = "Pending"; public static final String MISSED_COLLECTION = "Missed Collection"; public static final String NOT_COLLECTED = "Not Collected"; public static final String ACCEPTABLE = "Acceptable"; public static final String NOT_SPECIFIED = "Not Specified"; public static final String EXTN = "SpecimenExtension"; private static final String ENTITY_NAME = "specimen"; private String tissueSite; private String tissueSide; private String pathologicalStatus; private String lineage; private BigDecimal initialQuantity; private String specimenClass; private String specimenType; private BigDecimal concentration; private String label; private String activityStatus; private String barcode; private String comment; private Date createdOn; private String imageId; private BigDecimal availableQuantity; private String collectionStatus; private Set<String> biohazards = new HashSet<>(); private Integer freezeThawCycles; private CollectionProtocol collectionProtocol; private Visit visit; private SpecimenRequirement specimenRequirement; private StorageContainerPosition position; private Specimen parentSpecimen; private Set<Specimen> childCollection = new HashSet<>(); private Specimen pooledSpecimen; private Set<Specimen> specimensPool = new HashSet<>(); private Set<SpecimenExternalIdentifier> externalIds = new HashSet<>(); // records aliquot or derivative events that have occurred on this specimen private Set<SpecimenChildrenEvent> childrenEvents = new LinkedHashSet<>(); // records the event through which this specimen got created private SpecimenChildrenEvent parentEvent; // collectionEvent and receivedEvent are valid only for primary specimens private SpecimenCollectionEvent collectionEvent; private SpecimenReceivedEvent receivedEvent; // record the DP for which this specimen is currently reserved private SpecimenReservedEvent reservedEvent; // Available for all specimens in hierarchy based on values set for primary specimens private SpecimenCollectionReceiveDetail collRecvDetails; private List<SpecimenTransferEvent> transferEvents; private Set<SpecimenListItem> specimenListItems = new HashSet<>(); private boolean concentrationInit = false; @Autowired @Qualifier("specimenLabelGenerator") private LabelGenerator labelGenerator; @Autowired @Qualifier("specimenBarcodeGenerator") private LabelGenerator barcodeGenerator; @Autowired private DaoFactory daoFactory; private transient boolean forceDelete; private transient boolean printLabel; private transient boolean freezeThawIncremented; private transient Date transferTime; private transient String transferComments; private transient boolean autoCollectParents; private transient boolean updated; private transient String uid; private transient String parentUid; // holdingLocation and dp are used during distribution to record the location // where the specimen will be stored temporarily post distribution. private transient StorageContainerPosition holdingLocation; private transient DistributionProtocol dp; // Records the derivatives or aliquots created from this specimen in current action/transaction private transient SpecimenChildrenEvent derivativeEvent; private transient SpecimenChildrenEvent aliquotEvent; public static String getEntityName() { return ENTITY_NAME; } public String getTissueSite() { return tissueSite; } public void setTissueSite(String tissueSite) { if (StringUtils.isNotBlank(this.tissueSite) && !this.tissueSite.equals(tissueSite)) { getChildCollection().stream() .filter(child -> child.isAliquot() || this.tissueSite.equals(child.getTissueSite())) .forEach(child -> child.setTissueSite(tissueSite)); getSpecimensPool().forEach(poolSpmn -> poolSpmn.setTissueSite(tissueSite)); } this.tissueSite = tissueSite; } public String getTissueSide() { return tissueSide; } public void setTissueSide(String tissueSide) { if (StringUtils.isNotBlank(this.tissueSide) && !this.tissueSide.equals(tissueSide)) { getChildCollection().stream() .filter(child -> child.isAliquot() || this.tissueSide.equals(child.getTissueSide())) .forEach(child -> child.setTissueSide(tissueSide)); getSpecimensPool().forEach(poolSpmn -> poolSpmn.setTissueSide(tissueSide)); } this.tissueSide = tissueSide; } public String getPathologicalStatus() { return pathologicalStatus; } public void setPathologicalStatus(String pathologicalStatus) { if (StringUtils.isNotBlank(this.pathologicalStatus) && !this.pathologicalStatus.equals(pathologicalStatus)) { for (Specimen child : getChildCollection()) { if (child.isAliquot()) { child.setPathologicalStatus(pathologicalStatus); } } for (Specimen poolSpecimen : getSpecimensPool()) { poolSpecimen.setPathologicalStatus(pathologicalStatus); } } this.pathologicalStatus = pathologicalStatus; } public String getLineage() { return lineage; } public void setLineage(String lineage) { this.lineage = lineage; } public BigDecimal getInitialQuantity() { return initialQuantity; } public void setInitialQuantity(BigDecimal initialQuantity) { this.initialQuantity = initialQuantity; } public String getSpecimenClass() { return specimenClass; } public void setSpecimenClass(String specimenClass) { if (StringUtils.isNotBlank(this.specimenClass) && !this.specimenClass.equals(specimenClass)) { for (Specimen child : getChildCollection()) { if (child.isAliquot()) { child.setSpecimenClass(specimenClass); } } for (Specimen poolSpecimen : getSpecimensPool()) { poolSpecimen.setSpecimenClass(specimenClass); } } this.specimenClass = specimenClass; } public String getSpecimenType() { return specimenType; } public void setSpecimenType(String specimenType) { if (StringUtils.isNotBlank(this.specimenType) && !this.specimenType.equals(specimenType)) { for (Specimen child : getChildCollection()) { if (child.isAliquot()) { child.setSpecimenType(specimenType); } } for (Specimen poolSpecimen : getSpecimensPool()) { poolSpecimen.setSpecimenType(specimenType); } } this.specimenType = specimenType; } public BigDecimal getConcentration() { return concentration; } public void setConcentration(BigDecimal concentration) { if (concentrationInit) { if (this.concentration == concentration) { return; } if (this.concentration == null || !this.concentration.equals(concentration)) { for (Specimen child : getChildCollection()) { if (ObjectUtils.equals(this.concentration, child.getConcentration()) && child.isAliquot()) { child.setConcentration(concentration); } } for (Specimen poolSpecimen : getSpecimensPool()) { poolSpecimen.setConcentration(concentration); } } } this.concentration = concentration; this.concentrationInit = true; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getActivityStatus() { return activityStatus; } public void setActivityStatus(String activityStatus) { if (StringUtils.isBlank(activityStatus)) { activityStatus = Status.ACTIVITY_STATUS_ACTIVE.getStatus(); } this.activityStatus = activityStatus; } public String getBarcode() { return barcode; } public void setBarcode(String barcode) { this.barcode = barcode; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public Date getCreatedOn() { return Utility.chopSeconds(createdOn); } public void setCreatedOn(Date createdOn) { this.createdOn = Utility.chopSeconds(createdOn); } public String getImageId() { return imageId; } public void setImageId(String imageId) { this.imageId = imageId; } public BigDecimal getAvailableQuantity() { return availableQuantity; } public void setAvailableQuantity(BigDecimal availableQuantity) { this.availableQuantity = availableQuantity; } public String getCollectionStatus() { return collectionStatus; } public void setCollectionStatus(String collectionStatus) { this.collectionStatus = collectionStatus; } public Set<String> getBiohazards() { return biohazards; } public void setBiohazards(Set<String> biohazards) { this.biohazards = biohazards; } public void updateBiohazards(Set<String> biohazards) { getBiohazards().addAll(biohazards); getBiohazards().retainAll(biohazards); for (Specimen child : getChildCollection()) { if (child.isAliquot()) { child.updateBiohazards(biohazards); } } for (Specimen poolSpecimen : getSpecimensPool()) { poolSpecimen.updateBiohazards(biohazards); } } public Integer getFreezeThawCycles() { return freezeThawCycles; } public void setFreezeThawCycles(Integer freezeThawCycles) { this.freezeThawCycles = freezeThawCycles; } public CollectionProtocol getCollectionProtocol() { return collectionProtocol; } public void setCollectionProtocol(CollectionProtocol collectionProtocol) { this.collectionProtocol = collectionProtocol; } public Visit getVisit() { return visit; } public void setVisit(Visit visit) { this.visit = visit; } public SpecimenRequirement getSpecimenRequirement() { return specimenRequirement; } public void setSpecimenRequirement(SpecimenRequirement specimenRequirement) { this.specimenRequirement = specimenRequirement; } public StorageContainerPosition getPosition() { return position; } public void setPosition(StorageContainerPosition position) { this.position = position; } public Specimen getParentSpecimen() { return parentSpecimen; } public void setParentSpecimen(Specimen parentSpecimen) { this.parentSpecimen = parentSpecimen; } @NotAudited public Set<Specimen> getChildCollection() { return childCollection; } public void setChildCollection(Set<Specimen> childSpecimenCollection) { this.childCollection = childSpecimenCollection; } public Specimen getPooledSpecimen() { return pooledSpecimen; } public void setPooledSpecimen(Specimen pooledSpecimen) { this.pooledSpecimen = pooledSpecimen; } @NotAudited public Set<Specimen> getSpecimensPool() { return specimensPool; } public void setSpecimensPool(Set<Specimen> specimensPool) { this.specimensPool = specimensPool; } public Set<SpecimenExternalIdentifier> getExternalIds() { return externalIds; } public void setExternalIds(Set<SpecimenExternalIdentifier> externalIds) { this.externalIds = externalIds; } @NotAudited public Set<SpecimenChildrenEvent> getChildrenEvents() { return childrenEvents; } public void setChildrenEvents(Set<SpecimenChildrenEvent> childrenEvents) { this.childrenEvents = childrenEvents; } @NotAudited public SpecimenChildrenEvent getParentEvent() { return parentEvent; } public void setParentEvent(SpecimenChildrenEvent parentEvent) { this.parentEvent = parentEvent; } @NotAudited public SpecimenCollectionEvent getCollectionEvent() { if (isAliquot() || isDerivative()) { return null; } if (this.collectionEvent == null) { this.collectionEvent = SpecimenCollectionEvent.getFor(this); } if (this.collectionEvent == null) { this.collectionEvent = SpecimenCollectionEvent.createFromSr(this); } return this.collectionEvent; } public void setCollectionEvent(SpecimenCollectionEvent collectionEvent) { this.collectionEvent = collectionEvent; } @NotAudited public SpecimenReceivedEvent getReceivedEvent() { if (isAliquot() || isDerivative()) { return null; } if (this.receivedEvent == null) { this.receivedEvent = SpecimenReceivedEvent.getFor(this); } if (this.receivedEvent == null) { this.receivedEvent = SpecimenReceivedEvent.createFromSr(this); } return this.receivedEvent; } public void setReceivedEvent(SpecimenReceivedEvent receivedEvent) { this.receivedEvent = receivedEvent; } @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) public SpecimenReservedEvent getReservedEvent() { return reservedEvent; } public void setReservedEvent(SpecimenReservedEvent reservedEvent) { this.reservedEvent = reservedEvent; } @NotAudited public SpecimenCollectionReceiveDetail getCollRecvDetails() { return collRecvDetails; } public void setCollRecvDetails(SpecimenCollectionReceiveDetail collRecvDetails) { this.collRecvDetails = collRecvDetails; } @NotAudited public List<SpecimenTransferEvent> getTransferEvents() { if (this.transferEvents == null) { this.transferEvents = SpecimenTransferEvent.getFor(this); } return this.transferEvents; } @NotAudited public Set<SpecimenListItem> getSpecimenListItems() { return specimenListItems; } public void setSpecimenListItems(Set<SpecimenListItem> specimenListItems) { this.specimenListItems = specimenListItems; } public Set<DistributionProtocol> getDistributionProtocols() { return getCollectionProtocol().getDistributionProtocols(); } public LabelGenerator getLabelGenerator() { return labelGenerator; } public void setLabelGenerator(LabelGenerator labelGenerator) { this.labelGenerator = labelGenerator; } @Override public String getEntityType() { return EXTN; } @Override public Long getCpId() { return getCollectionProtocol().getId(); } public String getCpShortTitle() { return getCollectionProtocol().getShortTitle(); } public boolean isForceDelete() { return forceDelete; } public void setForceDelete(boolean forceDelete) { this.forceDelete = forceDelete; } public Date getTransferTime() { return transferTime; } public void setTransferTime(Date transferTime) { this.transferTime = transferTime; } public String getTransferComments() { return transferComments; } public void setTransferComments(String transferComments) { this.transferComments = transferComments; } public boolean isAutoCollectParents() { return autoCollectParents; } public void setAutoCollectParents(boolean autoCollectParents) { this.autoCollectParents = autoCollectParents; } public boolean isUpdated() { return updated; } public void setUpdated(boolean updated) { this.updated = updated; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getParentUid() { return parentUid; } public void setParentUid(String parentUid) { this.parentUid = parentUid; } public StorageContainerPosition getHoldingLocation() { return holdingLocation; } public void setHoldingLocation(StorageContainerPosition holdingLocation) { this.holdingLocation = holdingLocation; } public DistributionProtocol getDp() { return dp; } public void setDp(DistributionProtocol dp) { this.dp = dp; } public boolean isPrintLabel() { return printLabel; } public void setPrintLabel(boolean printLabel) { this.printLabel = printLabel; } public boolean isActive() { return Status.ACTIVITY_STATUS_ACTIVE.getStatus().equals(getActivityStatus()); } public boolean isClosed() { return Status.ACTIVITY_STATUS_CLOSED.getStatus().equals(getActivityStatus()); } public boolean isActiveOrClosed() { return isActive() || isClosed(); } public boolean isDeleted() { return Status.ACTIVITY_STATUS_DISABLED.getStatus().equals(getActivityStatus()); } public boolean isReserved() { return getReservedEvent() != null; } public boolean isEditAllowed() { return !isReserved() && isActive(); } public boolean isAliquot() { return ALIQUOT.equals(lineage); } public boolean isDerivative() { return DERIVED.equals(lineage); } public boolean isPrimary() { return NEW.equals(lineage); } public boolean isPoolSpecimen() { return getPooledSpecimen() != null; } public boolean isPooled() { return getSpecimenRequirement() != null && getSpecimenRequirement().isPooledSpecimenReq(); } public boolean isCollected() { return isCollected(getCollectionStatus()); } public boolean isPending() { return isPending(getCollectionStatus()); } public boolean isMissed() { return isMissed(getCollectionStatus()); } public boolean isNotCollected() { return isNotCollected(getCollectionStatus()); } public boolean isMissedOrNotCollected() { return isMissed() || isNotCollected(); } public Boolean isAvailable() { return getAvailableQuantity() == null || NumUtil.greaterThanZero(getAvailableQuantity()); } public void disable() { disable(!isForceDelete()); } public void disable(boolean checkChildSpecimens) { if (getActivityStatus().equals(Status.ACTIVITY_STATUS_DISABLED.getStatus())) { return; } if (checkChildSpecimens) { ensureNoActiveChildSpecimens(); } for (Specimen child : getChildCollection()) { child.disable(checkChildSpecimens); } for (Specimen specimen : getSpecimensPool()) { specimen.disable(checkChildSpecimens); } virtualize(null, "Specimen deleted"); setLabel(Utility.getDisabledValue(getLabel(), 255)); setBarcode(Utility.getDisabledValue(getBarcode(), 255)); setActivityStatus(Status.ACTIVITY_STATUS_DISABLED.getStatus()); FormUtil.getInstance().deleteRecords(getCpId(), Arrays.asList("Specimen", "SpecimenEvent", "SpecimenExtension"), getId()); } public static boolean isCollected(String status) { return COLLECTED.equals(status); } public static boolean isPending(String status) { return PENDING.equals(status); } public static boolean isMissed(String status) { return MISSED_COLLECTION.equals(status); } public static boolean isNotCollected(String status) { return NOT_COLLECTED.equals(status); } public boolean isPrePrintEnabled() { return getSpecimenRequirement() != null && getSpecimenRequirement().getLabelAutoPrintModeToUse() == CollectionProtocol.SpecimenLabelAutoPrintMode.PRE_PRINT; } public void prePrintChildrenLabels(String prevStatus, LabelPrinter<Specimen> printer) { if (getSpecimenRequirement() == null) { // We pre-print child specimen labels of only planned specimens return; } if (!isPrimary()) { // We pre-print child specimen labels of only primary specimens return; } if (!isCollected() || getCollectionProtocol().getSpmnLabelPrePrintMode() != CollectionProtocol.SpecimenLabelPrePrintMode.ON_PRIMARY_COLL) { // specimen is either not collected or print on collection is not enabled return; } if (Specimen.isCollected(prevStatus)) { // specimen was previously collected. no need to print the child specimen labels return; } if (getCollectionProtocol().isManualSpecLabelEnabled()) { // no child labels are pre-printed in specimen labels are manually scanned return; } if (CollectionUtils.isNotEmpty(getChildCollection())) { // We quit if there is at least one child specimen created underneath the primary specimen return; } List<PrintItem<Specimen>> printItems = createPendingSpecimens(getSpecimenRequirement(), this).stream() .filter(spmn -> spmn.getParentSpecimen().equals(this)) .map(Specimen::getPrePrintItems) .flatMap(List::stream) .collect(Collectors.toList()); if (!printItems.isEmpty()) { printer.print(printItems); } } public List<PrintItem<Specimen>> getPrePrintItems() { SpecimenRequirement requirement = getSpecimenRequirement(); if (requirement == null) { // OPSMN-4227: We won't pre-print unplanned specimens // This can happen when following state change transition happens: // visit -> completed -> planned + unplanned specimens collected -> visit missed -> pending return Collections.emptyList(); } List<PrintItem<Specimen>> result = new ArrayList<>(); if (requirement.getLabelAutoPrintModeToUse() == CollectionProtocol.SpecimenLabelAutoPrintMode.PRE_PRINT) { Integer printCopies = requirement.getLabelPrintCopiesToUse(); result.add(PrintItem.make(this, printCopies)); } for (Specimen poolSpmn : getSpecimensPool()) { result.addAll(poolSpmn.getPrePrintItems()); } for (Specimen childSpmn : getChildCollection()) { result.addAll(childSpmn.getPrePrintItems()); } return result; } public void close(User user, Date time, String reason) { if (!getActivityStatus().equals(Status.ACTIVITY_STATUS_ACTIVE.getStatus())) { return; } transferTo(holdingLocation, user, time, reason); addDisposalEvent(user, time, reason); setActivityStatus(Status.ACTIVITY_STATUS_CLOSED.getStatus()); } public List<DependentEntityDetail> getDependentEntities() { return DependentEntityDetail.singletonList(Specimen.getEntityName(), getActiveChildSpecimens()); } public void activate() { if (getActivityStatus().equals(Status.ACTIVITY_STATUS_ACTIVE.getStatus())) { return; } setActivityStatus(Status.ACTIVITY_STATUS_ACTIVE.getStatus()); // TODO: we need to add a reopen event here } public CollectionProtocolRegistration getRegistration() { return getVisit().getRegistration(); } public List<Specimen> getDescendants() { List<Specimen> result = new ArrayList<>(); result.add(this); for (Specimen specimen : getChildCollection()) { result.addAll(specimen.getDescendants()); } return result; } public void update(Specimen specimen) { boolean wasCollected = isCollected(); setForceDelete(specimen.isForceDelete()); setAutoCollectParents(specimen.isAutoCollectParents()); setOpComments(specimen.getOpComments()); String reason = null; if (!StringUtils.equals(getComment(), specimen.getComment())) { reason = specimen.getComment(); } updateStatus(specimen, reason); // NOTE: This has been commented to allow retrieving distributed specimens from the holding tanks // if (!isActive()) { // return; setLabel(specimen.getLabel()); setBarcode(specimen.getBarcode()); setImageId(specimen.getImageId()); setInitialQuantity(specimen.getInitialQuantity()); setAvailableQuantity(specimen.getAvailableQuantity()); setConcentration((isPoolSpecimen() ? getPooledSpecimen() : specimen).getConcentration()); if (!getVisit().equals(specimen.getVisit())) { if (isPrimary()) { updateVisit(specimen.getVisit(), specimen.getSpecimenRequirement()); } else { throw OpenSpecimenException.userError(SpecimenErrorCode.VISIT_CHG_NOT_ALLOWED, getLabel()); } } updateExternalIds(specimen.getExternalIds()); updateEvent(getCollectionEvent(), specimen.getCollectionEvent()); updateEvent(getReceivedEvent(), specimen.getReceivedEvent()); updateCollectionStatus(specimen.getCollectionStatus()); updatePosition(specimen.getPosition(), null, specimen.getTransferTime(), specimen.getTransferComments()); if (isCollected()) { if (isPrimary()) { updateCreatedOn(Utility.chopSeconds(getReceivedEvent().getTime())); } else { updateCreatedOn(specimen.getCreatedOn() != null ? specimen.getCreatedOn() : Calendar.getInstance().getTime()); if (!wasCollected) { getParentSpecimen().addToChildrenEvent(this); } } } else { updateCreatedOn(null); } // TODO: Specimen class/type should not be allowed to change Specimen spmnToUpdateFrom = null; if (isAliquot()) { spmnToUpdateFrom = getParentSpecimen(); } else if (isPoolSpecimen()) { spmnToUpdateFrom = getPooledSpecimen(); } else { spmnToUpdateFrom = specimen; } setTissueSite(spmnToUpdateFrom.getTissueSite()); setTissueSide(spmnToUpdateFrom.getTissueSide()); setSpecimenClass(spmnToUpdateFrom.getSpecimenClass()); setSpecimenType(spmnToUpdateFrom.getSpecimenType()); updateBiohazards(spmnToUpdateFrom.getBiohazards()); setPathologicalStatus(spmnToUpdateFrom.getPathologicalStatus()); setComment(specimen.getComment()); setExtension(specimen.getExtension()); setPrintLabel(specimen.isPrintLabel()); setFreezeThawCycles(specimen.getFreezeThawCycles()); setUpdated(true); } public void updateStatus(Specimen otherSpecimen, String reason) { updateStatus(otherSpecimen.getActivityStatus(), AuthUtil.getCurrentUser(), Calendar.getInstance().getTime(), reason, isForceDelete()); // OPSMN-4629 // the specimen is in closed state and has no position. // ensure the new updatable specimen has no position either. if (!isActive()) { otherSpecimen.setPosition(null); } } // TODO: Modify to accommodate pooled specimens public void updateStatus(String activityStatus, User user, Date date, String reason, boolean isForceDelete) { if (isReserved()) { throw OpenSpecimenException.userError(SpecimenErrorCode.EDIT_NOT_ALLOWED, getLabel()); } if (this.activityStatus != null && this.activityStatus.equals(activityStatus)) { return; } if (Status.ACTIVITY_STATUS_DISABLED.getStatus().equals(activityStatus)) { disable(!isForceDelete); } else if (Status.ACTIVITY_STATUS_CLOSED.getStatus().equals(activityStatus)) { close(user, date, reason); } else if (Status.ACTIVITY_STATUS_ACTIVE.getStatus().equals(activityStatus)) { activate(); } } public void updateCollectionStatus(String collectionStatus) { if (collectionStatus.equals(getCollectionStatus())) { // no change in collection status; therefore nothing needs to be done return; } if (isMissed(collectionStatus)) { if (!getVisit().isCompleted() && !getVisit().isMissed()) { throw OpenSpecimenException.userError(VisitErrorCode.COMPL_OR_MISSED_VISIT_REQ); } else if (getParentSpecimen() != null && !getParentSpecimen().isCollected() && !getParentSpecimen().isMissed()) { throw OpenSpecimenException.userError(SpecimenErrorCode.COLL_OR_MISSED_PARENT_REQ); } else { updateHierarchyStatus(collectionStatus); createMissedChildSpecimens(); } } else if (isNotCollected(collectionStatus)) { if (!getVisit().isCompleted() && !getVisit().isNotCollected()) { throw OpenSpecimenException.userError(VisitErrorCode.COMPL_OR_NC_VISIT_REQ); } else if (getParentSpecimen() != null && !getParentSpecimen().isCollected() && !getParentSpecimen().isNotCollected()) { throw OpenSpecimenException.userError(SpecimenErrorCode.COLL_OR_NC_PARENT_REQ); } else { updateHierarchyStatus(collectionStatus); createNotCollectedSpecimens(); } } else if (isPending(collectionStatus)) { if (!getVisit().isCompleted() && !getVisit().isPending()) { throw OpenSpecimenException.userError(VisitErrorCode.COMPL_OR_PENDING_VISIT_REQ); } else if (getParentSpecimen() != null && !getParentSpecimen().isCollected() && !getParentSpecimen().isPending()) { throw OpenSpecimenException.userError(SpecimenErrorCode.COLL_OR_PENDING_PARENT_REQ); } else { updateHierarchyStatus(collectionStatus); } } else if (isCollected(collectionStatus)) { if (!getVisit().isCompleted()) { throw OpenSpecimenException.userError(VisitErrorCode.COMPL_VISIT_REQ); } else { if (getParentSpecimen() != null && !getParentSpecimen().isCollected()) { if (!autoCollectParents) { throw OpenSpecimenException.userError(SpecimenErrorCode.COLL_PARENT_REQ); } autoCollectParentSpecimens(this); } setCollectionStatus(collectionStatus); decAliquotedQtyFromParent(); addOrUpdateCollRecvEvents(); } } checkPoolStatusConstraints(); } public void distribute(DistributionOrderItem item) { if (!isCollected() || isClosed()) { throw OpenSpecimenException.userError(SpecimenErrorCode.NOT_AVAILABLE_FOR_DIST, getLabel()); } // Deduct distributed quantity from available quantity if (getAvailableQuantity() != null) { if (NumUtil.greaterThanEquals(getAvailableQuantity(), item.getQuantity())) { setAvailableQuantity(getAvailableQuantity().subtract(item.getQuantity())); } else { setAvailableQuantity(BigDecimal.ZERO); } } // add distributed event SpecimenDistributionEvent.createForDistributionOrderItem(item).saveRecordEntry(); // cancel the reservation so that it can be distributed subsequently if available setReservedEvent(null); // close specimen if explicitly closed or no quantity available if (NumUtil.isZero(getAvailableQuantity()) || item.isDistributedAndClosed()) { String dpShortTitle = item.getOrder().getDistributionProtocol().getShortTitle(); close(item.getOrder().getDistributor(), item.getOrder().getExecutionDate(), "Distributed to " + dpShortTitle); } } public void updateCreatedOn(Date createdOn) { this.createdOn = createdOn; if (createdOn == null) { for (Specimen childSpecimen : getChildCollection()) { childSpecimen.updateCreatedOn(createdOn); } return; } if (createdOn.after(Calendar.getInstance().getTime())) { throw OpenSpecimenException.userError(SpecimenErrorCode.CREATED_ON_GT_CURRENT); } // The below code is commented for now, so that there will not be any issue for the legacy data. // While migrating time part of the date is set as 00:00:00, // So there is large possibility of below 2 exceptions. /*if (!isPrimary() && createdOn.before(getParentSpecimen().getCreatedOn())) { throw OpenSpecimenException.userError(SpecimenErrorCode.CHILD_CREATED_ON_LT_PARENT); } for (Specimen childSpecimen : getChildCollection()) { if (childSpecimen.getCreatedOn() != null && createdOn.after(childSpecimen.getCreatedOn())) { throw OpenSpecimenException.userError(SpecimenErrorCode.PARENT_CREATED_ON_GT_CHILDREN); } }*/ } public void returnSpecimen(DistributionOrderItem item) { if (isClosed()) { setAvailableQuantity(item.getReturnedQuantity()); activate(); } else { if (getAvailableQuantity() == null) { setAvailableQuantity(item.getReturnedQuantity()); } else { setAvailableQuantity(getAvailableQuantity().add(item.getReturnedQuantity())); } } StorageContainer container = item.getReturningContainer(); if (container != null) { StorageContainerPosition position = container.createPosition(item.getReturningColumn(), item.getReturningRow()); transferTo(position, item.getReturnDate(), "Specimen returned"); } SpecimenReturnEvent.createForDistributionOrderItem(item).saveRecordEntry(); } private void addDisposalEvent(User user, Date time, String reason) { SpecimenDisposalEvent event = new SpecimenDisposalEvent(this); event.setReason(reason); event.setUser(user); event.setTime(time); event.saveOrUpdate(); } private void virtualize(Date time, String comments) { transferTo(null, time, comments); } private void transferTo(StorageContainerPosition newPosition, Date time, String comments) { transferTo(newPosition, null, time, comments); } private void transferTo(StorageContainerPosition newPosition, User user, Date time, String comments) { StorageContainerPosition oldPosition = getPosition(); if (StorageContainerPosition.areSame(oldPosition, newPosition)) { return; } if (oldPosition != null && !oldPosition.isSupressAccessChecks()) { AccessCtrlMgr.getInstance().ensureSpecimenStoreRights(oldPosition.getContainer()); } if (newPosition != null && !newPosition.isSupressAccessChecks()) { AccessCtrlMgr.getInstance().ensureSpecimenStoreRights(newPosition.getContainer()); } SpecimenTransferEvent transferEvent = new SpecimenTransferEvent(this); transferEvent.setUser(user == null ? AuthUtil.getCurrentUser() : user); transferEvent.setTime(time == null ? Calendar.getInstance().getTime() : time); transferEvent.setComments(comments); if (oldPosition != null && newPosition != null) { oldPosition.getContainer().retrieveSpecimen(this); newPosition.getContainer().storeSpecimen(this); transferEvent.setFromLocation(oldPosition); transferEvent.setToLocation(newPosition); oldPosition.update(newPosition); } else if (oldPosition != null) { oldPosition.getContainer().retrieveSpecimen(this); transferEvent.setFromLocation(oldPosition); oldPosition.vacate(); setPosition(null); } else if (newPosition != null) { newPosition.getContainer().storeSpecimen(this); transferEvent.setToLocation(newPosition); newPosition.setOccupyingSpecimen(this); newPosition.occupy(); setPosition(newPosition); } transferEvent.saveOrUpdate(); } public void addChildSpecimen(Specimen specimen) { specimen.setParentSpecimen(this); if (!isCollected() && specimen.isCollected()) { if (!specimen.autoCollectParents) { throw OpenSpecimenException.userError(SpecimenErrorCode.COLL_PARENT_REQ); } autoCollectParentSpecimens(specimen); } if (specimen.isAliquot()) { specimen.decAliquotedQtyFromParent(); } if (specimen.getCreatedOn() != null && specimen.getCreatedOn().before(getCreatedOn())) { throw OpenSpecimenException.userError(SpecimenErrorCode.CHILD_CREATED_ON_LT_PARENT); } specimen.occupyPosition(); getChildCollection().add(specimen); addToChildrenEvent(specimen); } public void addPoolSpecimen(Specimen specimen) { specimen.setPooledSpecimen(this); specimen.occupyPosition(); getSpecimensPool().add(specimen); } public void setPending() { updateCollectionStatus(PENDING); } public void decAliquotedQtyFromParent() { if (isCollected() && isAliquot()) { adjustParentSpecimenQty(initialQuantity); } } public void occupyPosition() { if (position == null) { return; } if (!isCollected()) { // Un-collected (pending/missed collection) specimens can't occupy space position = null; return; } position.getContainer().storeSpecimen(this); position.occupy(); } public void addOrUpdateCollRecvEvents() { if (!isCollected()) { return; } addOrUpdateCollectionEvent(); addOrUpdateReceivedEvent(); } public void setLabelIfEmpty() { if (StringUtils.isNotBlank(label) || isMissedOrNotCollected()) { return; } String labelTmpl = getLabelTmpl(); String label = null; if (StringUtils.isNotBlank(labelTmpl)) { label = labelGenerator.generateLabel(labelTmpl, this); } else if (isAliquot() || isDerivative()) { Specimen parentSpecimen = getParentSpecimen(); int count = parentSpecimen.getChildCollection().size(); label = parentSpecimen.getLabel() + "_" + (count + 1); } if (StringUtils.isBlank(label)) { throw OpenSpecimenException.userError(SpecimenErrorCode.LABEL_REQUIRED); } setLabel(label); } public void setBarcodeIfEmpty() { if (StringUtils.isNotBlank(barcode) || isMissedOrNotCollected()) { return; } String barcodeTmpl = getCollectionProtocol().getSpecimenBarcodeFormatToUse(); if (StringUtils.isNotBlank(barcodeTmpl)) { setBarcode(barcodeGenerator.generateLabel(barcodeTmpl, this)); } } public String getLabelTmpl() { String labelTmpl = null; SpecimenRequirement sr = getSpecimenRequirement(); if (sr != null) { // anticipated specimen labelTmpl = sr.getLabelFormat(); } if (StringUtils.isNotBlank(labelTmpl)) { return labelTmpl; } CollectionProtocol cp = getVisit().getCollectionProtocol(); if (isAliquot()) { labelTmpl = cp.getAliquotLabelFormatToUse(); } else if (isDerivative()) { labelTmpl = cp.getDerivativeLabelFormat(); } else { labelTmpl = cp.getSpecimenLabelFormat(); } return labelTmpl; } public void updatePosition(StorageContainerPosition newPosition) { updatePosition(newPosition, null); } public void updatePosition(StorageContainerPosition newPosition, Date time) { updatePosition(newPosition, null, time, null); } public void updatePosition(StorageContainerPosition newPosition, User user, Date time, String comments) { if (!isCollected()) { return; } if (newPosition != null) { StorageContainer container = newPosition.getContainer(); if (container == null || (!container.isDimensionless() && !newPosition.isSpecified())) { newPosition = null; } } transferTo(newPosition, user, time, comments); } public String getLabelOrDesc() { if (StringUtils.isNotBlank(label)) { return label; } return getDesc(specimenClass, specimenType); } public void incrementFreezeThaw(Integer incrementFreezeThaw) { if (freezeThawIncremented) { return; } if (incrementFreezeThaw == null || incrementFreezeThaw <= 0) { return; } if (getFreezeThawCycles() == null) { setFreezeThawCycles(incrementFreezeThaw); } else { setFreezeThawCycles(getFreezeThawCycles() + incrementFreezeThaw); } freezeThawIncremented = true; } public boolean isStoredInDistributionContainer() { return getPosition() != null && getPosition().getContainer().isDistributionContainer(); } public void initCollections() { getBiohazards().size(); getExternalIds().size(); } public static String getDesc(String specimenClass, String type) { StringBuilder desc = new StringBuilder(); if (StringUtils.isNotBlank(specimenClass)) { desc.append(specimenClass); } if (StringUtils.isNotBlank(type)) { if (desc.length() > 0) { desc.append("-"); } desc.append(type); } return desc.toString(); } // Useful for sorting specimens at same level public static List<Specimen> sort(Collection<Specimen> specimens) { List<Specimen> result = new ArrayList<>(specimens); Collections.sort(result, new Comparator<Specimen>() { @Override public int compare(Specimen s1, Specimen s2) { Integer s1SortOrder = sortOrder(s1); Integer s2SortOrder = sortOrder(s2); Long s1ReqId = reqId(s1); Long s2ReqId = reqId(s2); if (s1SortOrder != null && s2SortOrder != null) { return s1SortOrder.compareTo(s2SortOrder); } else if (s1SortOrder != null) { return -1; } else if (s2SortOrder != null) { return 1; } else if (s1ReqId != null && s2ReqId != null) { if (!s1ReqId.equals(s2ReqId)) { return s1ReqId.compareTo(s2ReqId); } else { return compareById(s1, s2); } } else if (s1ReqId != null) { return -1; } else if (s2ReqId != null) { return 1; } else { return compareById(s1, s2); } } private int compareById(Specimen s1, Specimen s2) { if (s1.getId() != null && s2.getId() != null) { return s1.getId().compareTo(s2.getId()); } else if (s1.getId() != null) { return -1; } else if (s2.getId() != null) { return 1; } else { return 0; } } private Integer sortOrder(Specimen s) { if (s.getSpecimenRequirement() != null) { return s.getSpecimenRequirement().getSortOrder(); } return null; } private Long reqId(Specimen s) { if (s.getSpecimenRequirement() != null) { return s.getSpecimenRequirement().getId(); } return null; } }); return result; } public static List<Specimen> sortByLabels(Collection<Specimen> specimens, final List<String> labels) { List<Specimen> result = new ArrayList<Specimen>(specimens); Collections.sort(result, new Comparator<Specimen>() { @Override public int compare(Specimen s1, Specimen s2) { int s1Idx = labels.indexOf(s1.getLabel()); int s2Idx = labels.indexOf(s2.getLabel()); return s1Idx - s2Idx; } }); return result; } public static List<Specimen> sortByIds(Collection<Specimen> specimens, final List<Long> ids) { List<Specimen> result = new ArrayList<Specimen>(specimens); Collections.sort(result, new Comparator<Specimen>() { @Override public int compare(Specimen s1, Specimen s2) { int s1Idx = ids.indexOf(s1.getId()); int s2Idx = ids.indexOf(s2.getId()); return s1Idx - s2Idx; } }); return result; } public static List<Specimen> sortByBarcodes(Collection<Specimen> specimens, final List<String> barcodes) { List<Specimen> result = new ArrayList<>(specimens); result.sort(Comparator.comparingInt((s) -> barcodes.indexOf(s.getBarcode()))); return result; } public static boolean isValidLineage(String lineage) { if (StringUtils.isBlank(lineage)) { return false; } return lineage.equals(NEW) || lineage.equals(DERIVED) || lineage.equals(ALIQUOT); } private void addToChildrenEvent(Specimen childSpmn) { if (!childSpmn.isCollected() || childSpmn.getParentSpecimen() == null) { return; } if (!isEditAllowed()) { throw OpenSpecimenException.userError(SpecimenErrorCode.EDIT_NOT_ALLOWED, getLabel()); } SpecimenChildrenEvent currentEvent = childSpmn.isAliquot() ? aliquotEvent : derivativeEvent; if (currentEvent == null) { currentEvent = new SpecimenChildrenEvent(); currentEvent.setSpecimen(this); currentEvent.setLineage(childSpmn.getLineage()); currentEvent.setUser(AuthUtil.getCurrentUser()); currentEvent.setTime(childSpmn.getCreatedOn()); getChildrenEvents().add(currentEvent); } currentEvent.addChild(childSpmn); if (childSpmn.isAliquot()) { aliquotEvent = currentEvent; } else if (childSpmn.isDerivative()) { derivativeEvent = currentEvent; } } private void ensureNoActiveChildSpecimens() { for (Specimen specimen : getChildCollection()) { if (specimen.isActiveOrClosed() && specimen.isCollected()) { throw OpenSpecimenException.userError(SpecimenErrorCode.REF_ENTITY_FOUND); } } if (isPooled()) { for (Specimen specimen : getSpecimensPool()) { if (specimen.isActiveOrClosed() && specimen.isCollected()) { throw OpenSpecimenException.userError(SpecimenErrorCode.REF_ENTITY_FOUND); } } } } private int getActiveChildSpecimens() { int count = 0; for (Specimen specimen : getChildCollection()) { if (specimen.isActiveOrClosed() && specimen.isCollected()) { ++count; } } if (isPooled()) { for (Specimen specimen : getSpecimensPool()) { if (specimen.isActiveOrClosed() && specimen.isCollected()) { ++count; } } } return count; } private void addOrUpdateCollectionEvent() { if (isAliquot() || isDerivative()) { return; } getCollectionEvent().saveOrUpdate(); } private void addOrUpdateReceivedEvent() { if (isAliquot() || isDerivative()) { return; } getReceivedEvent().saveOrUpdate(); setCreatedOn(getReceivedEvent().getTime()); } private void deleteEvents() { if (!isAliquot() && !isDerivative()) { getCollectionEvent().delete(); getReceivedEvent().delete(); } for (SpecimenTransferEvent te : getTransferEvents()) { te.delete(); } } private void adjustParentSpecimenQty(BigDecimal qty) { BigDecimal parentQty = parentSpecimen.getAvailableQuantity(); if (parentQty == null || NumUtil.isZero(parentQty) || qty == null) { return; } parentQty = parentQty.subtract(qty); if (NumUtil.lessThanEqualsZero(parentQty)) { parentQty = BigDecimal.ZERO; } parentSpecimen.setAvailableQuantity(parentQty); } private void updateEvent(SpecimenEvent thisEvent, SpecimenEvent otherEvent) { if (isAliquot() || isDerivative()) { return; } thisEvent.update(otherEvent); } private void updateHierarchyStatus(String status) { setCollectionStatus(status); if (getId() != null && !isCollected(status)) { setAvailableQuantity(BigDecimal.ZERO); if (getPosition() != null) { getPosition().vacate(); } setPosition(null); if (getParentEvent() != null) { getParentEvent().removeChild(this); } deleteEvents(); } getChildCollection().forEach(child -> child.updateHierarchyStatus(status)); } public void checkPoolStatusConstraints() { if (!isPooled() && !isPoolSpecimen()) { return; } Specimen pooledSpmn = null; if (isPooled()) { if (isMissedOrNotCollected() || isPending()) { return; } pooledSpmn = this; } else if (isPoolSpecimen()) { if (isCollected()) { return; } pooledSpmn = getPooledSpecimen(); } boolean atLeastOneColl = false; for (Specimen poolSpmn : pooledSpmn.getSpecimensPool()) { if (poolSpmn.isCollected()) { atLeastOneColl = true; break; } } if (!atLeastOneColl && pooledSpmn.isCollected()) { throw OpenSpecimenException.userError(SpecimenErrorCode.NO_POOL_SPMN_COLLECTED, getLabel()); } } private void createMissedChildSpecimens() { createChildSpecimens(Specimen.MISSED_COLLECTION); } private void createNotCollectedSpecimens() { createChildSpecimens(Specimen.NOT_COLLECTED); } private void createChildSpecimens(String status) { if (getSpecimenRequirement() == null) { return; } Set<SpecimenRequirement> anticipated = new HashSet<>(getSpecimenRequirement().getChildSpecimenRequirements()); for (Specimen childSpmn : getChildCollection()) { if (childSpmn.getSpecimenRequirement() != null) { anticipated.remove(childSpmn.getSpecimenRequirement()); childSpmn.createChildSpecimens(status); } } for (SpecimenRequirement sr : anticipated) { Specimen specimen = sr.getSpecimen(); specimen.setVisit(getVisit()); specimen.setParentSpecimen(this); specimen.setCollectionStatus(status); getChildCollection().add(specimen); specimen.createChildSpecimens(status); } } private void autoCollectParentSpecimens(Specimen childSpmn) { Specimen parentSpmn = childSpmn.getParentSpecimen(); while (parentSpmn != null && parentSpmn.isPending()) { parentSpmn.setCollectionStatus(COLLECTED); if (parentSpmn.isPrimary()) { parentSpmn.addOrUpdateCollRecvEvents(); } else { parentSpmn.setCreatedOn(childSpmn.getCreatedOn()); } parentSpmn.addToChildrenEvent(childSpmn); childSpmn = parentSpmn; parentSpmn = parentSpmn.getParentSpecimen(); } if (parentSpmn != null) { // this means the parent specimen was pre-collected. // therefore need to add a processing event for its // recently collected child specimen parentSpmn.addToChildrenEvent(childSpmn); } } private void updateVisit(Visit visit, SpecimenRequirement sr) { setVisit(visit); setCollectionProtocol(visit.getCollectionProtocol()); setSpecimenRequirement(sr); getSpecimensPool().forEach(poolSpmn -> poolSpmn.updateVisit(visit, null)); getChildCollection().forEach(child -> child.updateVisit(visit, null)); } private void updateExternalIds(Collection<SpecimenExternalIdentifier> otherExternalIds) { for (SpecimenExternalIdentifier externalId : otherExternalIds) { SpecimenExternalIdentifier existing = getExternalIdByName(getExternalIds(), externalId.getName()); if (existing == null) { SpecimenExternalIdentifier newId = new SpecimenExternalIdentifier(); newId.setSpecimen(this); newId.setName(externalId.getName()); newId.setValue(externalId.getValue()); getExternalIds().add(newId); } else { existing.setValue(externalId.getValue()); } } getExternalIds().removeIf(externalId -> getExternalIdByName(otherExternalIds, externalId.getName()) == null); } private SpecimenExternalIdentifier getExternalIdByName(Collection<SpecimenExternalIdentifier> externalIds, String name) { return externalIds.stream().filter(externalId -> StringUtils.equals(externalId.getName(), name)).findFirst().orElse(null); } private List<Specimen> createPendingSpecimens(SpecimenRequirement sr, Specimen parent) { List<Specimen> result = new ArrayList<>(); for (SpecimenRequirement childSr : sr.getOrderedChildRequirements()) { Specimen specimen = childSr.getSpecimen(); specimen.setParentSpecimen(parent); specimen.setVisit(parent.getVisit()); specimen.setCollectionStatus(Specimen.PENDING); specimen.setLabelIfEmpty(); parent.addChildSpecimen(specimen); daoFactory.getSpecimenDao().saveOrUpdate(specimen); EventPublisher.getInstance().publish(new SpecimenSavedEvent(specimen)); result.add(specimen); result.addAll(createPendingSpecimens(childSr, specimen)); } return result; } }
package com.example.whatsmymood; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import com.google.android.gms.maps.model.LatLng; import org.apache.commons.lang3.ObjectUtils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Locale; /** * Takes user input and converts it into a relevant mood */ class AddMoodController{ private final CurrentUser current = CurrentUser.getInstance(); private final UserAccount user = current.getCurrentUser(); private boolean EDIT_MOOD = false; // Invalid User Selections private boolean SELECT_MOOD_INVALID = false; private boolean MOOD_MESSAGE_INVALID = false; private boolean DATE_INVALID = false; private static final int GET_LOCATION_REQUEST_CODE = 0; private static final int PERMISSIONS_REQUEST_ACCESS_CAMERA = 1; // Activity Result Codes private static final int CAPTURE_IMAGE_REQUEST_CODE = 4; private static final int RESULT_OK = -1; private int cameraPermissionCheck; private static ImageButton photoButton; private static Button addLocation; private final Dialog dialog; private final Context context; private String moodType; private final String moodAuthor = user.getUsername(); private String moodMsg = null; private static LatLng location = null; private String socialSit = null; private Date date; private String checkDate; private String checkDate2; // TODO: Make this non-static private static String mPhoto; // Dialog Layouts private final Spinner spinner; private final EditText editMoodMsg; private final EditText editSocialSit; private final EditText editDate; private Mood mood; /** * Passes the dialog and context * Sets up the click functionality for * the camera button and the post button * @param mContext Base context of the activity from main * @param mDialog Dialog created in footer handler */ public AddMoodController(final Context mContext, Dialog mDialog) { this.dialog = mDialog; this.context = mContext; this.spinner = (Spinner) this.dialog.findViewById(R.id.select_mood); this.editMoodMsg = (EditText) this.dialog.findViewById(R.id.enter_description); this.editSocialSit = (EditText) this.dialog.findViewById(R.id.enter_tags); this.editDate = (EditText) this.dialog.findViewById(R.id.enter_date); // Get Access to the Camera photoButton = (ImageButton) dialog.findViewById(R.id.load_picture); photoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // March 13th,2017 1:48 cameraPermissionCheck = ContextCompat.checkSelfPermission(context, android.Manifest.permission.CAMERA); if (cameraPermissionCheck != PackageManager.PERMISSION_GRANTED) { if (mContext instanceof MainActivity) { ActivityCompat.requestPermissions((MainActivity) context, new String[]{android.Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_ACCESS_CAMERA); } else { ActivityCompat.requestPermissions((ProfileActivity) context, new String[]{android.Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_ACCESS_CAMERA); } } else { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); if (mContext instanceof MainActivity) { ((MainActivity) context).startActivityForResult(intent, CAPTURE_IMAGE_REQUEST_CODE); } else { ((ProfileActivity) context).startActivityForResult(intent, CAPTURE_IMAGE_REQUEST_CODE); } } } }); // Sets the mood on post button click Button post = (Button) dialog.findViewById(R.id.post); post.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Mood mood = getMood(); // Checks the user is connected to wifi ConnectivityManager connManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getActiveNetworkInfo(); if (!EDIT_MOOD) { if (mood != null) { user.moodList.addMood(mood); Collections.sort(user.getMoodList().getMoodList(), new Comparator<Mood>() { public int compare(Mood mood1, Mood mood2) { return mood2.getDate().compareTo(mood1.getDate()); } }); ListView moodListView = (ListView) ((Activity) context).findViewById(R.id.moodListView); ((ArrayAdapter) moodListView.getAdapter()).notifyDataSetChanged(); try { mWifi.isConnected(); ElasticSearchUserController.UpdateUser updateUser = new ElasticSearchUserController.UpdateUser(); updateUser.execute(user); } catch (NullPointerException e) { e.printStackTrace(); CommandQueue.getInstance().addQueue(new UpdateCommand(user)); Log.d("COMMANDWOW", "WORKED"); } dialog.dismiss(); ThemeController.notifyThemeChange((Activity)mContext); } } else { if (mood != null) { EDIT_MOOD = false; Collections.sort(user.getMoodList().getMoodList(), new Comparator<Mood>() { public int compare(Mood mood1, Mood mood2) { return mood2.getDate().compareTo(mood1.getDate()); } }); ListView moodListView = (ListView) ((ProfileActivity) context).findViewById(R.id.moodListView); ((ArrayAdapter) moodListView.getAdapter()).notifyDataSetChanged(); try { mWifi.isConnected(); ElasticSearchUserController.UpdateUser updateUser = new ElasticSearchUserController.UpdateUser(); updateUser.execute(user); } catch (NullPointerException e) { e.printStackTrace(); CommandQueue.getInstance().addQueue(new UpdateCommand(user)); } dialog.dismiss(); ThemeController.notifyThemeChange((Activity)mContext); } } } }); addLocation = (Button) dialog.findViewById(R.id.enter_location); addLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context,AddLocationActivity.class); ((Activity) context).startActivityForResult(intent, GET_LOCATION_REQUEST_CODE); } }); } // I removed the static here but don't know if it will break anything. Check this with nathan after public static void processResult(int requestCode, int resultCode, Intent intent) { if (requestCode == CAPTURE_IMAGE_REQUEST_CODE) { if (resultCode == RESULT_OK) { Bitmap photo = (Bitmap) intent.getExtras().get("data"); // TODO: Figure out a way to not create memory leaks from this line // Basically photo's work but this line sets the image to the thumbnail of // the photo you just took. This is kind of optional, it's only so the user // knows that a photo was actually taken photoButton.setImageBitmap(photo); PhotoController photoController = new PhotoController(); mPhoto = photoController.encodePhoto(photo); } } if (requestCode == GET_LOCATION_REQUEST_CODE) { if (resultCode == RESULT_OK) { double lat = (Double) intent.getExtras().get("Lat"); double lng = (Double) intent.getExtras().get("Lng"); location = new LatLng(lat,lng); addLocation.setText("Location Added!"); Log.d("Add Location",location.toString()); } } } public void preFill(Mood mood) { EDIT_MOOD = true; // Gets the mood for updating //this.user = current.getCurrentUser(); int index = user.getMoodList().getIndex(mood); this.mood = current.getCurrentUser().getMoodList().get(index); // March 30th, 2017 String compareMood = this.mood.getMoodType(); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.context, R.array.mood_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); this.spinner.setAdapter(adapter); int position = adapter.getPosition(compareMood); this.spinner.setSelection(position); try { this.editMoodMsg.setText(this.mood.getMoodMsg()); } catch (NullPointerException e) { e.printStackTrace(); } try { this.editSocialSit.setText(this.mood.getSocialSit()); } catch (NullPointerException e) { e.printStackTrace(); } try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); checkDate = dateFormat.format(this.mood.getDate()); this.editDate.setText(checkDate); } catch (NullPointerException e) { e.printStackTrace(); } try { PhotoController photoController = new PhotoController(); Bitmap photo = photoController.decodePhoto(this.mood.getPhoto()); photoButton.setImageBitmap(photo); } catch (NullPointerException e) { e.printStackTrace(); } } /** * Main controller actions * Takes each input and converts it into * their respective variables * @return Calls make mood to make a mood object */ private Mood getMood() { if (!spinner.getSelectedItem().toString().equals("Select a mood")) { this.moodType = spinner.getSelectedItem().toString(); } else { SELECT_MOOD_INVALID = true; } if (!editMoodMsg.getText().toString().isEmpty()) { String message = editMoodMsg.getText().toString(); if (message.split("\\s+").length > 3 || message.length() > 15) { MOOD_MESSAGE_INVALID = true; } else { this.moodMsg = editMoodMsg.getText().toString(); } } if (!editSocialSit.getText().toString().isEmpty()) { this.socialSit = editSocialSit.getText().toString(); } // Checks if the date is empty and if the format is correct if (!editDate.getText().toString().isEmpty()) { SimpleDateFormat check = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); check.setLenient(false); try { this.checkDate2 = editDate.getText().toString(); this.date = check.parse(checkDate2); } catch(ParseException e) { e.printStackTrace(); DATE_INVALID = true; } } if (SELECT_MOOD_INVALID) { TextView textview = (TextView) spinner.getSelectedView(); textview.setError(""); textview.setTextColor(Color.RED); textview.setText(R.string.invalid_mood); SELECT_MOOD_INVALID = false; } else if (MOOD_MESSAGE_INVALID) { editMoodMsg.setError("Mood Messages must be less than 15 characters and less than 4 words"); MOOD_MESSAGE_INVALID = false; } else if (DATE_INVALID) { editDate.setError("Invalid Date Inputted (yyyy-MM-DD)"); DATE_INVALID = false; } else { if (!EDIT_MOOD) { return makeMood(); } else { return updateMood(); } } return null; } /** * Creates the mood * Automatically creates a date to the current date * if there is no date specified * @return Returns a mood object */ private Mood makeMood() { if (this.date == null) { mood = new Mood(this.moodAuthor, this.moodType); } else { mood = new Mood(this.moodAuthor, this.moodType, this.date); } mood.setMoodMsg(this.moodMsg); mood.setLocation(this.location); mood.setSocialSit(this.socialSit); mood.setPhoto(mPhoto); mPhoto = null; return mood; } private Mood updateMood() { mood.setMoodType(this.moodType); mood.setMoodMsg(this.moodMsg); mood.setLocation(this.location); mood.setSocialSit(this.socialSit); if (this.date == null) { mood.setDate(new Date()); } else { if (this.checkDate.equals(this.checkDate2)) { mood.setDate(this.mood.getDate()); } else { mood.setDate(this.date); } } mood.setPhoto(mPhoto); mPhoto = null; return mood; } }
package com.example.whatsmymood; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import java.io.ByteArrayOutputStream; import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Color; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Base64; import android.util.Log; import android.location.LocationManager; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import com.google.android.gms.games.video.Videos; import static android.content.Context.LOCATION_SERVICE; /** * Takes user input and converts it into a relevant mood */ public class AddMoodController extends AppCompatActivity{ // Invalid User Selections private boolean DATE_INVALID = false; private boolean SELECT_MOOD_INVALID = false; private static final int PERMISSIONS_REQUEST_ACCESS_CAMERA = 1; // Activity Result Codes private final static int CAPTURE_IMAGE_REQUEST_CODE = 2; private final static int CONFIRM = 3; private int cameraPermissionCheck; private Dialog dialog; private Context mContext; private Mood mood; private String moodType; private String moodAuthor; // Set to null because they are not mandatory private String moodMsg = null; private String location = null; private String socialSit = null; private Date date; // TODO: Figure out how we're handling photos private String photo; /** * Passes the dialog and context * Sets up the click functionality for * the camera button and the post button * @param mContext * @param d * @param view */ public AddMoodController(final Context mContext, Dialog d, View view) { this.dialog = d; this.mContext = mContext; /** * Get access to the camera in android on user click */ Button photoButton = (Button) dialog.findViewById(R.id.load_picture); photoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { cameraPermissionCheck = ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.CAMERA); if (cameraPermissionCheck != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions((Activity) mContext, new String[]{android.Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_ACCESS_CAMERA); } else { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); ((Activity) mContext).startActivityForResult(intent, CAPTURE_IMAGE_REQUEST_CODE); } } }); /** * Sets the mood on post button click */ Button post = (Button) dialog.findViewById(R.id.post); post.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CurrentUser current = CurrentUser.getInstance(); moodAuthor = CurrentUser.getInstance().getCurrentUser().getUsername(); UserAccount user = current.getCurrentUser(); Mood m = getMood(); if(m != null) { user.moodList.addMood(getMood()); ElasticSearchUserController.UpdateUser updateUser = new ElasticSearchUserController.UpdateUser(); updateUser.execute(user); dialog.dismiss(); } } }); } /** * Grabs the result from the camera activity * // TODO: Get the bitmap image successfully * @param requestCode * @param resultCode * @param intent */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == CAPTURE_IMAGE_REQUEST_CODE) { if (resultCode == CONFIRM) { Bitmap photo = (Bitmap) intent.getExtras().get("data"); // Used for decoding the image for later storage ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); byte[] imageBytes = outputStream.toByteArray(); String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT); this.photo = encodedImage; } } } /** * Main controller actions * Takes each inputi and converts it into * their respective variables * @return */ public Mood getMood() { Spinner spinner = (Spinner) this.dialog.findViewById(R.id.select_mood); if (!spinner.getSelectedItem().toString().equals("Select a mood")) { this.moodType = spinner.getSelectedItem().toString(); } else { // Set to TRUE if they have no selected an entry SELECT_MOOD_INVALID = true; } EditText msg = (EditText) this.dialog.findViewById(R.id.enter_description); if (!msg.getText().toString().isEmpty()) { this.moodMsg = msg.getText().toString(); } // TODO: Make this an actual location // TODO: Handle exception where user does not input a location/invalid locations EditText location = (EditText) this.dialog.findViewById(R.id.enter_location); if (!location.getText().toString().isEmpty()) { this.location = location.getText().toString(); } EditText socialSit = (EditText) this.dialog.findViewById(R.id.enter_tags); if (!socialSit.getText().toString().isEmpty()) { this.socialSit = socialSit.getText().toString(); } EditText date = (EditText) this.dialog.findViewById(R.id.enter_date); // Checks if the date is empty // and parses the date to make sure // the date format is correct if (!date.getText().toString().isEmpty()) { SimpleDateFormat check = new SimpleDateFormat("yyyy-MM-dd"); check.setLenient(false); try { Date moodDate = check.parse(date.getText().toString()); this.date = moodDate; } catch(ParseException e) { e.printStackTrace(); DATE_INVALID = true; } } if (SELECT_MOOD_INVALID) { // TODO: Find a better way to output the error Spinner mSpinner = (Spinner) this.dialog.findViewById(R.id.select_mood); TextView textview = (TextView) mSpinner.getSelectedView(); textview.setError(""); textview.setTextColor(Color.RED);//just to highlight that this is an error textview.setText("Invalid Mood Selected"); // TODO: Handle invalid mood properly // SELECT_MOOD_INVALID is always set to true unless we manually set it to false SELECT_MOOD_INVALID = false; } else if (DATE_INVALID) { TextView textview = (TextView) this.dialog.findViewById(R.id.enter_date); textview.setError("Invalid Date Inputed (yyyy-MM-DD)"); // TODO: Handle invalid date properly // DATE_INVALID is always set to true unless we manually set it to false DATE_INVALID = false; // Makes the mood if there are no errors } else { return makeMood(); } return null; } /** * Creates the mood * Automatically creates a date to the current date * if there is no date specifeid * @return */ public Mood makeMood() { // If the date is null, automatically set the date to the current date if (this.date == null) { Date newDate = new Date(); this.mood = new Mood(this.moodAuthor,this.moodType, newDate); } else { this.mood = new Mood(this.moodAuthor,this.moodType, this.date); } mood.setMoodMsg(this.moodMsg); mood.setLocation(this.location); mood.setSocialSit(this.socialSit); mood.setPhoto(this.photo); return mood; } }
package alien4cloud.component; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.LinkedList; import java.util.List; import javax.annotation.Resource; import org.alien4cloud.tosca.model.Csar; import org.elasticsearch.index.query.QueryBuilders; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import alien4cloud.csar.services.CsarGitRepositoryService; import alien4cloud.csar.services.CsarGitService; import alien4cloud.dao.IGenericSearchDAO; import alien4cloud.model.git.CsarGitCheckoutLocation; import alien4cloud.model.git.CsarGitRepository; import alien4cloud.tosca.ArchiveParserTest; import alien4cloud.tosca.parser.ParsingErrorLevel; import alien4cloud.tosca.parser.ParsingResult; import alien4cloud.utils.FileUtil; import lombok.extern.slf4j.Slf4j; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context-test.xml") @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) @Slf4j public class CsarGitServiceTest { @Resource(name = "alien-es-dao") private IGenericSearchDAO alienDAO; @Resource CsarGitService csarGitService; @Resource CsarGitRepositoryService csarGitRepositoryService; @Value("${directories.alien}/${directories.upload_temp}") private String alienRepoDir; @Before public void cleanup() { alienDAO.delete(CsarGitRepository.class, QueryBuilders.matchAllQuery()); alienDAO.delete(Csar.class, QueryBuilders.matchAllQuery()); if (Files.isDirectory(Paths.get(alienRepoDir))) { log.debug("cleaning the test env"); try { FileUtil.delete(Paths.get(alienRepoDir)); } catch (IOException e) { e.printStackTrace(); } } } @Test public void importOneBranchFromGit() { CsarGitCheckoutLocation alien12Location = new CsarGitCheckoutLocation(); alien12Location.setBranchId("1.2.0"); List<CsarGitCheckoutLocation> importLocations = new LinkedList<>(); importLocations.add(alien12Location); String repoId = csarGitRepositoryService.create("https://github.com/alien4cloud/tosca-normative-types.git", "", "", importLocations, false); List<ParsingResult<Csar>> result = csarGitService.importFromGitRepository(repoId); Assert.assertEquals(1, result.size()); Assert.assertEquals("tosca-normative-types", result.get(0).getResult().getName()); } @Test public void importManyBranchFromGit() { CsarGitCheckoutLocation alien12Location = new CsarGitCheckoutLocation(); alien12Location.setBranchId("1.2.0"); CsarGitCheckoutLocation masterLocation = new CsarGitCheckoutLocation(); masterLocation.setBranchId("master"); List<CsarGitCheckoutLocation> importLocations = new LinkedList<>(); importLocations.add(alien12Location); importLocations.add(masterLocation); String repoId = csarGitRepositoryService.create("https://github.com/alien4cloud/tosca-normative-types.git", "", "", importLocations, false); List<ParsingResult<Csar>> result = csarGitService.importFromGitRepository(repoId); Assert.assertEquals(2, result.size()); Assert.assertEquals("tosca-normative-types", result.get(0).getResult().getName()); Assert.assertEquals("1.0.0-ALIEN12", result.get(0).getResult().getVersion()); Assert.assertEquals("tosca-normative-types", result.get(1).getResult().getName()); Assert.assertEquals("1.0.0-SNAPSHOT", result.get(1).getResult().getVersion()); } @Test public void importManyBranchFromGitAndStoreLocally() { CsarGitCheckoutLocation alien12Location = new CsarGitCheckoutLocation(); alien12Location.setBranchId("1.2.0"); CsarGitCheckoutLocation masterLocation = new CsarGitCheckoutLocation(); masterLocation.setBranchId("master"); List<CsarGitCheckoutLocation> importLocations = new LinkedList<>(); importLocations.add(alien12Location); importLocations.add(masterLocation); String repoId = csarGitRepositoryService.create("https://github.com/alien4cloud/tosca-normative-types.git", "", "", importLocations, true); List<ParsingResult<Csar>> result = csarGitService.importFromGitRepository(repoId); Assert.assertEquals(2, result.size()); Assert.assertEquals("tosca-normative-types", result.get(0).getResult().getName()); Assert.assertEquals("1.0.0-ALIEN12", result.get(0).getResult().getVersion()); Assert.assertEquals("tosca-normative-types", result.get(1).getResult().getName()); Assert.assertEquals("1.0.0-SNAPSHOT", result.get(1).getResult().getVersion()); // now we re-import result = csarGitService.importFromGitRepository(repoId); Assert.assertEquals(0, result.size()); } @Test public void importArchiveInProperOrder() { CsarGitCheckoutLocation normativeTypesMasterLocation = new CsarGitCheckoutLocation(); normativeTypesMasterLocation.setBranchId("1.2.0"); List<CsarGitCheckoutLocation> importLocations = new LinkedList<>(); importLocations.add(normativeTypesMasterLocation); String repoId = csarGitRepositoryService.create("https://github.com/alien4cloud/tosca-normative-types.git", "", "", importLocations, false); List<ParsingResult<Csar>> result = csarGitService.importFromGitRepository(repoId); Assert.assertFalse(result.get(0).hasError(ParsingErrorLevel.ERROR)); CsarGitCheckoutLocation testArchiveLocation = new CsarGitCheckoutLocation(); testArchiveLocation.setBranchId("test-order-import"); importLocations.clear(); importLocations.add(testArchiveLocation); repoId = csarGitRepositoryService.create("https://github.com/alien4cloud/samples.git", "", "", importLocations, false); List<ParsingResult<Csar>> sampleResult = csarGitService.importFromGitRepository(repoId); Assert.assertEquals(3, sampleResult.size()); for (ParsingResult<Csar> csarParsingResult : sampleResult) { boolean hasError = csarParsingResult.hasError(ParsingErrorLevel.ERROR); if (hasError) { ArchiveParserTest.displayErrors(csarParsingResult); } Assert.assertFalse(hasError); } Assert.assertEquals("test-archive-1", sampleResult.get(0).getResult().getName()); Assert.assertEquals("test-archive-3", sampleResult.get(1).getResult().getName()); Assert.assertEquals("test-archive-2", sampleResult.get(2).getResult().getName()); } }
package annis.administration; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import javax.ws.rs.BadRequestException; import javax.ws.rs.ForbiddenException; import javax.ws.rs.ServerErrorException; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.corpus_tools.graphannis.errors.GraphANNISException; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatterBuilder; import org.joda.time.format.DateTimeParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Joiner; import annis.CommonHelper; import annis.QueryGenerator; import annis.dao.QueryDao; import annis.exceptions.AnnisTimeoutException; import annis.model.DisplayedResultQuery; import annis.model.Query; import annis.service.objects.MatchAndDocumentCount; import annis.service.objects.QueryLanguage; import annis.sqlgen.extensions.LimitOffsetQueryData; public class URLShortenerDefinition { private final static Logger log = LoggerFactory.getLogger(URLShortenerDefinition.class); private URI uri; private DisplayedResultQuery query; private UUID uuid; private DateTime creationTime; private String errorMsg; protected URLShortenerDefinition(URI uri, UUID uuid, DateTime creationTime) { this(uri, uuid, creationTime, new DisplayedResultQuery()); } protected URLShortenerDefinition(URI uri, UUID uuid, DateTime creationTime, DisplayedResultQuery query) { this.uri = uri; this.uuid = uuid; this.query = query; this.creationTime = creationTime; this.errorMsg = null; } public static UUID parseUUID(String uuid) { return UUID.fromString(uuid); } public static DateTime parseCreationTime(String creationTime) { DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSZZ").getParser(), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ssZZ").getParser(), }; DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); return dateFormatter.parseDateTime(creationTime); } public static URLShortenerDefinition parse(String url, String uuid, String creationTime) throws URISyntaxException, UnsupportedEncodingException { URI parsedURI = new URI(url); URLShortenerDefinition result = new URLShortenerDefinition(parsedURI, parseUUID(uuid), parseCreationTime(creationTime)); if (parsedURI.getPath().startsWith("/embeddedvis")) { for (NameValuePair arg : URLEncodedUtils.parse(parsedURI, "UTF-8")) { if ("embedded_interface".equals(arg.getName())) { URI interfaceURI = new URI(arg.getValue()); result.query = parseFragment(interfaceURI.getFragment()); break; } } } else { result.query = parseFragment(parsedURI.getFragment()); } return result; } private static DisplayedResultQuery parseFragment(String fragment) { Map<String, String> args = CommonHelper.parseFragment(fragment); String corporaRaw = args.get("c"); if (corporaRaw != null) { Set<String> corpora = new LinkedHashSet<>(Arrays.asList(corporaRaw.split("\\s*,\\s*"))); return QueryGenerator.displayed().left(Integer.parseInt(args.get("cl"))) .right(Integer.parseInt(args.get("cr"))).offset(Integer.parseInt(args.get("s"))) .limit(Integer.parseInt(args.get("l"))).segmentation(args.get("seg")).baseText(args.get("bt")) .query(args.get("q")).corpora(corpora).build(); } return null; } public URLShortenerDefinition rewriteInQuirksMode() { DisplayedResultQuery rewrittenQuery = new DisplayedResultQuery(this.query); rewrittenQuery.setQueryLanguage(QueryLanguage.AQL_QUIRKS_V3); UriBuilder rewrittenUri = UriBuilder.fromUri(this.uri); if (this.uri.getPath().startsWith("/embeddedvis")) { // we need to keep query parameters arguments, except for the one with the // linked query rewrittenUri.replaceQueryParam("embedded_interface", rewrittenQuery.toCitationFragment()); } else { // just update the fragment, but leave everything else the same rewrittenUri.fragment(rewrittenQuery.toCitationFragment()); } return new URLShortenerDefinition(rewrittenUri.build(), this.uuid, this.creationTime, rewrittenQuery); } public Query getQuery() { return query; } public String getErrorMsg() { return errorMsg; } public UUID getUuid() { return uuid; } public URI getUri() { return uri; } public DateTime getCreationTime() { return creationTime; } public static int MAX_RETRY = 5; private QueryStatus testFind(QueryDao queryDao, WebTarget annisSearchService) throws GraphANNISException, IOException { WebTarget findTarget = annisSearchService.path("find").queryParam("q", query.getQuery()).queryParam("corpora", Joiner.on(",").join(query.getCorpora())); File matchesGraphANNISFile = File.createTempFile("annis-migrate-url-shortener-graphannis", ".txt"); matchesGraphANNISFile.deleteOnExit(); // write all graphANNIS matches to temporary file try (BufferedOutputStream fileOutput = new BufferedOutputStream(new FileOutputStream(matchesGraphANNISFile))) { queryDao.find(query.getQuery(), query.getQueryLanguage(), new LinkedList<>(query.getCorpora()), new LimitOffsetQueryData(0, Integer.MAX_VALUE), fileOutput); } // read in the file again line by line and compare it with the legacy ANNIS // version try (BufferedReader matchesGraphANNIS = new BufferedReader(new FileReader(matchesGraphANNISFile)); BufferedReader matchesLegacy = new BufferedReader( new InputStreamReader(findTarget.request(MediaType.TEXT_PLAIN_TYPE).get(InputStream.class)))) { // compare each line String m1; String m2; while ((m1 = matchesGraphANNIS.readLine()) != null && (m2 = matchesLegacy.readLine()) != null) { if (!m1.equals(m2)) { this.errorMsg = "(should be)" + System.lineSeparator() + m2 + System.lineSeparator() + "(but was)" + System.lineSeparator() + m1; return QueryStatus.MatchesDiffer; } } } return QueryStatus.Ok; } public QueryStatus test(QueryDao queryDao, WebTarget annisSearchService) throws GraphANNISException { if (this.query.getCorpora().isEmpty()) { this.errorMsg = "Empty corpus list"; return QueryStatus.Failed; } // check count first (also warmup for the corpus) int countGraphANNIS; try { countGraphANNIS = queryDao.count(query.getQuery(), query.getQueryLanguage(), new LinkedList<>(query.getCorpora())); } catch (GraphANNISException ex) { countGraphANNIS = 0; } try { QueryStatus status = QueryStatus.Ok; Optional<Integer> countLegacy = Optional.empty(); try { for (int tries = 0; tries < MAX_RETRY; tries++) { try { countLegacy = Optional.of(annisSearchService.path("count").queryParam("q", query.getQuery()) .queryParam("corpora", Joiner.on(",").join(query.getCorpora())).request() .get(MatchAndDocumentCount.class).getMatchCount()); break; } catch (ServerErrorException ex) { if (tries >= MAX_RETRY - 1) { this.errorMsg = ex.getMessage(); return QueryStatus.Failed; } else { log.warn("Server error when executing query {}", query.getQuery(), ex); } } } } catch (BadRequestException ex) { countLegacy = Optional.of(0); } if (countGraphANNIS != countLegacy.get()) { this.errorMsg = "should have been " + countLegacy.get() + " but was " + countGraphANNIS; status = QueryStatus.CountDiffers; } else { status = testFind(queryDao, annisSearchService); if (status == QueryStatus.Failed) { // don't try quirks mode when failed return status; } } if (status != QueryStatus.Ok && this.query.getQueryLanguage() == QueryLanguage.AQL) { // check in quirks mode and rewrite if necessary log.info("Trying quirks mode for query {} on corpus {}", this.query.getQuery().trim(), this.query.getCorpora()); URLShortenerDefinition quirksQuery = this.rewriteInQuirksMode(); QueryStatus quirksStatus = quirksQuery.test(queryDao, annisSearchService); if (quirksStatus == QueryStatus.Ok) { this.query = quirksQuery.query; this.uri = quirksQuery.uri; this.errorMsg = "Rewrite in quirks mode necessary"; status = QueryStatus.Ok; } else { this.errorMsg = quirksQuery.getErrorMsg(); } } return status; } catch (ForbiddenException | AnnisTimeoutException | IOException ex) { this.errorMsg = ex.toString(); return QueryStatus.Failed; } } }
package org.ieatta.test.adapter; import android.support.test.runner.AndroidJUnit4; import android.test.ActivityUnitTestCase; import com.tableview.RecycleViewManager; import com.tableview.TableViewControllerAdapter; import com.tableview.storage.DTTableViewManager; import com.tableview.storage.TableViewConfiguration; import org.ieatta.test.adapter.cell.FooterView; import org.ieatta.test.adapter.cell.HeaderView; import org.ieatta.test.adapter.cell.HeaderFooterViewModel; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.hamcrest.MatcherAssert.assertThat; public class RecycleViewManagerTest extends ActivityUnitTestCase { private RecycleViewManager manager; private DTTableViewManager mProvider; private final HeaderFooterViewModel headerViewModel = new HeaderFooterViewModel("testHeaderView"); private final HeaderFooterViewModel footerViewModel = new HeaderFooterViewModel("testFooterView"); public RecycleViewManagerTest(Class activityClass) { super(activityClass); } @Before public void setUp() throws Exception { manager = new RecycleViewManager(); mProvider = manager.getTableManager(); TableViewConfiguration configuration = new TableViewConfiguration(new TableViewConfiguration.Builder(this.getActivity().getApplicationContext())); TableViewControllerAdapter adapter = new TableViewControllerAdapter(this.mProvider); mProvider.setConfiguration(configuration, adapter); } @Test public void testHeaderView() { // when this.manager.setRegisterHeaderView(HeaderView.getType()); this.manager.setHeaderItem(headerViewModel, HeaderView.getType()); // how this.manager.updateTableSections(); // then Object expectModel = this.mProvider.memoryStorage.getRowModel(0); assertThat("The same cell type.", headerViewModel.equals(expectModel)); } @Test public void testFooterView() { // when this.manager.setRegisterFooterClass(FooterView.getType()); this.manager.setFooterItem(footerViewModel, FooterView.getType()); // how this.manager.updateTableSections(); // then Object expectModel = this.mProvider.memoryStorage.getRowModel(0); assertThat("The same cell type.", footerViewModel.equals(expectModel)); } @Test public void testHeaderFooterView() { // when this.manager.setRegisterHeaderClass(HeaderView.getType()); this.manager.setRegisterFooterClass(FooterView.getType()); this.manager.setHeaderItem(headerViewModel, HeaderView.getType()); this.manager.setFooterItem(footerViewModel, FooterView.getType()); // how this.manager.updateTableSections(); // then Object expectHeaderModel = this.mProvider.memoryStorage.getRowModel(0); Object expectFooterModel = this.mProvider.memoryStorage.getRowModel(1); assertThat("The same cell type.", headerViewModel.equals(expectHeaderModel)); assertThat("The same cell type.", footerViewModel.equals(expectFooterModel)); } }
package com.github.mobile.android.issue; import static android.view.View.GONE; import static android.view.View.VISIBLE; import android.content.res.Resources; import android.text.Html; import android.view.View; import android.webkit.WebView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import com.github.mobile.android.R.id; import com.github.mobile.android.R.string; import com.github.mobile.android.util.AvatarHelper; import com.github.mobile.android.util.HtmlViewer; import com.github.mobile.android.util.ServiceHelper; import com.github.mobile.android.util.Time; import com.madgag.android.listviews.ViewHolder; import java.util.Locale; import org.eclipse.egit.github.core.Issue; import org.eclipse.egit.github.core.User; /** * Holder for a issue minus the comments */ public class IssueHeaderViewHolder implements ViewHolder<Issue> { private final AvatarHelper avatarHelper; private final Resources resources; private final TextView titleText; private final HtmlViewer bodyViewer; private final TextView createdText; private final ImageView creatorAvatar; private final TextView assigneeText; private final ImageView assigneeAvatar; private final LinearLayout labelsArea; private final TextView milestoneText; private final TextView stateText; /** * @return bodyViewer */ public HtmlViewer getBodyViewer() { return bodyViewer; } /** * Create issue header view holder * * @param view * @param avatarHelper * @param resources */ public IssueHeaderViewHolder(final View view, final AvatarHelper avatarHelper, final Resources resources) { this.avatarHelper = avatarHelper; this.resources = resources; titleText = (TextView) view.findViewById(id.tv_issue_title); createdText = (TextView) view.findViewById(id.tv_issue_creation); creatorAvatar = (ImageView) view.findViewById(id.iv_gravatar); assigneeText = (TextView) view.findViewById(id.tv_assignee_name); assigneeAvatar = (ImageView) view.findViewById(id.iv_assignee_gravatar); labelsArea = (LinearLayout) view.findViewById(id.ll_labels); milestoneText = (TextView) view.findViewById(id.tv_milestone); stateText = (TextView) view.findViewById(id.tv_state); bodyViewer = new HtmlViewer((WebView) view.findViewById(id.wv_issue_body)); } public void updateViewFor(Issue issue) { titleText.setText(issue.getTitle()); String body = issue.getBodyHtml(); if (body != null && body.length() > 0) bodyViewer.setHtml(body).getView().setVisibility(VISIBLE); else bodyViewer.getView().setVisibility(GONE); String reported = "<b>" + issue.getUser().getLogin() + "</b> opened " + Time.relativeTimeFor(issue.getCreatedAt()); createdText.setText(Html.fromHtml(reported)); avatarHelper.bind(creatorAvatar, issue.getUser()); User assignee = issue.getAssignee(); if (assignee != null) { assigneeText.setText(assignee.getLogin()); assigneeAvatar.setVisibility(VISIBLE); avatarHelper.bind(assigneeAvatar, assignee); } else { assigneeAvatar.setVisibility(GONE); assigneeText.setText(assigneeText.getContext().getString(string.unassigned)); } if (!issue.getLabels().isEmpty()) { labelsArea.setVisibility(VISIBLE); LabelsDrawable drawable = new LabelsDrawable(createdText.getTextSize(), ServiceHelper.getDisplayWidth(labelsArea), issue.getLabels()); drawable.getPaint().setColor(resources.getColor(android.R.color.transparent)); labelsArea.setBackgroundDrawable(drawable); LayoutParams params = new LayoutParams(drawable.getBounds().width(), drawable.getBounds().height()); labelsArea.setLayoutParams(params); } else labelsArea.setVisibility(GONE); if (issue.getMilestone() != null) milestoneText.setText(issue.getMilestone().getTitle()); else milestoneText.setText(milestoneText.getContext().getString(string.no_milestone)); String state = issue.getState(); if (state != null && state.length() > 0) state = state.substring(0, 1).toUpperCase(Locale.US) + state.substring(1); else state = ""; stateText.setText(state); } }
package com.marverenic.music.activity.instance; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.crashlytics.android.Crashlytics; import com.marverenic.music.JockeyApplication; import com.marverenic.music.R; import com.marverenic.music.activity.BaseActivity; import com.marverenic.music.instances.Album; import com.marverenic.music.instances.Artist; import com.marverenic.music.instances.Library; import com.marverenic.music.instances.Song; import com.marverenic.music.instances.section.AlbumSection; import com.marverenic.music.instances.section.ArtistBioSingleton; import com.marverenic.music.instances.section.HeaderSection; import com.marverenic.music.instances.section.LibraryEmptyState; import com.marverenic.music.instances.section.LoadingSingleton; import com.marverenic.music.instances.section.RelatedArtistSection; import com.marverenic.music.instances.section.SongSection; import com.marverenic.music.lastfm2.data.store.LastFmStore; import com.marverenic.music.lastfm2.model.LfmArtist; import com.marverenic.music.utils.Themes; import com.marverenic.music.view.BackgroundDecoration; import com.marverenic.music.view.DividerDecoration; import com.marverenic.music.view.EnhancedAdapters.HeterogeneousAdapter; import com.marverenic.music.view.GridSpacingDecoration; import com.marverenic.music.view.ViewUtils; import com.trello.rxlifecycle.RxLifecycle; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.inject.Inject; import rx.android.schedulers.AndroidSchedulers; public class ArtistActivity extends BaseActivity { public static final String ARTIST_EXTRA = "artist"; @Inject LastFmStore mLfmStore; private RecyclerView mRecyclerView; private HeterogeneousAdapter mAdapter; private LoadingSingleton mLoadingSection; private ArtistBioSingleton mBioSection; private RelatedArtistSection mRelatedArtistSection; private AlbumSection mAlbumSection; private SongSection mSongSection; private Artist mReference; private LfmArtist mLfmReference; private List<LfmArtist> mRelatedArtists; private List<Song> mSongs; private List<Album> mAlbums; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_instance_artwork); JockeyApplication.getComponent(this).inject(this); mReference = getIntent().getParcelableExtra(ARTIST_EXTRA); CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar); collapsingToolbar.setTitle(mReference.getArtistName()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); getWindow().setStatusBarColor(Color.TRANSPARENT); } mAlbums = Library.getArtistAlbumEntries(mReference); mSongs = Library.getArtistSongEntries(mReference); mLfmStore.getArtistInfo(mReference.getArtistName()) .compose(RxLifecycle.bindActivity(lifecycle())) .observeOn(AndroidSchedulers.mainThread()) .subscribe( this::setLastFmReference, Crashlytics::logException); // Sort the album list chronologically if all albums have years, // otherwise sort alphabetically if (allEntriesHaveYears()) { Collections.sort(mAlbums, (a1, a2) -> a1.getYear() - a2.getYear()); } else { Collections.sort(mAlbums); } mRecyclerView = (RecyclerView) findViewById(R.id.list); setupAdapter(); } private boolean allEntriesHaveYears() { for (int i = 0; i < mAlbums.size(); i++) { if (mAlbums.get(i).getYear() == 0) { return false; } } return true; } private void setLastFmReference(LfmArtist lfmArtist) { mLfmReference = lfmArtist; mRelatedArtists = new ArrayList<>(); for (LfmArtist relatedArtist : lfmArtist.getSimilarArtists()) { if (Library.findArtistByName(relatedArtist.getName()) != null) { mRelatedArtists.add(relatedArtist); } } setupAdapter(); } private void setupAdapter() { if (mRecyclerView == null) { return; } if (mAdapter == null) { setupRecyclerView(); mAdapter = new HeterogeneousAdapter(); mAdapter.setEmptyState(new LibraryEmptyState(this) { @Override public String getEmptyMessage() { if (mReference == null) { return getString(R.string.empty_error_artist); } else { return super.getEmptyMessage(); } } @Override public String getEmptyMessageDetail() { if (mReference == null) { return ""; } else { return super.getEmptyMessageDetail(); } } @Override public String getEmptyAction1Label() { return ""; } }); mRecyclerView.setAdapter(mAdapter); } setupNetworkAdapter(); setupAlbumAdapter(); setupSongAdapter(); mAdapter.notifyDataSetChanged(); } private void setupRecyclerView() { int numColumns = ViewUtils.getNumberOfGridColumns(this); // Setup the GridLayoutManager GridLayoutManager layoutManager = new GridLayoutManager(this, numColumns); GridLayoutManager.SpanSizeLookup spanSizeLookup = new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { // Albums & related artists fill one column, // all other view types fill the available width if (mAdapter.getItemViewType(position) == AlbumSection.ID || mAdapter.getItemViewType(position) == RelatedArtistSection.ID) { return 1; } else { return numColumns; } } }; spanSizeLookup.setSpanIndexCacheEnabled(true); // For performance layoutManager.setSpanSizeLookup(spanSizeLookup); mRecyclerView.setLayoutManager(layoutManager); setupListDecorations(numColumns); } private void setupListDecorations(int numColumns) { mRecyclerView.addItemDecoration( new GridSpacingDecoration( (int) getResources().getDimension(R.dimen.grid_margin), numColumns, AlbumSection.ID)); mRecyclerView.addItemDecoration( new GridSpacingDecoration( (int) getResources().getDimension(R.dimen.card_margin), numColumns, RelatedArtistSection.ID)); mRecyclerView.addItemDecoration( new BackgroundDecoration(Themes.getBackgroundElevated(), R.id.loadingView, R.id.infoCard, R.id.relatedCard)); mRecyclerView.addItemDecoration( new DividerDecoration(this, R.id.infoCard, R.id.albumInstance, R.id.subheaderFrame, R.id.relatedCard, R.id.empty_layout)); } private void setupNetworkAdapter() { if (mLfmReference == null) { setupLoadingAdapter(); } else { setupLastFmAdapter(); } } private void setupLoadingAdapter() { if (mLoadingSection == null) { mLoadingSection = new LoadingSingleton(); mAdapter.addSection(mLoadingSection, 0); } } private void setupLastFmAdapter() { if (mLoadingSection != null) { mAdapter.removeSectionById(LoadingSingleton.ID); mLoadingSection = null; } if (mBioSection == null) { mBioSection = new ArtistBioSingleton(mLfmReference, !mRelatedArtists.isEmpty()); mAdapter.addSection(mBioSection, 0); } if (mRelatedArtistSection == null) { mRelatedArtistSection = new RelatedArtistSection(mRelatedArtists); mAdapter.addSection(mRelatedArtistSection, 1); } } private void setupSongAdapter() { if (mSongs == null) { mSongs = Collections.emptyList(); } if (mSongSection == null) { mSongSection = new SongSection(mSongs); mAdapter .addSection(new HeaderSection(getString(R.string.header_songs), SongSection.ID)) .addSection(mSongSection); } else { mSongSection.setData(mSongs); } } private void setupAlbumAdapter() { if (mAlbums == null) { mAlbums = Collections.emptyList(); } if (mAlbumSection == null) { mAlbumSection = new AlbumSection(mAlbums); mAdapter .addSection( new HeaderSection(getString(R.string.header_albums), AlbumSection.ID)) .addSection(mAlbumSection); } else { mAlbumSection.setData(mAlbums); } } }
package com.marverenic.music.ui.library.browse; import android.content.Context; import android.databinding.BindingAdapter; import android.databinding.InverseBindingAdapter; import android.databinding.InverseBindingListener; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.marverenic.music.R; import java.util.List; public class BreadCrumbView<T> extends HorizontalScrollView { private LinearLayout mBreadCrumbContainer; private BreadCrumb<T>[] mBreadCrumbs; private int mSelectedIndex; @Nullable private OnBreadCrumbClickListener<T> mListener; @InverseBindingAdapter(attribute = "selectedCrumb") public static <T> T getSelected(BreadCrumbView<T> view) { return view.getBreadCrumb(view.mSelectedIndex).getData(); } @BindingAdapter("selectedCrumb") public static <T> void setSelectedBreadCrumb(BreadCrumbView<T> view, T data) { for (int i = 0; i < view.getBreadCrumbCount(); i++) { if (view.getBreadCrumb(i).getData().equals(data)) { view.setSelectedBreadCrumb(i); return; } } } @BindingAdapter(value = "selectedCrumbAttrChanged") public static <T> void setListeners(BreadCrumbView<T> view, InverseBindingListener inverseBindingListener) { view.setBreadCrumbClickListener(breadCrumb -> inverseBindingListener.onChange()); } public BreadCrumbView(Context context) { super(context); init(); } public BreadCrumbView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public BreadCrumbView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { mBreadCrumbContainer = new LinearLayout(getContext()); mBreadCrumbContainer.setOrientation(LinearLayout.HORIZONTAL); addView(mBreadCrumbContainer); } @Override protected void onFinishInflate() { super.onFinishInflate(); if (getChildCount() > 1) { throw new IllegalStateException("BreadCrumbView should not have any children"); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); scrollToActiveCrumb(); } private void scrollToActiveCrumb() { if (mSelectedIndex < 0 || mSelectedIndex > mBreadCrumbs.length) { return; } View active = mBreadCrumbContainer.getChildAt(mSelectedIndex); boolean startVisible = getScrollX() <= active.getLeft(); boolean endVisible = getScrollX() + getWidth() >= active.getRight(); if (!startVisible || !endVisible) { smoothScrollTo(active.getLeft(), 0); } } public void setBreadCrumbs(List<BreadCrumb<T>> breadCrumbs) { //noinspection unchecked mBreadCrumbs = breadCrumbs.toArray((BreadCrumb<T>[]) new BreadCrumb[breadCrumbs.size()]); mSelectedIndex = breadCrumbs.size() - 1; mBreadCrumbContainer.removeAllViews(); for (int i = 0; i < mBreadCrumbs.length; i++) { BreadCrumb<T> breadCrumb = mBreadCrumbs[i]; breadCrumb.setView(createBreadCrumbView(i != mBreadCrumbs.length - 1)); breadCrumb.getView().setSelected(i == mBreadCrumbs.length - 1); mBreadCrumbContainer.addView(breadCrumb.getView().root); } } public BreadCrumb<T> getBreadCrumb(int index) { return mBreadCrumbs[index]; } public int getBreadCrumbCount() { return mBreadCrumbs.length; } public void setSelectedBreadCrumb(int index) { for (int i = 0; i < mBreadCrumbs.length; i++) { mBreadCrumbs[i].setSelected(i == index); } mSelectedIndex = index; if (!isLayoutRequested()) { scrollToActiveCrumb(); } } private BreadCrumbViewHolder createBreadCrumbView(boolean showSeparator) { LayoutInflater inflater = LayoutInflater.from(getContext()); View breadCrumb = inflater.inflate(R.layout.view_bread_crumb, this, false); BreadCrumbViewHolder viewHolder = new BreadCrumbViewHolder(breadCrumb); viewHolder.label.setOnClickListener(this::onBreadCrumbClick); viewHolder.separator.setVisibility(showSeparator ? View.VISIBLE : View.GONE); return viewHolder; } private void onBreadCrumbClick(View view) { requestLayout(); for (int i = 0; i < mBreadCrumbs.length; i++) { if (mBreadCrumbs[i].getView().label == view) { setSelectedBreadCrumb(i); if (mListener != null) mListener.onBreadcrumbClick(mBreadCrumbs[i]); return; } } } public void setBreadCrumbClickListener(@Nullable OnBreadCrumbClickListener<T> listener) { mListener = listener; } interface OnBreadCrumbClickListener<T> { void onBreadcrumbClick(BreadCrumb<T> breadCrumb); } public static class BreadCrumb<T> { private String mName; private T mData; private BreadCrumbViewHolder mView; private boolean mIsSelected; public BreadCrumb(String name, T data) { mName = name; mData = data; } public String getName() { return mName; } public T getData() { return mData; } final BreadCrumbViewHolder getView() { return mView; } final void setView(BreadCrumbViewHolder view) { mView = view; mView.label.setText(mName); } final boolean isSelected() { return mIsSelected; } final void setSelected(boolean isSelected) { mIsSelected = isSelected; mView.setSelected(isSelected); } } private static class BreadCrumbViewHolder { final View root; final TextView label; final ImageView separator; BreadCrumbViewHolder(View breadCrumbView) { root = breadCrumbView; label = root.findViewById(R.id.bread_crumb_label); separator = root.findViewById(R.id.bread_crumb_divider); setSelected(false); } void setSelected(boolean selected) { label.setAlpha(selected ? 1.0f : 0.7f); } } }
package com.simplemobiletools.gallery.fragments; import android.content.res.Configuration; import android.content.res.Resources; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.LayoutInflater; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import com.simplemobiletools.gallery.Constants; import com.simplemobiletools.gallery.R; import com.simplemobiletools.gallery.Utils; import com.simplemobiletools.gallery.activities.ViewPagerActivity; import com.simplemobiletools.gallery.models.Medium; import java.io.IOException; import java.util.Locale; public class VideoFragment extends ViewPagerFragment implements View.OnClickListener, SurfaceHolder.Callback, MediaPlayer.OnCompletionListener, MediaPlayer.OnVideoSizeChangedListener, SeekBar.OnSeekBarChangeListener { private static final String TAG = VideoFragment.class.getSimpleName(); private static final String PROGRESS = "progress"; private MediaPlayer mediaPlayer; private SurfaceView surfaceView; private SurfaceHolder surfaceHolder; private ImageView playOutline; private TextView currTimeView; private TextView durationView; private Handler timerHandler; private SeekBar seekBar; private Medium medium; private View timeHolder; private boolean isPlaying; private boolean isDragged; private boolean isFullscreen; private int currTime; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.pager_video_item, container, false); medium = (Medium) getArguments().getSerializable(Constants.MEDIUM); if (savedInstanceState != null) { currTime = savedInstanceState.getInt(PROGRESS); } isFullscreen = (getActivity().getWindow().getDecorView().getSystemUiVisibility() & View.SYSTEM_UI_FLAG_FULLSCREEN) == View.SYSTEM_UI_FLAG_FULLSCREEN; setupPlayer(view); view.setOnClickListener(this); return view; } private void setupPlayer(View view) { if (getActivity() == null) return; playOutline = (ImageView) view.findViewById(R.id.video_play_outline); playOutline.setOnClickListener(this); surfaceView = (SurfaceView) view.findViewById(R.id.video_surface); surfaceView.setOnClickListener(this); surfaceHolder = surfaceView.getHolder(); surfaceHolder.addCallback(this); initTimeHolder(view); } public void itemDragged() { pauseVideo(); } @Override public void systemUiVisibilityChanged(boolean toFullscreen) { if (isFullscreen != toFullscreen) { isFullscreen = toFullscreen; checkFullscreen(); } } private void initTimeHolder(View view) { timeHolder = view.findViewById(R.id.video_time_holder); final Resources res = getResources(); final int height = Utils.getNavBarHeight(res); final int left = timeHolder.getPaddingLeft(); final int top = timeHolder.getPaddingTop(); final int right = timeHolder.getPaddingRight(); final int bottom = timeHolder.getPaddingBottom(); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { timeHolder.setPadding(left, top, right, bottom + height); } else { timeHolder.setPadding(left, top, right + height, bottom); } currTimeView = (TextView) view.findViewById(R.id.video_curr_time); durationView = (TextView) view.findViewById(R.id.video_duration); seekBar = (SeekBar) view.findViewById(R.id.video_seekbar); seekBar.setOnSeekBarChangeListener(this); if (isFullscreen) timeHolder.setVisibility(View.INVISIBLE); } private void setupTimeHolder() { final int duration = mediaPlayer.getDuration() / 1000; seekBar.setMax(duration); durationView.setText(getTimeString(duration)); timerHandler = new Handler(); setupTimer(); } private void setupTimer() { getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (mediaPlayer != null && !isDragged && isPlaying) { currTime = mediaPlayer.getCurrentPosition() / 1000; seekBar.setProgress(currTime); currTimeView.setText(getTimeString(currTime)); } timerHandler.postDelayed(this, 1000); } }); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(PROGRESS, currTime); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.video_play_outline: togglePlayPause(); break; default: isFullscreen = !isFullscreen; checkFullscreen(); ((ViewPagerActivity) getActivity()).fragmentClicked(); break; } } private void checkFullscreen() { int anim = R.anim.fade_in; if (isFullscreen) { anim = R.anim.fade_out; seekBar.setOnSeekBarChangeListener(null); } else { seekBar.setOnSeekBarChangeListener(this); } final Animation animation = AnimationUtils.loadAnimation(getContext(), anim); timeHolder.startAnimation(animation); } private void pauseVideo() { if (isPlaying) { togglePlayPause(); } } private void togglePlayPause() { if (getActivity() == null) return; isPlaying = !isPlaying; if (isPlaying) { if (mediaPlayer != null) { mediaPlayer.start(); } playOutline.setImageDrawable(null); } else { if (mediaPlayer != null) { mediaPlayer.pause(); } playOutline.setImageDrawable(getResources().getDrawable(R.mipmap.play_outline_big)); } } @Override public void surfaceCreated(SurfaceHolder holder) { initMediaPlayer(); } private void initMediaPlayer() { try { mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(getContext(), Uri.parse(medium.getPath())); mediaPlayer.setDisplay(surfaceHolder); mediaPlayer.setOnCompletionListener(this); mediaPlayer.setOnVideoSizeChangedListener(this); mediaPlayer.prepare(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); addPreviewImage(); setupTimeHolder(); setProgress(currTime); } catch (IOException e) { Log.e(TAG, "init media player " + e.getMessage()); } } private void setProgress(int seconds) { mediaPlayer.seekTo(seconds * 1000); seekBar.setProgress(seconds); currTimeView.setText(getTimeString(seconds)); } private void addPreviewImage() { mediaPlayer.start(); mediaPlayer.pause(); } @Override public void onPause() { super.onPause(); pauseVideo(); } @Override public void onDestroy() { super.onDestroy(); if (getActivity() != null && !getActivity().isChangingConfigurations()) { cleanup(); } } private void cleanup() { pauseVideo(); if (currTimeView != null) currTimeView.setText(getTimeString(0)); if (mediaPlayer != null) { mediaPlayer.release(); mediaPlayer = null; } if (seekBar != null) seekBar.setProgress(0); if (timerHandler != null) timerHandler.removeCallbacksAndMessages(null); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { } @Override public void onCompletion(MediaPlayer mp) { seekBar.setProgress(seekBar.getMax()); final int duration = mediaPlayer.getDuration() / 1000; currTimeView.setText(getTimeString(duration)); pauseVideo(); } @Override public void onVideoSizeChanged(MediaPlayer mp, int width, int height) { setVideoSize(width, height); } private void setVideoSize(int videoWidth, int videoHeight) { final float videoProportion = (float) videoWidth / (float) videoHeight; final Display display = getActivity().getWindowManager().getDefaultDisplay(); int screenWidth; int screenHeight; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { final DisplayMetrics realMetrics = new DisplayMetrics(); display.getRealMetrics(realMetrics); screenWidth = realMetrics.widthPixels; screenHeight = realMetrics.heightPixels; } else { screenWidth = display.getWidth(); screenHeight = display.getHeight(); } final float screenProportion = (float) screenWidth / (float) screenHeight; final android.view.ViewGroup.LayoutParams lp = surfaceView.getLayoutParams(); if (videoProportion > screenProportion) { lp.width = screenWidth; lp.height = (int) ((float) screenWidth / videoProportion); } else { lp.width = (int) (videoProportion * (float) screenHeight); lp.height = screenHeight; } surfaceView.setLayoutParams(lp); } private String getTimeString(int duration) { final StringBuilder sb = new StringBuilder(8); final int hours = duration / (60 * 60); final int minutes = (duration % (60 * 60)) / 60; final int seconds = ((duration % (60 * 60)) % 60); if (mediaPlayer != null && mediaPlayer.getDuration() > 3600000) { sb.append(String.format(Locale.getDefault(), "%02d", hours)).append(":"); } sb.append(String.format(Locale.getDefault(), "%02d", minutes)); sb.append(":").append(String.format(Locale.getDefault(), "%02d", seconds)); return sb.toString(); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (mediaPlayer != null && fromUser) { setProgress(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { if (mediaPlayer == null) initMediaPlayer(); mediaPlayer.pause(); isDragged = true; } @Override public void onStopTrackingTouch(SeekBar seekBar) { if (!isPlaying) { togglePlayPause(); } else { mediaPlayer.start(); } isDragged = false; } }
package com.slothnull.android.medox.service; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.graphics.BitmapFactory; import android.os.IBinder; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.fitness.data.DataPoint; import com.google.android.gms.fitness.data.DataSource; import com.google.android.gms.fitness.data.Value; import com.google.android.gms.fitness.request.DataSourcesRequest; import com.google.android.gms.fitness.request.OnDataPointListener; import com.google.android.gms.fitness.request.SensorRequest; import com.google.android.gms.fitness.result.DataSourcesResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.slothnull.android.medox.EmergencyNotification; import com.slothnull.android.medox.R; import com.slothnull.android.medox.Splash; import com.slothnull.android.medox.helper.medox; import com.slothnull.android.medox.model.AbstractConfig; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.fitness.Fitness; import com.google.android.gms.fitness.data.DataSet; import com.google.android.gms.fitness.data.DataType; import com.google.android.gms.fitness.data.Field; import com.google.android.gms.fitness.result.DailyTotalResult; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; public class IndicatorsService extends Service { private static final String TAG = "IndicatorsService"; private static final int HEART_REQUEST_INTERVAL = 5; private static final int PEDO_REQUEST_INTERVAL = 10; private static final int CAL_REQUEST_INTERVAL = 10; private boolean emergencyState = false; private GoogleApiClient mClient = null; private OnDataPointListener mListener; Timer pedoTimer; Timer calTimer; public static int oldHeart = 0; public static int oldPedo = 0; public static int oldCal = 0; int currentHeart = 0; int currentPedo = 0; int currentCal = 0; //initially set values to avoid database delay errors public int minHeart = -1; public int maxHeart = -1; @Override public void onCreate() { super.onCreate(); Log.v(TAG, "started"); setData(); //get Google Api client mClient = medox.getGoogleApiHelper().getGoogleApiClient(); //foreground service Intent notificationIntent = new Intent(this, Splash.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Notification notification = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.notification) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.logo)) .setContentTitle("Indicators Service Running") .setContentText("Medox Indicators service running") .setContentIntent(pendingIntent).build(); startForeground(1339/* ID of notification */, notification); //steps timer every 10 seconds updates firebase pedoTimer = new Timer(); pedoTimer.scheduleAtFixedRate(new TimerTask() { synchronized public void run() { readPedo(); } },TimeUnit.SECONDS.toMillis(PEDO_REQUEST_INTERVAL) , TimeUnit.SECONDS.toMillis(PEDO_REQUEST_INTERVAL)); //calories timer every 10 seconds updates firebase calTimer = new Timer(); calTimer.scheduleAtFixedRate(new TimerTask() { synchronized public void run() { readCal(); } },TimeUnit.SECONDS.toMillis(CAL_REQUEST_INTERVAL) , TimeUnit.SECONDS.toMillis(CAL_REQUEST_INTERVAL)); registerHeart(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } public void setData(){ String UID = FirebaseAuth.getInstance().getCurrentUser().getUid(); DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference(); ValueEventListener configListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Get Post object and use the values to update the UI AbstractConfig config = dataSnapshot.getValue(AbstractConfig.class); if (config.maxHeartRate != null) { maxHeart = Integer.parseInt(config.maxHeartRate); Log.i(TAG, "maxHeart: " + maxHeart); } if (config.minHeartRate != null) { minHeart = Integer.parseInt(config.minHeartRate); Log.i(TAG, "minHeart: " + minHeart); } } @Override public void onCancelled(DatabaseError databaseError) { // Getting Post failed, log a message Log.w(TAG, "loadPost:onCancelled", databaseError.toException()); } }; mDatabase.child("users").child(UID).child("config") .addValueEventListener(configListener); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { super.onDestroy(); Log.v("STOP_SERVICE", "DONE"); } public void checkHeart(int heartRate){ Log.i(TAG, "checking Heart Rate" ); if (maxHeart != -1 && minHeart != -1){ //initialized "already get that from db" if ((heartRate > maxHeart || heartRate < minHeart) && !emergencyState){ //!emergencyState to avoid resend emergency Log.i(TAG, "HeartRate not safe: sending emerg." ); emergencyState = true; sendEmergency(); } if(heartRate < maxHeart && heartRate > minHeart && emergencyState){ //returned to normal emergencyState = false; } } } public void sendEmergency(){ // Launch Emergency Activity Intent intent = new Intent(this, EmergencyNotification.class); intent.putExtra(EmergencyNotification.INDICATORS_KEY, "true"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } /** * Read the current daily step total, computed from midnight of the current day * on the device's current timezone. */ private void readPedo () { Log.i(TAG, "readPedo Called"); //[START_GET_STEPS_COUNT] int total = 0; PendingResult<DailyTotalResult> result = Fitness.HistoryApi.readDailyTotal(mClient, DataType.TYPE_STEP_COUNT_DELTA); DailyTotalResult totalResult = result.await(5, TimeUnit.SECONDS); if (totalResult.getStatus().isSuccess()) { DataSet totalSet = totalResult.getTotal(); total = totalSet.isEmpty() ? 0 : totalSet.getDataPoints().get(0).getValue(Field.FIELD_STEPS).asInt(); } else { Log.w(TAG, "There was a problem getting the step count."); } Log.i(TAG, "Total steps: " + total); currentPedo = total; //[END_GET_STEPS_COUNT] //[START_CHECK_SEND_PROCESS] //to avoid sending data if not too much change boolean pedoDiff = Math.abs(currentPedo - oldPedo) > 5; if(pedoDiff){ //if user not signed in stop service Log.i(TAG, "sending pedo rate to fb"); FirebaseUser auth = FirebaseAuth.getInstance().getCurrentUser(); if(auth == null){ stopService(new Intent(this, IndicatorsService.class)); return; } //send data to db DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference(); String UID = FirebaseAuth.getInstance().getCurrentUser().getUid(); mDatabase.child("users").child(UID).child("data").child("pedo") .setValue(String.valueOf(currentPedo)); } Log.d(TAG, "Pedo Rate: " + Integer.toString(currentPedo)); oldPedo = currentPedo; //[END_CHECK_SEND_PROCESS] } /** * Read the current daily step total, computed from midnight of the current day * on the device's current timezone. */ private void readCal () { Log.i(TAG, "readCal Called"); //[START_GET_STEPS_COUNT] int total = 0; PendingResult<DailyTotalResult> result = Fitness.HistoryApi.readDailyTotal(mClient, DataType.AGGREGATE_CALORIES_EXPENDED); DailyTotalResult totalResult = result.await(5, TimeUnit.SECONDS); if (totalResult.getStatus().isSuccess()) { DataSet totalSet = totalResult.getTotal(); total = Math.round(totalSet.isEmpty() ? 0 : totalSet.getDataPoints().get(0).getValue(Field.FIELD_CALORIES).asFloat()); } else { Log.w(TAG, "There was a problem getting the Calories"); } Log.i(TAG, "Total Calories: " + total); currentCal = total; //[END_GET_STEPS_COUNT] //[START_CHECK_SEND_PROCESS] //to avoid sending data if not too much change boolean calDiff = Math.abs(currentCal - oldCal) > 5; if(calDiff){ //if user not signed in stop service Log.i(TAG, "sending Calories to fb"); FirebaseUser auth = FirebaseAuth.getInstance().getCurrentUser(); if(auth == null){ stopService(new Intent(this, IndicatorsService.class)); return; } //send data to db DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference(); String UID = FirebaseAuth.getInstance().getCurrentUser().getUid(); mDatabase.child("users").child(UID).child("data").child("calories") .setValue(String.valueOf(currentCal)); } Log.d(TAG, "Calories: " + Integer.toString(currentCal)); oldCal = currentCal; //[END_CHECK_SEND_PROCESS] } /** * Read the current heart rate and sends it to fb, * also checks if heart rate is in the safe region */ public void registerHeart(){ Log.i(TAG, "readHeart Called"); //[START_GET_HEART_RATE] mListener = new OnDataPointListener() { @Override public void onDataPoint(DataPoint dataPoint) { for (Field field : dataPoint.getDataType().getFields()) { Value val = dataPoint.getValue(field); Log.i(TAG, "Detected DataPoint field: " + field.getName()); Log.i(TAG, "Detected DataPoint value: " + val); currentHeart = val.asInt(); } } }; Fitness.SensorsApi.findDataSources(mClient, new DataSourcesRequest.Builder() .setDataTypes(DataType.TYPE_HEART_RATE_BPM) .setDataSourceTypes(DataSource.TYPE_RAW, DataSource.TYPE_DERIVED) .build()) .setResultCallback(new ResultCallback<DataSourcesResult>() { @Override public void onResult(DataSourcesResult dataSourcesResult) { for (DataSource dataSource : dataSourcesResult.getDataSources()) { // There isn't heart rate source here final DataType dataType = dataSource.getDataType(); Fitness.SensorsApi.add(mClient, new SensorRequest.Builder() .setDataSource(dataSource) .setDataType(dataType) .setSamplingRate(HEART_REQUEST_INTERVAL, TimeUnit.SECONDS) .build(), mListener) .setResultCallback(new ResultCallback<Status>() { @Override public void onResult(Status status) { if (status.isSuccess()) { Log.i(TAG, "Listener registered!"); } else { Log.i(TAG, "Listener not registered."); } } }); } } }); //[END_GET_HEART_RATE] //[START_CHECK_SEND_PROCESS] //to avoid sending Location if not too much change boolean heartDiff = Math.abs(currentHeart - oldHeart) > 1; if(heartDiff){ //if user not signed in stop service Log.i(TAG, "sending heart rate to fb"); FirebaseUser auth = FirebaseAuth.getInstance().getCurrentUser(); if(auth == null){ stopService(new Intent(this, IndicatorsService.class)); return; } //send data to db DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference(); String UID = FirebaseAuth.getInstance().getCurrentUser().getUid(); mDatabase.child("users").child(UID).child("data").child("heartRate") .setValue(String.valueOf(currentHeart)); } Log.d(TAG, "Heart Rate: " + Integer.toString(currentHeart)); oldHeart = currentHeart; checkHeart(currentHeart); //[END_CHECK_SEND_PROCESS] } }
package de.bitshares_munich.adapters; import android.content.Context; import android.graphics.Color; import android.support.v4.content.ContextCompat; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.List; import java.util.Locale; import de.bitshares_munich.models.TransactionDetails; import de.bitshares_munich.smartcoinswallet.R; import de.bitshares_munich.utils.Helper; import de.codecrafters.tableview.TableDataAdapter; public class TransactionsTableAdapter extends TableDataAdapter<TransactionDetails> { Context context; public TransactionsTableAdapter(Context _context, List<TransactionDetails> data) { super(_context, data); context = _context; } @Override public View getCellView(int rowIndex, int columnIndex, ViewGroup parentView) { TransactionDetails transactiondetails = getRowData(rowIndex); View renderedView = null; switch (columnIndex) { case 0: renderedView = renderDateView(transactiondetails); break; case 1: renderedView = renderSendRecieve(transactiondetails); break; case 2: renderedView = renderDetails(transactiondetails); break; case 3: renderedView = renderAmount(transactiondetails); break; } return renderedView; } private View renderDateView(TransactionDetails transactiondetails) { LayoutInflater me = getLayoutInflater(); View v = me.inflate(R.layout.transactionsdateview, null); TextView textView = (TextView) v.findViewById(R.id.transactiondate); textView.setText(transactiondetails.getDateString()); TextView textView2 = (TextView) v.findViewById(R.id.transactiontime); textView2.setText(transactiondetails.getTimeString() + " " + transactiondetails.getTimeZone()); TextView textView3 = (TextView) v.findViewById(R.id.transactionttimezone); textView3.setVisibility(View.GONE); return v; } private View renderSendRecieve(TransactionDetails transactiondetails) { LayoutInflater me = getLayoutInflater(); View v = me.inflate(R.layout.transactionssendrecieve, null); ImageView imgView = (ImageView) v.findViewById(R.id.iv); if ( transactiondetails.getSent() ) { imgView.setImageResource(R.drawable.send); } else { imgView.setImageResource(R.drawable.receive); } return v; } private View renderDetails(TransactionDetails transactiondetails) { LayoutInflater me = getLayoutInflater(); View v = me.inflate(R.layout.transactiondetailsview, null); TextView textView = (TextView) v.findViewById(R.id.transactiondetailsto); String tString = context.getText(R.string.to_capital) + ": " + transactiondetails.getDetailsTo(); textView.setTextSize(TypedValue.COMPLEX_UNIT_PT,7); textView.setText(tString); tString = context.getText(R.string.from_capital) + ": " + transactiondetails.getDetailsFrom(); TextView textView1 = (TextView) v.findViewById(R.id.transactiondetailsfrom); textView1.setTextSize(TypedValue.COMPLEX_UNIT_PT,7); textView1.setText(tString); if(transactiondetails.getDetailsMemo() == null || transactiondetails.getDetailsMemo().isEmpty()) { TextView textView2 = (TextView) v.findViewById(R.id.transactiondetailsmemo); textView2.setText(""); textView2.setTextSize(TypedValue.COMPLEX_UNIT_PT,7); textView2.setVisibility(View.GONE); } else { tString = transactiondetails.getDetailsMemo(); tString = tString.substring(0, Math.min(tString.length(), 53)); tString = abbreviateString(tString, 50); tString = context.getText(R.string.memo_capital) + " : " + tString; TextView textView2 = (TextView) v.findViewById(R.id.transactiondetailsmemo); textView2.setTextSize(TypedValue.COMPLEX_UNIT_PT,7); textView2.setText(tString); } return v; } private View renderAmount(TransactionDetails transactiondetails) { LayoutInflater me = getLayoutInflater(); View v = me.inflate(R.layout.transactionsendamountview, null); int colorText; Locale locale; NumberFormat format; String language; language = Helper.fetchStringSharePref(context, context.getString(R.string.pref_language)); locale = new Locale(language); Helper.setLocaleNumberFormat(locale, 1); if( transactiondetails.getSent() ) { TextView textView = (TextView) v.findViewById(R.id.transactionssendamount); textView.setTextColor(ContextCompat.getColor(getContext(),R.color.sendamount)); String amount = Helper.setLocaleNumberFormat(locale,transactiondetails.getAmount()); textView.setText("- " + amount + " " + transactiondetails.getAssetSymbol()); amount = ""; if ( transactiondetails.getFaitAmount() == 0 ) { TextView textView2 = (TextView) v.findViewById(R.id.transactionssendfaitamount); textView2.setText(""); } else { TextView textView2 = (TextView) v.findViewById(R.id.transactionssendfaitamount); textView2.setTextColor(ContextCompat.getColor(getContext(),R.color.sendamount)); double faitAmount = transactiondetails.getFaitAmount(); if ( faitAmount > 0.009 ) { amount = String.format(locale,"%.2f",faitAmount); } else if ( (faitAmount < 0.009) && (faitAmount > 0.0009) ) { amount = String.format(locale,"%.3f",faitAmount); } else if ( (faitAmount < 0.0009) && (faitAmount > 0.00009) ) { amount = String.format(locale,"%.4f",faitAmount); } else { amount = String.format(locale,"%.5f",faitAmount); } String displayFaitAmount = ""; if ( Helper.isRTL(locale,transactiondetails.getFaitAssetSymbol()) ) { displayFaitAmount = String.format(locale,"%s %s",amount,transactiondetails.getFaitAssetSymbol()); } else { displayFaitAmount = String.format(locale,"%s %s",transactiondetails.getFaitAssetSymbol(),amount); } textView2.setText("- " + displayFaitAmount); } } else { TextView textView = (TextView) v.findViewById(R.id.transactionssendamount); textView.setTextColor(ContextCompat.getColor(getContext(),R.color.recieveamount)); String amount = Helper.setLocaleNumberFormat(locale,transactiondetails.getAmount()); textView.setText("+ " + amount + " " + transactiondetails.getAssetSymbol()); amount = ""; if ( transactiondetails.getFaitAmount() == 0 ) { TextView textView2 = (TextView) v.findViewById(R.id.transactionssendfaitamount); textView2.setText(""); } else { TextView textView2 = (TextView) v.findViewById(R.id.transactionssendfaitamount); textView2.setTextColor(ContextCompat.getColor(getContext(), R.color.recieveamount)); double faitAmount = transactiondetails.getFaitAmount(); if ( faitAmount > 0.009 ) { amount = String.format(locale,"%.2f",faitAmount); } else if ( (faitAmount < 0.009) && (faitAmount > 0.0009) ) { amount = String.format(locale,"%.3f",faitAmount); } else if ( (faitAmount < 0.0009) && (faitAmount > 0.00009) ) { amount = String.format(locale,"%.4f",faitAmount); } else { amount = String.format(locale,"%.5f",faitAmount); } String displayFaitAmount = ""; if ( Helper.isRTL(locale,transactiondetails.getFaitAssetSymbol()) ) { displayFaitAmount = String.format(locale,"%s %s",amount,transactiondetails.getFaitAssetSymbol()); } else { displayFaitAmount = String.format(locale,"%s %s",transactiondetails.getFaitAssetSymbol(),amount); } textView2.setText("+ " + displayFaitAmount); } } return v; } public static String abbreviateString(String input, int maxLength) { if (input.length() <= maxLength) return input; else return input.substring(0, maxLength-3) + "..."; } }
package io.github.webbluetoothcg.bletestperipheral; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattServer; import android.bluetooth.BluetoothGattServerCallback; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothManager; import android.bluetooth.le.AdvertiseCallback; import android.bluetooth.le.AdvertiseData; import android.bluetooth.le.AdvertiseSettings; import android.bluetooth.le.BluetoothLeAdvertiser; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import java.util.Arrays; public class Peripheral extends Activity implements ServiceFragment.OnFragmentInteractionListener{ private static final int REQUEST_ENABLE_BT = 1; private static final String TAG = Peripheral.class.getCanonicalName(); private static final String CURRENT_FRAGMENT_TAG = "CURRENT_FRAGMENT"; private TextView mAdvStatus; private TextView mConnectionStatus; private BluetoothGattService mBluetoothGattService; private BluetoothDevice mBluetoothDevice; private BluetoothManager mBluetoothManager; private BluetoothAdapter mBluetoothAdapter; private AdvertiseData mAdvData; private AdvertiseSettings mAdvSettings; private BluetoothLeAdvertiser mAdvertiser; private final AdvertiseCallback mAdvCallback = new AdvertiseCallback() { @Override public void onStartFailure(int errorCode) { super.onStartFailure(errorCode); Log.e(TAG, "Not broadcasting: " + errorCode); int statusText; switch (errorCode) { case ADVERTISE_FAILED_ALREADY_STARTED: statusText = R.string.status_advertising; Log.w(TAG, "App was already advertising"); break; case ADVERTISE_FAILED_DATA_TOO_LARGE: statusText = R.string.status_advDataTooLarge; break; case ADVERTISE_FAILED_FEATURE_UNSUPPORTED: statusText = R.string.status_advFeatureUnsupported; break; case ADVERTISE_FAILED_INTERNAL_ERROR: statusText = R.string.status_advInternalError; break; case ADVERTISE_FAILED_TOO_MANY_ADVERTISERS: statusText = R.string.status_advTooManyAdvertisers; break; default: statusText = R.string.status_notAdvertising; Log.wtf(TAG, "Unhandled error: " + errorCode); } mAdvStatus.setText(statusText); } @Override public void onStartSuccess(AdvertiseSettings settingsInEffect) { super.onStartSuccess(settingsInEffect); Log.v(TAG, "Broadcasting"); mAdvStatus.setText(R.string.status_advertising); } }; private BluetoothGattServer mGattServer; private final BluetoothGattServerCallback mGattServerCallback = new BluetoothGattServerCallback() { @Override public void onConnectionStateChange(BluetoothDevice device, final int status, int newState) { super.onConnectionStateChange(device, status, newState); if (status == BluetoothGatt.GATT_SUCCESS) { if (newState == BluetoothGatt.STATE_CONNECTED) { mBluetoothDevice = device; String deviceName = mBluetoothDevice.getName(); // Some devices don't return a name. if (deviceName == null) { deviceName = mBluetoothDevice.getAddress(); } final String message = getString(R.string.status_connectedTo) + " " + deviceName; runOnUiThread(new Runnable() { @Override public void run() { mConnectionStatus.setText(message); } }); Log.v(TAG, "Connected to device: " + mBluetoothDevice.getAddress()); } else if (newState == BluetoothGatt.STATE_DISCONNECTED) { mBluetoothDevice = null; runOnUiThread(new Runnable() { @Override public void run() { mConnectionStatus.setText(R.string.status_notConnected); } }); Log.v(TAG, "Disconnected from device"); } } else { mBluetoothDevice = null; // There are too many gatt errors (some of them not even in the documentation) so we just // show the error to the user. final String errorMessage = getString(R.string.errorCode) + ": " + status; runOnUiThread(new Runnable() { @Override public void run() { mConnectionStatus.setText(errorMessage); } }); Log.e(TAG, "Error when connecting: " + status); } } @Override public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) { super.onCharacteristicReadRequest(device, requestId, offset, characteristic); Log.d(TAG, "Device tried to read characteristic: " + characteristic.getUuid()); Log.d(TAG, "Value: " + Arrays.toString(characteristic.getValue())); if (offset == 0) { mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, characteristic.getValue()); } else { mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_INVALID_OFFSET, offset, null); } } @Override public void onNotificationSent(BluetoothDevice device, int status) { super.onNotificationSent(device, status); Log.v(TAG, "Notification sent. Status: " + status); } }; ////// Lifecycle Callbacks ////// @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_peripherals); mAdvStatus = (TextView) findViewById(R.id.textView_advertisingStatus); mConnectionStatus = (TextView) findViewById(R.id.textView_connectionStatus); // TODO(g-ortuno): This can be moved to Peripherals. ensureBleFeaturesAvailable(); // If we are not being restored from a previous state then create and add the fragment. // Initialize it to null otherwise the compiler complains. ServiceFragment currentServiceFragment = null; if (savedInstanceState == null) { int peripheralIndex = getIntent().getIntExtra(Peripherals.EXTRA_PERIPHERAL_INDEX, /* default */ -1); if (peripheralIndex == 0) { currentServiceFragment = new BatteryServiceFragment(); } else if (peripheralIndex == 1) { currentServiceFragment = new HeartRateServiceFragment(); } else { Log.wtf(TAG, "Service doesn't exist"); } getFragmentManager() .beginTransaction() .add(R.id.fragment_container, currentServiceFragment, CURRENT_FRAGMENT_TAG) .commit(); } else { currentServiceFragment = (ServiceFragment) getFragmentManager() .findFragmentByTag(CURRENT_FRAGMENT_TAG); } mBluetoothGattService = currentServiceFragment.getBluetoothGattService(); mAdvSettings = new AdvertiseSettings.Builder() .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED) .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM) .setConnectable(true) .build(); mAdvData = new AdvertiseData.Builder() .setIncludeDeviceName(true) .setIncludeTxPowerLevel(true) .build(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_ENABLE_BT) { if (resultCode == RESULT_OK) { if (!mBluetoothAdapter.isMultipleAdvertisementSupported()) { Toast.makeText(this, R.string.bluetoothAdvertisingNotSupported, Toast.LENGTH_LONG).show(); Log.e(TAG, "Advertising not supported"); finish(); } else { mAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser(); onStart(); } } else { //TODO(g-ortuno): UX for asking the user to activate bt Toast.makeText(this, R.string.bluetoothNotEnabled, Toast.LENGTH_LONG).show(); Log.e(TAG, "Bluetooth not enabled"); finish(); } } } @Override protected void onStart() { super.onStart(); mGattServer = mBluetoothManager.openGattServer(this, mGattServerCallback); // If the user disabled Bluetooth when the app was in the background, // openGattServer() will return null. if (mAdvertiser != null && mGattServer != null) { resetStatusViews(); // Add a service for a total of three services (Generic Attribute and Generic Access // are present by default). mGattServer.addService(mBluetoothGattService); mAdvertiser.startAdvertising(mAdvSettings, mAdvData, mAdvCallback); } else { ensureBleFeaturesAvailable(); } } @Override protected void onStop() { super.onPause(); if (mAdvertiser != null) { // If stopAdvertising() gets called before close() a null // pointer exception is raised. mGattServer.close(); mAdvertiser.stopAdvertising(mAdvCallback); resetStatusViews(); } } @Override public void onNotifyButtonPressed(BluetoothGattCharacteristic characteristic) { if (mBluetoothDevice != null) { mGattServer.notifyCharacteristicChanged(mBluetoothDevice, characteristic, // true for indication (acknowledge) and false for notification (unacknowledge). // In this case there is no callback for us to receive the acknowledgement from // the client so we just send a notification. false); } else { Toast.makeText(this, R.string.bluetoothDeviceNotConnected, Toast.LENGTH_SHORT).show(); } } private void resetStatusViews() { mAdvStatus.setText(R.string.status_notAdvertising); mConnectionStatus.setText(R.string.status_notConnected); } ////// Bluetooth ////// private void ensureBleFeaturesAvailable() { mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = mBluetoothManager.getAdapter(); if (mBluetoothAdapter == null) { Toast.makeText(this, R.string.bluetoothNotSupported, Toast.LENGTH_LONG).show(); Log.e(TAG, "Bluetooth not supported"); finish(); } else if (!mBluetoothAdapter.isEnabled()) { // Make sure bluetooth is enabled. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } else if (!mBluetoothAdapter.isMultipleAdvertisementSupported()) { // Make sure device supports LE advertising. Toast.makeText(this, R.string.bluetoothAdvertisingNotSupported, Toast.LENGTH_LONG).show(); Log.e(TAG, "Advertising not supported"); finish(); } else { mAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser(); } } }
package iq.qicard.hussain.securepreferences; import org.apache.commons.codec.binary.Base64; import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.Nullable; import java.io.UnsupportedEncodingException; import java.util.HashSet; import java.util.Map; import java.util.Set; import iq.qicard.hussain.securepreferences.security.CipherAES; import iq.qicard.hussain.securepreferences.security.CipherSHA; import iq.qicard.hussain.securepreferences.util.AesCipherHelper; public class SecurePreferences implements SharedPreferences{ private static final String DEFAULT_FILENAME = "secured_prefs"; private static final String CHARSET = "UTF-8"; private final CipherAES mAES; private Context mContext; private SharedPreferences mProxyPreferences; private SecurePreferences(Context context, String fileName, String password) { this.mContext = context; this.mAES = AesCipherHelper.generateFromSinglePassphrase(password); this.mProxyPreferences = mContext.getSharedPreferences(fileName, Context.MODE_PRIVATE); } private String generateKeyHash(String key){ try{ byte[] mBytes = CipherSHA.hashUsingSHA256(key.getBytes(CHARSET)); return Base64.encodeBase64URLSafeString(mBytes); }catch(UnsupportedEncodingException e){ throw new IllegalStateException(e.getMessage()); } } private String encryptToBase64(String data){ try{ byte[] mBytes = mAES.encrypt(data.getBytes(CHARSET)); return Base64.encodeBase64URLSafeString(mBytes); }catch(UnsupportedEncodingException e){ throw new IllegalStateException(e.getMessage()); } } private String decryptFromBase64(String base64Data){ try{ byte[] data = Base64.decodeBase64(base64Data); byte[] decrypted = mAES.decrypt(data); return new String(decrypted, CHARSET); }catch(UnsupportedEncodingException e){ throw new IllegalStateException(e.getMessage()); } } @Override public Map<String, ?> getAll() { return null; } @Nullable @Override public String getString(String key, String defValue){ final String encryptedData = mProxyPreferences.getString(generateKeyHash(key), null); return encryptedData != null ? decryptFromBase64(encryptedData) : defValue; } @Nullable @Override public Set<String> getStringSet(String key, Set<String> set) { return null; } @Override public int getInt(String key, int defValue) { return 0; } @Override public long getLong(String key, long defValue) { return 0; } @Override public float getFloat(String key, float defValue) { return 0; } @Override public boolean getBoolean(String key, boolean defValue) { return false; } @Override public boolean contains(String key) { return mProxyPreferences.contains(generateKeyHash(key)); } @Override public SharedPreferences.Editor edit() { return new Editor(); } @Override public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) { mProxyPreferences.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener); } @Override public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) { mProxyPreferences.unregisterOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener); } public class Editor implements SharedPreferences.Editor{ protected SharedPreferences.Editor mProxyEditor; public Editor(){ this.mProxyEditor = SecurePreferences.this.mProxyPreferences.edit(); } @Override public SharedPreferences.Editor putString(String key, String data){ String hashedKey = generateKeyHash(key); String encryptedData = encryptToBase64(data); mProxyEditor.putString(hashedKey, encryptedData); return this; } @Override public SharedPreferences.Editor putStringSet(String key, Set<String> set) { String hashedKey = generateKeyHash(key); Set<String> encryptedSet = new HashSet<>(); for(String temp : set) { encryptedSet.add(encryptToBase64(temp)); } mProxyEditor.putStringSet(hashedKey, encryptedSet); return this; } @Override public SharedPreferences.Editor putInt(String key, int data) { String hashedKey = generateKeyHash(key); String encryptedData = encryptToBase64(Integer.toString(data)); mProxyEditor.putString(hashedKey, encryptedData); return this; } @Override public SharedPreferences.Editor putLong(String key, long data){ String hashedKey = generateKeyHash(key); String encryptedData = encryptToBase64(Long.toString(data)); mProxyEditor.putString(hashedKey, encryptedData); return this; } @Override public SharedPreferences.Editor putFloat(String key, float data) { String hashedKey = generateKeyHash(key); String encryptedData = encryptToBase64(Float.toString(data)); mProxyEditor.putString(hashedKey, encryptedData); return this; } @Override public SharedPreferences.Editor putBoolean(String key, boolean data) { String hashedKey = generateKeyHash(key); String encryptedData = encryptToBase64(Boolean.toString(data)); mProxyEditor.putString(hashedKey, encryptedData); return this; } @Override public SharedPreferences.Editor remove(String key) { mProxyEditor.remove(generateKeyHash(key)); return this; } @Override public SharedPreferences.Editor clear() { mProxyEditor.clear(); return this; } @Override public boolean commit() { return mProxyEditor.commit(); } @Override public void apply() { mProxyEditor.commit(); } } }
package org.shadowice.flocke.andotp.Dialogs; import android.app.AlertDialog; import android.content.DialogInterface; import androidx.appcompat.app.AppCompatDelegate; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import com.github.aakira.expandablelayout.ExpandableLayoutListenerAdapter; import com.github.aakira.expandablelayout.ExpandableLinearLayout; import org.shadowice.flocke.andotp.Activities.MainActivity; import org.shadowice.flocke.andotp.Database.Entry; import org.shadowice.flocke.andotp.R; import org.shadowice.flocke.andotp.Utilities.Settings; import org.shadowice.flocke.andotp.Utilities.TokenCalculator; import org.shadowice.flocke.andotp.View.EntriesCardAdapter; import org.shadowice.flocke.andotp.View.TagsAdapter; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.concurrent.Callable; public class ManualEntryDialog { public static void show(final MainActivity callingActivity, Settings settings, final EntriesCardAdapter adapter) { show(callingActivity, settings, adapter, null); } public static void show(final MainActivity callingActivity, Settings settings, final EntriesCardAdapter adapter, Entry oldEntry) { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); boolean isNewEntry = oldEntry == null; ViewGroup container = callingActivity.findViewById(R.id.main_content); View inputView = callingActivity.getLayoutInflater().inflate(R.layout.dialog_manual_entry, container, false); if (settings.getBlockAccessibility()) inputView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); final Spinner typeInput = inputView.findViewById(R.id.manual_type); final EditText issuerInput = inputView.findViewById(R.id.manual_issuer); final EditText labelInput = inputView.findViewById(R.id.manual_label); final EditText secretInput = inputView.findViewById(R.id.manual_secret); final TextView secretView = inputView.findViewById(R.id.manual_secret_view); final EditText counterInput = inputView.findViewById(R.id.manual_counter); final EditText periodInput = inputView.findViewById(R.id.manual_period); final EditText digitsInput = inputView.findViewById(R.id.manual_digits); final LinearLayout counterLayout = inputView.findViewById(R.id.manual_layout_counter); final LinearLayout periodLayout = inputView.findViewById(R.id.manual_layout_period); final Spinner algorithmInput = inputView.findViewById(R.id.manual_algorithm); final Button tagsInput = inputView.findViewById(R.id.manual_tags); final ArrayAdapter<TokenCalculator.HashAlgorithm> algorithmAdapter = new ArrayAdapter<>(callingActivity, android.R.layout.simple_expandable_list_item_1, TokenCalculator.HashAlgorithm.values()); final ArrayAdapter<Entry.OTPType> typeAdapter = new ArrayAdapter<>(callingActivity, android.R.layout.simple_expandable_list_item_1, Entry.OTPType.values()); typeInput.setAdapter(typeAdapter); algorithmInput.setAdapter(algorithmAdapter); periodInput.setText(String.format(Locale.US, "%d", TokenCalculator.TOTP_DEFAULT_PERIOD)); digitsInput.setText(String.format(Locale.US, "%d", TokenCalculator.TOTP_DEFAULT_DIGITS)); counterInput.setText(String.format(Locale.US, "%d", TokenCalculator.HOTP_INITIAL_COUNTER)); typeInput.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { Entry.OTPType type = (Entry.OTPType) adapterView.getSelectedItem(); if (type == Entry.OTPType.STEAM) { counterLayout.setVisibility(View.GONE); periodLayout.setVisibility(View.VISIBLE); digitsInput.setText(String.format(Locale.US, "%d", TokenCalculator.STEAM_DEFAULT_DIGITS)); periodInput.setText(String.format(Locale.US, "%d", TokenCalculator.TOTP_DEFAULT_PERIOD)); algorithmInput.setSelection(algorithmAdapter.getPosition(TokenCalculator.HashAlgorithm.SHA1)); digitsInput.setEnabled(false); periodInput.setEnabled(false); algorithmInput.setEnabled(false); } else if (type == Entry.OTPType.TOTP) { counterLayout.setVisibility(View.GONE); periodLayout.setVisibility(View.VISIBLE); digitsInput.setText(String.format(Locale.US, "%d", TokenCalculator.TOTP_DEFAULT_DIGITS)); digitsInput.setEnabled(isNewEntry); periodInput.setEnabled(isNewEntry); algorithmInput.setEnabled(isNewEntry); } else if (type == Entry.OTPType.HOTP) { counterLayout.setVisibility(View.VISIBLE); periodLayout.setVisibility(View.GONE); digitsInput.setText(String.format(Locale.US, "%d", TokenCalculator.TOTP_DEFAULT_DIGITS)); digitsInput.setEnabled(isNewEntry); periodInput.setEnabled(isNewEntry); algorithmInput.setEnabled(isNewEntry); } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); List<String> allTags = adapter.getTags(); HashMap<String, Boolean> tagsHashMap = new HashMap<>(); for(String tag: allTags) { tagsHashMap.put(tag, false); } final TagsAdapter tagsAdapter = new TagsAdapter(callingActivity, tagsHashMap); final Callable tagsCallable = new Callable() { @Override public Object call() throws Exception { List<String> selectedTags = tagsAdapter.getActiveTags(); StringBuilder stringBuilder = new StringBuilder(); for(int j = 0; j < selectedTags.size(); j++) { stringBuilder.append(selectedTags.get(j)); if(j < selectedTags.size() - 1) { stringBuilder.append(", "); } } tagsInput.setText(stringBuilder.toString()); return null; } }; tagsInput.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TagsDialog.show(callingActivity, tagsAdapter, tagsCallable, tagsCallable); } }); final Button expandButton = inputView.findViewById(R.id.dialog_expand_button); // Dirty fix for the compound drawable to avoid crashes on KitKat expandButton.setCompoundDrawablesWithIntrinsicBounds(null, null, callingActivity.getResources().getDrawable(R.drawable.ic_arrow_down_accent), null); final ExpandableLinearLayout expandLayout = inputView.findViewById(R.id.dialog_expand_layout); expandButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { expandLayout.toggle(); } }); expandLayout.setListener(new ExpandableLayoutListenerAdapter() { @Override public void onOpened() { super.onOpened(); expandButton.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_up_accent, 0); } @Override public void onClosed() { super.onClosed(); expandButton.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_down_accent, 0); } }); AlertDialog.Builder builder = new AlertDialog.Builder(callingActivity); builder.setTitle(R.string.dialog_title_manual_entry) .setView(inputView) .setPositiveButton(R.string.button_save, null) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) {} }); AlertDialog dialog = builder.create(); dialog.show(); final Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); positiveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Replace spaces with empty characters String secret = secretInput.getText().toString().replaceAll("\\s+",""); if (!Entry.validateSecret(secret)) { secretInput.setError(callingActivity.getString(R.string.error_invalid_secret)); return; } Entry.OTPType type = (Entry.OTPType) typeInput.getSelectedItem(); TokenCalculator.HashAlgorithm algorithm = (TokenCalculator.HashAlgorithm) algorithmInput.getSelectedItem(); int digits = Integer.parseInt(digitsInput.getText().toString()); String issuer = issuerInput.getText().toString(); String label = labelInput.getText().toString(); if (type == Entry.OTPType.TOTP || type == Entry.OTPType.STEAM) { int period = Integer.parseInt(periodInput.getText().toString()); if (oldEntry == null) { Entry e = new Entry(type, secret, period, digits, issuer, label, algorithm, tagsAdapter.getActiveTags()); e.updateOTP(); e.setLastUsed(System.currentTimeMillis()); adapter.addEntry(e); } else { oldEntry.setIssuer(issuer); oldEntry.setLabel(label); oldEntry.setTags(tagsAdapter.getActiveTags()); adapter.saveAndRefresh(settings.getAutoBackupEncryptedFullEnabled()); } callingActivity.refreshTags(); } else if (type == Entry.OTPType.HOTP) { long counter = Long.parseLong(counterInput.getText().toString()); if (oldEntry == null) { Entry e = new Entry(type, secret, counter, digits, issuer, label, algorithm, tagsAdapter.getActiveTags()); e.updateOTP(); e.setLastUsed(System.currentTimeMillis()); adapter.addEntry(e); } else { oldEntry.setIssuer(issuer); oldEntry.setLabel(label); oldEntry.setTags(tagsAdapter.getActiveTags()); adapter.saveAndRefresh(settings.getAutoBackupEncryptedFullEnabled()); } } dialog.dismiss(); } }); positiveButton.setEnabled(false); TextWatcher watcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { if ((TextUtils.isEmpty(labelInput.getText()) && TextUtils.isEmpty(issuerInput.getText())) || TextUtils.isEmpty(secretInput.getText()) || TextUtils.isEmpty(digitsInput.getText()) || Integer.parseInt(digitsInput.getText().toString()) == 0) { positiveButton.setEnabled(false); } else { Entry.OTPType type = (Entry.OTPType) typeInput.getSelectedItem(); if (type == Entry.OTPType.HOTP) { if (TextUtils.isEmpty(counterInput.getText())) { positiveButton.setEnabled(false); } else { positiveButton.setEnabled(true); } } else if (type == Entry.OTPType.TOTP || type == Entry.OTPType.STEAM) { if (TextUtils.isEmpty(periodInput.getText()) || Integer.parseInt(periodInput.getText().toString()) == 0) { positiveButton.setEnabled(false); } else { positiveButton.setEnabled(true); } } else { positiveButton.setEnabled(true); } } } }; labelInput.addTextChangedListener(watcher); issuerInput.addTextChangedListener(watcher); secretInput.addTextChangedListener(watcher); periodInput.addTextChangedListener(watcher); digitsInput.addTextChangedListener(watcher); counterInput.addTextChangedListener(watcher); if (!isNewEntry) { Entry.OTPType oldType = oldEntry.getType(); typeInput.setSelection(typeAdapter.getPosition(oldType)); issuerInput.setText(oldEntry.getIssuer()); labelInput.setText(oldEntry.getLabel()); secretView.setText(oldEntry.getSecretEncoded()); digitsInput.setText(Integer.toString(oldEntry.getDigits())); algorithmInput.setSelection(algorithmAdapter.getPosition(oldEntry.getAlgorithm())); if (oldType == Entry.OTPType.TOTP || oldType == Entry.OTPType.STEAM) { periodInput.setText(Integer.toString(oldEntry.getPeriod())); } else if (oldType == Entry.OTPType.HOTP) { counterInput.setText(Long.toString(oldEntry.getCounter())); } for(String tag: oldEntry.getTags()) { tagsAdapter.setTagState(tag, true); } try { tagsCallable.call(); } catch (Exception e) { e.printStackTrace(); } secretInput.setVisibility(View.GONE); secretView.setVisibility(View.VISIBLE); // Little hack: match the color and background of the TextView to that of a disabled EditText secretInput.setEnabled(false); secretView.setBackground(secretInput.getBackground()); secretView.setTextColor(secretInput.getTextColors().getColorForState(secretInput.getDrawableState(), R.color.colorPrimary)); typeInput.setEnabled(false); digitsInput.setEnabled(false); algorithmInput.setEnabled(false); periodInput.setEnabled(false); counterInput.setEnabled(false); } } }
package quotebook.theoneandonly.com.thequotebook; import android.graphics.Color; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; import java.util.Random; public class QuoteAdapter extends RecyclerView.Adapter<QuoteAdapter.QuoteViewHolder> { private List<Quote> quoteList; public QuoteAdapter(List<Quote> quoteList) { this.quoteList = quoteList; } @Override public int getItemCount() { return quoteList.size(); } // Create new views (invoked by the layout manager) @Override public QuoteAdapter.QuoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.card_layout, parent, false); QuoteViewHolder vh = new QuoteViewHolder(v); return vh; } @Override public void onBindViewHolder(QuoteViewHolder quoteViewHolder, int i) { Quote q = quoteList.get(i); Log.d("QUOTE", "onBindViewHolder: " + q.quote + " " + q.person); quoteViewHolder.vQuote.setText(q.quote); quoteViewHolder.vPerson.setText(q.person); } public static class QuoteViewHolder extends RecyclerView.ViewHolder { protected TextView vQuote; protected TextView vPerson; protected CardView vCard; public QuoteViewHolder(View v) { super(v); vQuote = (TextView) v.findViewById(R.id.quote); vPerson = (TextView) v.findViewById(R.id.person); vCard = (CardView) v.findViewById(R.id.card_view); Random rnd = new Random(); int r = rnd.nextInt(200); int g = rnd.nextInt(200); int b = rnd.nextInt(200); int randomColor = Color.rgb(r, g, b); vCard.setCardBackgroundColor(randomColor); } } }
package org.geomajas.internal.service; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.PostConstruct; import org.geomajas.geometry.Bbox; import org.geomajas.geometry.Crs; import org.geomajas.geometry.CrsTransform; import org.geomajas.global.CrsInfo; import org.geomajas.global.CrsTransformInfo; import org.geomajas.global.ExceptionCode; import org.geomajas.global.GeomajasException; import org.geomajas.internal.service.crs.CrsFactory; import org.geomajas.layer.LayerException; import org.geomajas.layer.feature.InternalFeature; import org.geomajas.service.GeoService; import org.geotools.geometry.jts.JTS; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.CRS; import org.opengis.geometry.MismatchedDimensionException; import org.opengis.referencing.FactoryException; import org.opengis.referencing.NoSuchAuthorityCodeException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.TransformException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.vividsolutions.jts.algorithm.InteriorPointArea; import com.vividsolutions.jts.algorithm.InteriorPointLine; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.LinearRing; import com.vividsolutions.jts.geom.MultiLineString; import com.vividsolutions.jts.geom.MultiPoint; import com.vividsolutions.jts.geom.MultiPolygon; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; /** * Collection of utility functions concerning geometries. * * @author Joachim Van der Auwera * @author Jan De Moerloose * @author Pieter De Graef */ @Component() public final class GeoServiceImpl implements GeoService { private final Logger log = LoggerFactory.getLogger(GeoServiceImpl.class); @Autowired(required = false) private Map<String, CrsInfo> crsDefinitions; @Autowired(required = false) private Map<String, CrsTransformInfo> crsTransformDefinitions; private Map<String, Crs> crsCache = new ConcurrentHashMap<String, Crs>(); private Map<String, CrsTransform> transformCache = new ConcurrentHashMap<String, CrsTransform>(); private static final Map<Class<? extends Geometry>, Geometry> EMPTY_GEOMETRIES = new HashMap<Class<? extends Geometry>, Geometry>(); @PostConstruct protected void postConstruct() throws GeomajasException { if (null != crsDefinitions) { for (CrsInfo crsInfo : crsDefinitions.values()) { try { CoordinateReferenceSystem crs = CRS.parseWKT(crsInfo.getCrsWkt()); String code = crsInfo.getKey(); crsCache.put(code, CrsFactory.getCrs(code, crs)); } catch (FactoryException e) { throw new GeomajasException(e, ExceptionCode.CRS_DECODE_FAILURE_FOR_MAP, crsInfo.getKey()); } } } if (null != crsTransformDefinitions) { for (CrsTransformInfo crsTransformInfo : crsTransformDefinitions.values()) { String key = getTransformKey(crsTransformInfo); transformCache.put(key, getCrsTransform(key, crsTransformInfo)); } } GeometryFactory factory = new GeometryFactory(); EMPTY_GEOMETRIES.put(Point.class, factory.createPoint((Coordinate) null)); EMPTY_GEOMETRIES.put(LineString.class, factory.createLineString((Coordinate[]) null)); EMPTY_GEOMETRIES.put(Polygon.class, factory.createPolygon(null, null)); EMPTY_GEOMETRIES.put(MultiPoint.class, factory.createMultiPoint((Coordinate[]) null)); EMPTY_GEOMETRIES.put(MultiLineString.class, factory.createMultiLineString((LineString[]) null)); // cast needed! EMPTY_GEOMETRIES.put(MultiPolygon.class, factory.createMultiPolygon((Polygon[]) null)); // cast needed! EMPTY_GEOMETRIES.put(Geometry.class, factory.createGeometryCollection(null)); } private String getTransformKey(CrsTransformInfo crsTransformInfo) { return crsTransformInfo.getSource() + "->" + crsTransformInfo.getTarget(); } private String getTransformKey(Crs source, Crs target) { return source.getId() + "->" + target.getId(); } private CrsTransform getCrsTransform(String key, CrsTransformInfo crsTransformInfo) throws GeomajasException { Crs source = getCrs2(crsTransformInfo.getSource()); Crs target = getCrs2(crsTransformInfo.getTarget()); MathTransform mathTransform = getBaseMathTransform(source, target); return new CrsTransformImpl(key, source, target, mathTransform, crsTransformInfo.getTransformableArea()); } private static Geometry createEmptyGeometryForClass(Class<? extends Geometry> geomClass) { Geometry empty = EMPTY_GEOMETRIES.get(geomClass); if (empty == null) { empty = EMPTY_GEOMETRIES.get(Geometry.class); } return empty; } public CoordinateReferenceSystem getCrs(String crs) throws LayerException { return getCrs2(crs); } /** @{inheritDoc} */ public Crs getCrs2(String crs) throws LayerException { try { Crs res = crsCache.get(crs); if (null == res) { res = CrsFactory.getCrs(crs, CRS.decode(crs)); crsCache.put(crs, res); } return res; } catch (NoSuchAuthorityCodeException e) { throw new LayerException(e, ExceptionCode.CRS_DECODE_FAILURE_FOR_MAP, crs); } catch (FactoryException e) { throw new LayerException(e, ExceptionCode.CRS_DECODE_FAILURE_FOR_MAP, crs); } } /** * Isn't there a method for this in GeoTools? * * @param crs * CRS string in the form of 'EPSG:<srid>'. * @return SRID as integer. */ public int getSridFromCrs(String crs) { int crsInt; if (crs.indexOf(':') != -1) { crsInt = Integer.parseInt(crs.substring(crs.indexOf(':') + 1)); } else { try { crsInt = Integer.parseInt(crs); } catch (NumberFormatException e) { crsInt = 0; } } return crsInt; } /** @{inheritDoc} */ public String getCodeFromCrs(Crs crs) { return crs.getId(); } /** @{inheritDoc} */ public String getCodeFromCrs(CoordinateReferenceSystem crs) { return "EPSG:" + getSridFromCrs(crs); } /** * Unreliable but works if srids are same as EPSG numbers. * * @param crs * reference system of EPSG type. * @return SRID as integer. */ public int getSridFromCrs(CoordinateReferenceSystem crs) { return getSridFromCrs(crs.getIdentifiers().iterator().next().toString()); } private MathTransform getBaseMathTransform(Crs sourceCrs, Crs targetCrs) throws GeomajasException { try { MathTransform transform; try { transform = CRS.findMathTransform(sourceCrs, targetCrs); } catch (Exception e) { transform = CRS.findMathTransform(sourceCrs, targetCrs, true); } return transform; } catch (FactoryException fe) { throw new GeomajasException(fe, ExceptionCode.CRS_TRANSFORMATION_NOT_POSSIBLE, sourceCrs.getId(), targetCrs.getId()); } } /** @{inheritDoc} */ public MathTransform findMathTransform(CoordinateReferenceSystem sourceCrs, CoordinateReferenceSystem targetCrs) throws GeomajasException { return getCrsTransform(getCrs2(getCodeFromCrs(sourceCrs)), getCrs2(getCodeFromCrs(targetCrs))); } /** @{inheritDoc} */ public CrsTransform getCrsTransform(String sourceCrs, String targetCrs) throws GeomajasException { return getCrsTransform(getCrs2(sourceCrs), getCrs2(targetCrs)); } /** @{inheritDoc} */ public CrsTransform getCrsTransform(CoordinateReferenceSystem sourceCrs, CoordinateReferenceSystem targetCrs) throws GeomajasException { Crs source, target; if (sourceCrs instanceof Crs) { source = (Crs) sourceCrs; } else { source = getCrs2(getCodeFromCrs(sourceCrs)); } if (targetCrs instanceof Crs) { target = (Crs) targetCrs; } else { target = getCrs2(getCodeFromCrs(targetCrs)); } return getCrsTransform(source, target); } /** @{inheritDoc} */ public CrsTransform getCrsTransform(Crs sourceCrs, Crs targetCrs) throws GeomajasException { String key = getTransformKey(sourceCrs, targetCrs); CrsTransform transform = transformCache.get(key); if (null == transform) { MathTransform mathTransform = getBaseMathTransform(sourceCrs, targetCrs); // as there was no transformable area configured, try to build it instead Envelope transformableArea = null; try { org.opengis.geometry.Envelope ogEnvelope = CRS.getEnvelope(targetCrs); if (null != ogEnvelope) { Envelope envelope = new Envelope(ogEnvelope.getLowerCorner().getCoordinate()[0], ogEnvelope .getUpperCorner().getCoordinate()[0], ogEnvelope.getLowerCorner().getCoordinate()[1], ogEnvelope.getUpperCorner().getCoordinate()[1]); log.info("CRS " + targetCrs.getId() + " envelope " + envelope); ReferencedEnvelope refEnvelope = new ReferencedEnvelope(envelope, targetCrs); transformableArea = refEnvelope.transform(sourceCrs, true); log.info("transformable area for " + key + " is " + transformableArea); } } catch (MismatchedDimensionException mde) { log.warn("Cannot build transformableArea for CRS transformation between " + sourceCrs.getId() + " and " + targetCrs.getId() + ", " + mde.getMessage()); } catch (TransformException te) { log.warn("Cannot build transformableArea for CRS transformation between " + sourceCrs.getId() + " and " + targetCrs.getId() + ", " + te.getMessage()); } catch (FactoryException fe) { log.warn("Cannot build transformableArea for CRS transformation between " + sourceCrs.getId() + " and " + targetCrs.getId() + ", " + fe.getMessage()); } transform = new CrsTransformImpl(key, sourceCrs, targetCrs, mathTransform, transformableArea); transformCache.put(key, transform); } return transform; } /** @{inheritDoc} */ @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "REC_CATCH_EXCEPTION") public Geometry transform(Geometry source, CrsTransform crsTransform) { try { if (crsTransform.isTransforming()) { Geometry transformableArea = crsTransform.getTransformableGeometry(); if (null != transformableArea) { source = source.intersection(transformableArea); } return JTS.transform(source, crsTransform); } else { return source; } } catch (Exception e) { // typically TopologyException, TransformException or FactoryException, but be safe log.warn("Problem during transformation " + crsTransform.getId() + "of " + source + ", maybe you need to configure the transformable area using a CrsTransformInfo object for this " + "transformation. Object replaced by empty Envelope.", e); return createEmptyGeometryForClass(source.getClass()); } } /** @{inheritDoc} */ public Geometry transform(Geometry geometry, Crs sourceCrs, Crs targetCrs) throws GeomajasException { if (sourceCrs == targetCrs) { // NOPMD // only works when the caching of the CRSs works return geometry; } CrsTransform crsTransform = getCrsTransform(sourceCrs, targetCrs); return transform(geometry, crsTransform); } /** @{inheritDoc} */ public Geometry transform(Geometry geometry, String sourceCrs, String targetCrs) throws GeomajasException { if (sourceCrs.equals(targetCrs)) { return geometry; } CrsTransform crsTransform = getCrsTransform(sourceCrs, targetCrs); return transform(geometry, crsTransform); } /** @{inheritDoc} */ public Geometry transform(Geometry geometry, CoordinateReferenceSystem sourceCrs, CoordinateReferenceSystem targetCrs) throws GeomajasException { if (sourceCrs == targetCrs) { // NOPMD // only works when the caching of the CRSs works return geometry; } Crs source, target; if (sourceCrs instanceof Crs) { source = (Crs) sourceCrs; } else { source = getCrs2(getCodeFromCrs(sourceCrs)); } if (targetCrs instanceof Crs) { target = (Crs) targetCrs; } else { target = getCrs2(getCodeFromCrs(targetCrs)); } CrsTransform crsTransform = getCrsTransform(source, target); return transform(geometry, crsTransform); } /** @{inheritDoc} */ @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "REC_CATCH_EXCEPTION") public Bbox transform(Bbox source, CrsTransform crsTransform) { try { if (crsTransform.isTransforming()) { Envelope envelope = new Envelope(source.getX(), source.getMaxX(), source.getY(), source.getMaxY()); Envelope transformableArea = crsTransform.getTransformableEnvelope(); if (null != transformableArea) { envelope = envelope.intersection(transformableArea); } if (envelope.isNull()) { return new Bbox(); } else { ReferencedEnvelope refEnvelope = new ReferencedEnvelope(envelope, crsTransform.getSource()); envelope = refEnvelope.transform(crsTransform.getTarget(), true); return new Bbox(envelope.getMinX(), envelope.getMinY(), envelope.getWidth(), envelope.getHeight()); } } else { return source; } } catch (Exception e) { // typically TopologyException, TransformException or FactoryException, but be safe log.warn("Problem during transformation " + crsTransform.getId() + "of " + source + ", maybe you need to configure the transformable area using a CrsTransformInfo object for this " + "transformation. Object replaced by empty Bbox.", e); return new Bbox(); } } /** @{inheritDoc} */ public Bbox transform(Bbox bbox, Crs sourceCrs, Crs targetCrs) throws GeomajasException { if (sourceCrs == targetCrs) { // NOPMD // only works when the caching of the CRSs works return bbox; } CrsTransform crsTransform = getCrsTransform(sourceCrs, targetCrs); return transform(bbox, crsTransform); } /** @{inheritDoc} */ public Bbox transform(Bbox bbox, String sourceCrs, String targetCrs) throws GeomajasException { if (sourceCrs.equals(targetCrs)) { // only works when the caching of the CRSs works return bbox; } CrsTransform crsTransform = getCrsTransform(sourceCrs, targetCrs); return transform(bbox, crsTransform); } /** @{inheritDoc} */ @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "REC_CATCH_EXCEPTION") public Envelope transform(Envelope source, CrsTransform crsTransform) { try { if (crsTransform.isTransforming()) { Envelope transformableArea = crsTransform.getTransformableEnvelope(); if (null != transformableArea) { source = source.intersection(transformableArea); } if (source.isNull()) { return source; } else { ReferencedEnvelope refEnvelope = new ReferencedEnvelope(source, crsTransform.getSource()); return refEnvelope.transform(crsTransform.getTarget(), true); } } else { return source; } } catch (Exception e) { // typically TopologyException, TransformException or FactoryException, but be safe log.warn("Problem during transformation " + crsTransform.getId() + "of " + source + ", maybe you need to configure the transformable area using a CrsTransformInfo object for this " + "transformation. Object replaced by empty Envelope.", e); return new Envelope(); } } /** @{inheritDoc} */ public Envelope transform(Envelope source, Crs sourceCrs, Crs targetCrs) throws GeomajasException { if (sourceCrs == targetCrs) { // NOPMD // only works when the caching of the CRSs works return source; } CrsTransform crsTransform = getCrsTransform(sourceCrs, targetCrs); return transform(source, crsTransform); } /** @{inheritDoc} */ public Envelope transform(Envelope source, String sourceCrs, String targetCrs) throws GeomajasException { if (sourceCrs.equals(targetCrs)) { // only works when the caching of the CRSs works return source; } CrsTransform crsTransform = getCrsTransform(sourceCrs, targetCrs); return transform(source, crsTransform); } /** @{inheritDoc} */ public Coordinate transform(Coordinate source, CrsTransform crsTransform) { try { if (crsTransform.isTransforming()) { Envelope transformableArea = crsTransform.getTransformableEnvelope(); if (null == transformableArea || transformableArea.contains(source)) { return JTS.transform(source, new Coordinate(), crsTransform); } return null; } else { return source; } } catch (Exception e) { // typically TopologyException, TransformException or FactoryException, but be safe log.warn("Problem during transformation " + crsTransform.getId() + "of " + source + ", maybe you need to configure the transformable area using a CrsTransformInfo object for this " + "transformation. Object replaced by empty Envelope.", e); return null; } } /** @{inheritDoc} */ public Coordinate transform(Coordinate source, Crs sourceCrs, Crs targetCrs) throws GeomajasException { if (sourceCrs == targetCrs) { // NOPMD // only works when the caching of the CRSs works return source; } CrsTransform crsTransform = getCrsTransform(sourceCrs, targetCrs); return transform(source, crsTransform); } /** @{inheritDoc} */ public Coordinate transform(Coordinate source, String sourceCrs, String targetCrs) throws GeomajasException { if (sourceCrs.equals(targetCrs)) { // only works when the caching of the CRSs works return source; } CrsTransform crsTransform = getCrsTransform(sourceCrs, targetCrs); return transform(source, crsTransform); } /** @{inheritDoc} */ public Coordinate calcDefaultLabelPosition(InternalFeature feature) { Geometry geometry = feature.getGeometry(); Coordinate labelPoint = null; if (geometry != null && !geometry.isEmpty() && geometry.isValid()) { if (geometry instanceof Polygon || geometry instanceof MultiPolygon) { try { InteriorPointArea ipa = new InteriorPointArea(geometry); labelPoint = ipa.getInteriorPoint(); } catch (Throwable t) { // NOPMD // BUG in JTS for some valid geometries ? fall back to centroid log.warn("getInteriorPoint() failed", t); } } else if (geometry instanceof LineString || geometry instanceof MultiLineString) { InteriorPointLine ipa = new InteriorPointLine(geometry); labelPoint = ipa.getInteriorPoint(); } else { labelPoint = geometry.getCentroid().getCoordinate(); } } if (null == labelPoint && null != geometry) { Point centroid = geometry.getCentroid(); if (null != centroid) { labelPoint = centroid.getCoordinate(); } } if (null != labelPoint && (Double.isNaN(labelPoint.x) || Double.isNaN(labelPoint.y))) { labelPoint = new Coordinate(geometry.getCoordinate()); } return null == labelPoint ? null : new Coordinate(labelPoint); } /** @{inheritDoc} */ public Geometry createCircle(final Point point, final double radius, final int nrPoints) { double x = point.getX(); double y = point.getY(); Coordinate[] coords = new Coordinate[nrPoints + 1]; for (int i = 0; i < nrPoints; i++) { double angle = ((double) i / (double) nrPoints) * Math.PI * 2.0; double dx = Math.cos(angle) * radius; double dy = Math.sin(angle) * radius; coords[i] = new Coordinate(x + dx, y + dy); } coords[nrPoints] = coords[0]; LinearRing ring = point.getFactory().createLinearRing(coords); return point.getFactory().createPolygon(ring, null); } }
package com.nhl.bootique.cayenne; import com.nhl.bootique.jdbc.JdbcModule; import com.nhl.bootique.test.junit.BQTestFactory; import org.apache.cayenne.access.DataDomain; import org.apache.cayenne.configuration.server.ServerRuntime; import org.apache.cayenne.query.SQLSelect; import org.junit.Rule; import org.junit.Test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class CayenneModuleIT { @Rule public BQTestFactory testFactory = new BQTestFactory(); @Test public void testFullConfig() { ServerRuntime runtime = testFactory.newRuntime() .configurator(bootique -> bootique.modules(JdbcModule.class, CayenneModule.class)) .build("--config=classpath:fullconfig.yml") .getRuntime() .getInstance(ServerRuntime.class); DataDomain domain = runtime.getDataDomain(); assertNotNull(domain.getEntityResolver().getDbEntity("db_entity2")); // trigger a DB op SQLSelect.dataRowQuery("SELECT * FROM db_entity2").select(runtime.newContext()); } @Test public void testNoConfig() { ServerRuntime runtime = testFactory.newRuntime() .configurator(bootique -> bootique.modules(JdbcModule.class, CayenneModule.class)) .build("--config=classpath:noconfig.yml") .getRuntime() .getInstance(ServerRuntime.class); DataDomain domain = runtime.getDataDomain(); assertTrue(domain.getEntityResolver().getDbEntities().isEmpty()); } }
package net.mm2d.android.net; import android.content.Context; import android.os.Build; import android.support.annotation.NonNull; import java.net.NetworkInterface; import java.util.Collection; /** * LAN * * @author <a href="mailto:ryo@mm2d.net"> (OHMAE Ryosuke)</a> */ public abstract class Lan { /** * * * @param context * @return */ @NonNull public static Lan createInstance(Context context) { return isEmulator() ? new EmulatorLan() : new AndroidLan(context); } /** * * * @return true:false: */ private static boolean isEmulator() { return Build.UNKNOWN.equals(Build.BOOTLOADER) && Build.MODEL.contains("Android SDK"); } /** * LAN * * @return true:false: */ public abstract boolean hasAvailableInterface(); /** * LAN * * @return LAN */ @NonNull public abstract Collection<NetworkInterface> getAvailableInterfaces(); }
package jodd.joy.core; import jodd.db.DbDefault; import jodd.db.DbSessionProvider; import jodd.db.connection.ConnectionProvider; import jodd.db.orm.DbOrmManager; import jodd.db.orm.config.AutomagicDbOrmConfigurator; import jodd.db.pool.CoreConnectionPool; import jodd.joy.AppUtil; import jodd.joy.petite.ProxettaAwarePetiteContainer; import jodd.jtx.JtxTransactionManager; import jodd.jtx.db.DbJtxSessionProvider; import jodd.jtx.db.DbJtxTransactionManager; import jodd.jtx.meta.Transaction; import jodd.jtx.proxy.AnnotationTxAdvice; import jodd.jtx.proxy.AnnotationTxAdviceManager; import jodd.jtx.proxy.AnnotationTxAdviceSupport; import jodd.petite.PetiteContainer; import jodd.petite.config.AutomagicPetiteConfigurator; import jodd.petite.scope.SessionScope; import jodd.petite.scope.SingletonScope; import jodd.props.Props; import jodd.props.PropsUtil; import jodd.proxetta.MethodInfo; import jodd.proxetta.Proxetta; import jodd.proxetta.ProxyAspect; import jodd.proxetta.pointcuts.MethodAnnotationPointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static jodd.joy.AppUtil.prepareAppLogDir; import static jodd.joy.AppUtil.resolveAppDirs; /** * Default application core frame. */ public abstract class DefaultAppCore { /** * Petite bean names. */ public static final String PETITE_APPCORE = "app"; // AppCore public static final String PETITE_DBPOOL = "dbpool"; // database pool public static final String PETITE_DBORM = "dbOrm"; // DbOrm instance public static final String PETITE_APPINIT = "appInit"; // init bean /** * Logger. */ protected static Logger log; /** * Default scanning path that will be examined by various * Jodd auto-magic tools. */ protected final String[] scanningPath; /** * Default constructor. */ protected DefaultAppCore() { scanningPath = resolveScanningPath(); } /** * Defines the scanning path for Jodd frameworks. * Scanning path will contain all classes inside and bellow * the app core packages and 'jodd' packages. */ protected String[] resolveScanningPath() { return new String[] {this.getClass().getPackage().getName() + ".*", "jodd.*"}; } /** * Returns <code>true</code> if application is started as a part of web application. */ public boolean isWebApplication() { return AppUtil.isWebApplication(); } /** * Starts the application and performs all initialization. */ public synchronized void start() { resolveAppDirs("app.props"); // app directories are resolved from location of 'app.props'. prepareAppLogDir("log"); // creates log folder, depending of application type initLogger(); // logger becomes available after this point log.info("app dir: {}", AppUtil.getAppDir()); log.info("log dir: {}", AppUtil.getLogDir()); log.info("classpath: {}", AppUtil.getClasspathDir()); try { initTypes(); initProxetta(); initPetite(); initDb(); initApp(); log.info("app started"); } catch (RuntimeException rex) { log.error(rex.toString(), rex); try { stop(); } catch (Exception ignore) { } throw rex; } } /** * Stops the application. */ public synchronized void stop() { log.info("shutting down..."); stopApp(); stopDb(); log.info("app stopped"); } /** * Initializes the logger. It must be initialized after the * log path is defined. */ protected void initLogger() { log = LoggerFactory.getLogger(DefaultAppCore.class); } protected Proxetta proxetta; /** * Returns proxetta. */ public Proxetta getProxetta() { return proxetta; } /** * Creates Proxetta with all aspects. The following aspects are created: * * <li>Transaction proxy - applied on all classes that contains public top-level methods * annotated with <code>@Transaction</code> annotation. This is just one way how proxies * can be applied - since base configuration is in Java, everything is possible. */ protected void initProxetta() { log.info("proxetta initialization"); proxetta = Proxetta.withAspects(createAppAspects()).loadsWith(this.getClass().getClassLoader()); } /** * Creates all application aspects. By default it creates just * {@link #createTxProxyAspects() transactional aspect}. */ protected ProxyAspect[] createAppAspects() { return new ProxyAspect[] {createTxProxyAspects()}; } /** * Creates TX aspect that will be applied on all classes * having at least one public top-level method annotated * with <code>@Transaction</code>. */ protected ProxyAspect createTxProxyAspects() { return new ProxyAspect(AnnotationTxAdvice.class, new MethodAnnotationPointcut(Transaction.class) { @Override public boolean apply(MethodInfo methodInfo) { return isPublic(methodInfo) && isTopLevelMethod(methodInfo) && super.apply(methodInfo); } }); } protected PetiteContainer petite; /** * Returns application container (Petite). */ public PetiteContainer getPetite() { return petite; } /** * Creates and initializes Petite container. * It will be auto-magically configured by scanning the classpath. * Also, all 'app*.prop*' will be loaded and values will * be injected in the matched beans. At the end it registers * this instance of core into the container. */ protected void initPetite() { log.info("petite initialization"); petite = createPetiteContainer(); boolean isWebApplication = AppUtil.isWebApplication(); log.info("app in web: {}", Boolean.valueOf(isWebApplication)); if (isWebApplication == false) { // make session scope to act as singleton scope // if this is not a web application (and http session is not available). petite.getManager().registerScope(SessionScope.class, new SingletonScope()); } // automagic configuration AutomagicPetiteConfigurator pcfg = new AutomagicPetiteConfigurator(); pcfg.setIncludedEntries(scanningPath); pcfg.configure(petite); // load parameters from properties files Props appProps = PropsUtil.createFromClasspath("/app*.prop*"); petite.defineParameters(appProps); // add AppCore instance to Petite petite.addBean(PETITE_APPCORE, this); } /** * Creates Petite container. By default, it creates * {@link jodd.joy.petite.ProxettaAwarePetiteContainer proxetta aware petite container}. */ protected PetiteContainer createPetiteContainer() { return new ProxettaAwarePetiteContainer(proxetta); } /** * Database debug mode will print out sql statements. */ protected boolean debugMode; /** * Returns <code>true</code> if debug mode is on. */ public boolean isDebugMode() { return debugMode; } /** * JTX manager. */ protected JtxTransactionManager jtxManager; /** * Returns JTX transaction manager. */ public JtxTransactionManager getJtxManager() { return jtxManager; } /** * Database connection provider. */ protected ConnectionProvider connectionProvider; /** * Returns connection provider. */ public ConnectionProvider getConnectionProvider() { return connectionProvider; } /** * Initializes database. First, creates connection pool. * and transaction manager. Then, Jodds DbOrmManager is * configured. It is also configured automagically, by scanning * the class path for entities. */ protected void initDb() { log.info("database initialization"); // connection pool petite.registerBean(PETITE_DBPOOL, CoreConnectionPool.class); connectionProvider = (ConnectionProvider) petite.getBean(PETITE_DBPOOL); connectionProvider.init(); // transactions manager jtxManager = createJtxTransactionManager(connectionProvider); jtxManager.setValidateExistingTransaction(true); AnnotationTxAdviceSupport.manager = new AnnotationTxAdviceManager(jtxManager, "$class"); DbSessionProvider sessionProvider = new DbJtxSessionProvider(jtxManager); // global settings DbDefault.debug = debugMode; DbDefault.connectionProvider = connectionProvider; DbDefault.sessionProvider = sessionProvider; DbOrmManager dbOrmManager = createDbOrmManager(); DbOrmManager.setInstance(dbOrmManager); petite.addBean(PETITE_DBORM, dbOrmManager); // automatic configuration AutomagicDbOrmConfigurator dbcfg = new AutomagicDbOrmConfigurator(); dbcfg.setIncludedEntries(scanningPath); dbcfg.configure(dbOrmManager); } /** * Creates JTX transaction manager. */ protected JtxTransactionManager createJtxTransactionManager(ConnectionProvider connectionProvider) { return new DbJtxTransactionManager(connectionProvider); } /** * Creates DbOrmManager. */ protected DbOrmManager createDbOrmManager() { return DbOrmManager.getInstance(); } /** * Closes database resources at the end. */ protected void stopDb() { log.info("database shutdown"); jtxManager.close(); connectionProvider.close(); } protected AppInit appInit; /** * Initializes business part of the application. * Simply delegates to {@link AppInit#init()}. */ protected void initApp() { appInit = (AppInit) petite.getBean(PETITE_APPINIT); if (appInit != null) { appInit.init(); } } /** * Stops business part of the application. * Simply delegates to {@link AppInit#stop()}. */ protected void stopApp() { if (appInit != null) { appInit.stop(); } } /** * Initializes types for beanutil and db conversions and other usages. */ protected void initTypes() { } }
package dr.geo; import dr.geo.cartogram.CartogramMapping; import dr.xml.*; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.File; import java.io.IOException; import java.util.*; /** * @author Marc A. Suchard * @author Philippe Lemey */ public class Polygon2D { public static final String POLYGON = "polygon"; public static final String CLOSED = "closed"; public static final String FILL_VALUE = "fillValue"; public Polygon2D(LinkedList<Point2D> points, boolean closed) { this.point2Ds = points; if (!closed) { Point2D start = points.get(0); points.add(start); } convertPointsToArrays(); length = points.size() - 1; } public Polygon2D() { length = 0; point2Ds = new LinkedList<Point2D>(); } public String getID() { return id; } public Polygon2D(Element e) { List<Element> children = e.getChildren(); id = e.getAttributeValue(XMLParser.ID); for(Element childElement : children) { if (childElement.getName().equals(KMLCoordinates.COORDINATES)) { String value = childElement.getTextTrim(); StringTokenizer st1 = new StringTokenizer(value, "\n"); int count = st1.countTokens(); //System.out.println(count); point2Ds = new LinkedList<Point2D>(); for (int i = 0; i < count; i++) { String line = st1.nextToken(); StringTokenizer st2 = new StringTokenizer(line, ","); if (st2.countTokens() != 3) throw new IllegalArgumentException("All KML coordinates must contain (X,Y,Z) values. Three dimensions not found in element '" + line + "'"); final double x = Double.valueOf(st2.nextToken()); final double y = Double.valueOf(st2.nextToken()); point2Ds.add(new Point2D.Double(x, y)); } convertPointsToArrays(); length = point2Ds.size() - 1; break; } } } private void convertPointsToArrays() { final int length = point2Ds.size(); if (x == null || x.length != length) { x = new double[length]; y = new double[length]; } Iterator<Point2D> it = point2Ds.iterator(); for(int i=0; i<length; i++) { final Point2D point = it.next(); x[i] = point.getX(); y[i] = point.getY(); } } public void addPoint2D(Point2D Point2D) { if (point2Ds.size() == 0) point2Ds.add(Point2D); else if (point2Ds.size() == 1) { point2Ds.add(Point2D); point2Ds.add(point2Ds.get(0)); } else { Point2D last = point2Ds.removeLast(); point2Ds.add(Point2D); if(!last.equals(Point2D)) point2Ds.add(last); } convertPointsToArrays(); length = point2Ds.size() - 1; } public boolean containsPoint2D(Point2D Point2D) { final double inX = Point2D.getX(); final double inY = Point2D.getY(); boolean contains = false; // Take a horizontal ray from (inX,inY) to the right. // If ray across the polygon edges an odd # of times, the point is inside. for (int i = 0, j = length - 1; i < length; j = i++) { if ((((y[i] <= inY) && (inY < y[j])) || ((y[j] <= inY) && (inY < y[i]))) && (inX < (x[j] - x[i]) * (inY - y[i]) / (y[j] - y[i]) + x[i])) contains = !contains; } return contains; } public void setFillValue(double value) { fillValue = value; } public double getFillValue() { return fillValue; } // public boolean containsPoint2D(Point2D Point2D) { // this takes 3 times as long as the above code, why??? // final double inX = Point2D.getX(); // final double inY = Point2D.getY(); // boolean contains = false; // // Take a horizontal ray from (inX,inY) to the right. // // If ray across the polygon edges an odd # of times, the Point2D is inside. // final Point2D end = point2Ds.get(length-1); // assumes closed // double xi = end.getX(); // double yi = end.getY(); // Iterator<Point2D> listIterator = point2Ds.iterator(); // for(int i=0; i<length; i++) { // final double xj = xi; // final double yj = yi; // final Point2D next = listIterator.next(); // xi = next.getX(); // yi = next.getY(); // if ((((yi <= inY) && (inY < yj)) || // ((yj <= inY) && (inY < yi))) && // (inX < (xj - xi) * (inY - yi) / (yj - yi) + xi)) // contains = !contains; // return contains; private enum Side { left, right, top, bottom } public Polygon2D clip(Rectangle2D boundingBox) { LinkedList<Point2D> clippedPolygon = new LinkedList<Point2D>(); Point2D p; // current Point2D Point2D p2; // next Point2D // make copy of original polygon to work with LinkedList<Point2D> workPoly = new LinkedList<Point2D>(point2Ds); // loop through all for clipping edges for (Side side : Side.values()) { clippedPolygon.clear(); for (int i = 0; i < workPoly.size() - 1; i++) { p = workPoly.get(i); p2 = workPoly.get(i + 1); if (isInsideClip(p, side, boundingBox)) { if (isInsideClip(p2, side, boundingBox)) // here both point2Ds are inside the clipping window so add the second one clippedPolygon.add(p2); else // the seond Point2D is outside so add the intersection Point2D clippedPolygon.add(intersectionPoint2D(side, p, p2, boundingBox)); } else { // so first Point2D is outside the window here if (isInsideClip(p2, side, boundingBox)) { // the following Point2D is inside so add the insection Point2D and also p2 clippedPolygon.add(intersectionPoint2D(side, p, p2, boundingBox)); clippedPolygon.add(p2); } } } // make sure that first and last element are the same, we want a closed polygon if (!clippedPolygon.getFirst().equals(clippedPolygon.getLast())) clippedPolygon.add(clippedPolygon.getFirst()); // we have to keep on working with our new clipped polygon workPoly = new LinkedList<Point2D>(clippedPolygon); } return new Polygon2D(clippedPolygon,true); } public void transformByMapping(CartogramMapping mapping){ for (int i = 0; i < length +1; i++) { point2Ds.set(i, mapping.map(point2Ds.get(i))); } convertPointsToArrays(); } public void swapXYs(){ for (int i = 0; i < length +1; i++) { point2Ds.set(i, new Point2D.Double(point2Ds.get(i).getY(), point2Ds.get(i).getX())); } convertPointsToArrays(); } public void rescale(double longMin, double longwidth, double gridXSize, double latMax, double latwidth, double gridYSize){ for (int i = 0; i < length +1; i++) { point2Ds.set(i, new Point2D.Double(((point2Ds.get(i).getX()-longMin)*(gridXSize/longwidth)),((latMax- point2Ds.get(i).getY())*(gridYSize/latwidth)))); } convertPointsToArrays(); } // Here is a formula for the area of a polygon with vertices {(xk,yk): k = 1,...,n}: // Area = 1/2 [(x1*y2 - x2*y1) + (x2*y3 - x3*y2) + ... + (xn*y1 - x1*yn)]. // This formula appears in an Article by Gil Strang of MIT // on p. 253 of the March 1993 issue of The American Mathematical Monthly, with the note that it is // "known, but not well known". There is also a very brief discussion of proofs and other references, // including an article by Bart Braden of Northern Kentucky U., a known Mathematica enthusiast. public double calculateArea(){ double area = 0; //we can implement it like this because the polygon is closed (point2D.get(0) = point2D.get(length + 1) for (int i = 0; i < length + 1; i++) { area += (x[i]*y[i+1] - x[i+1]*y[i]); } return (area/2); } private static boolean isInsideClip(Point2D p, Side side, Rectangle2D boundingBox) { if (side == Side.top) return (p.getY() <= boundingBox.getMaxY()); else if (side == Side.bottom) return (p.getY() >= boundingBox.getMinY()); else if (side == Side.left) return (p.getX() >= boundingBox.getMinX()); else if (side == Side.right) return (p.getX() <= boundingBox.getMaxX()); else throw new RuntimeException("Error in Polygon"); } private static Point2D intersectionPoint2D(Side side, Point2D p1, Point2D p2, Rectangle2D boundingBox) { if (side == Side.top) { final double topEdge = boundingBox.getMaxY(); return new Point2D.Double(p1.getX() + (topEdge - p1.getY()) * (p2.getX() - p1.getX()) / (p2.getY() - p1.getY()), topEdge); } else if (side == Side.bottom) { final double bottomEdge = boundingBox.getMinY(); return new Point2D.Double(p1.getX() + (bottomEdge - p1.getY()) * (p2.getX() - p1.getX()) / (p2.getY() - p1.getY()), bottomEdge); } else if (side == Side.right) { final double rightEdge = boundingBox.getMaxX(); return new Point2D.Double(rightEdge, p1.getY() + (rightEdge - p1.getX()) * (p2.getY() - p1.getY()) / (p2.getX() - p1.getX())); } else if (side == Side.left) { final double leftEdge = boundingBox.getMinX(); return new Point2D.Double(leftEdge, p1.getY() + (leftEdge - p1.getX()) * (p2.getY() - p1.getY()) / (p2.getX() - p1.getX())); } return null; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("polygon[\n"); for(Point2D pt : point2Ds) { sb.append("\t"); sb.append(pt); sb.append("\n"); } sb.append("]"); return sb.toString(); } public static List<Polygon2D> readKMLFile(String fileName) { List<Polygon2D> polygons = new ArrayList<Polygon2D>(); try { SAXBuilder builder = new SAXBuilder(); builder.setValidation(false); builder.setIgnoringElementContentWhitespace(true); Document doc = builder.build(new File(fileName)); Element root = doc.getRootElement(); if (!root.getName().equalsIgnoreCase("KML")) throw new RuntimeException("Not a KML file"); List<Element> children = root.getChildren(); for(Element e : children) { if (e.getName().equalsIgnoreCase("polygon")) { Polygon2D polygon = new Polygon2D(e); polygons.add(polygon); } } } catch (IOException e) { e.printStackTrace(); } catch (JDOMException e) { e.printStackTrace(); } return polygons; } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return POLYGON; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { KMLCoordinates coordinates = (KMLCoordinates) xo.getChild(KMLCoordinates.class); boolean closed = xo.getAttribute(CLOSED, false); if ((!closed && coordinates.length < 3) || (closed && coordinates.length < 4)) throw new XMLParseException("Insufficient point2Ds in polygon '" + xo.getId() + "' to define a polygon in 2D"); LinkedList<Point2D> Point2Ds = new LinkedList<Point2D>(); for (int i = 0; i < coordinates.length; i++) Point2Ds.add(new Point2D.Double(coordinates.x[i], coordinates.y[i])); Polygon2D polygon = new Polygon2D(Point2Ds, closed); polygon.setFillValue(xo.getAttribute(FILL_VALUE, 0.0)); return polygon; }
package Datos; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; /** * * @author Anahi */ public class Pagos { private int id_pago; private int numero_pago; private String tipo; private String forma; private int cant_cuotas; private float monto; private int anio; private int id_socio; /** * @return the id_pago */ public int getId_pago() { return id_pago; } /** * @return the numero_pago */ public int getNumero_pago() { return numero_pago; } /** * @param numero_pago the numero_pago to set */ public void setNumero_pago(int numero_pago) { this.numero_pago = numero_pago; } /** * @return the tipo */ public String getTipo() { return tipo; } /** * @param tipo the tipo to set */ public void setTipo(String tipo) { this.tipo = tipo; } /** * @return the forma */ public String getForma() { return forma; } /** * @param forma the forma to set */ public void setForma(String forma) { this.forma = forma; } /** * @return the cant_cuotas */ public int getCant_cuotas() { return cant_cuotas; } /** * @param cant_cuotas the cant_cuotas to set */ public void setCant_cuotas(int cant_cuotas) { this.cant_cuotas = cant_cuotas; } /** * @return the monto */ public float getMonto() { return monto; } /** * @param monto the monto to set */ public void setMonto(float monto) { this.monto = monto; } /** * @return the anio */ public int getAnio() { return anio; } /** * @param anio the anio to set */ public void setAnio(int anio) { this.anio = anio; } /** * @return the id_socio */ public int getId_socio() { return id_socio; } /** * @param id_socio the id_socio to set */ public void setId_socio(int id_socio) { this.id_socio = id_socio; } public Pagos buscarUltimoPago(int id_socio){ Pagos ultimoPago = new Pagos(); try { Connection cn = Conexion.Cadena(); String SQL = "SELECT * FROM pago"+ " WHERE id_socio ='"+id_socio+"' "; System.out.println(SQL); Statement sentencia = cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rsDatos = sentencia.executeQuery(SQL); System.out.println("Correcto"); int num_pago; if (rsDatos.last()) { num_pago=rsDatos.getInt("numero_pago"); System.out.println( num_pago); } } catch (Exception e) { } return ultimoPago; } }
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class GameEngine extends JPanel implements MouseListener, ActionListener, MouseMotionListener, KeyListener { Tile currentlySelected = null; // row 1 Tile tile0 = new Tile(0); Tile tile1 = new Tile(1); Tile tile2 = new Tile(0); Tile tile3 = new Tile(1); Tile tile4 = new Tile(0); Tile tile5 = new Tile(1); Tile tile6 = new Tile(0); Tile tile7 = new Tile(1); // row 2 Tile tile8 = new Tile(1); Tile tile9 = new Tile(0); Tile tile10 = new Tile(1); Tile tile11 = new Tile(0); Tile tile12 = new Tile(1); Tile tile13 = new Tile(0); Tile tile14 = new Tile(1); Tile tile15 = new Tile(0); // row 3 Tile tile16 = new Tile(0); Tile tile17 = new Tile(1); Tile tile18 = new Tile(0); Tile tile19 = new Tile(1); Tile tile20 = new Tile(0); Tile tile21 = new Tile(1); Tile tile22 = new Tile(0); Tile tile23 = new Tile(1); // row 4 Tile tile24 = new Tile(0); Tile tile25 = new Tile(0); Tile tile26 = new Tile(0); Tile tile27 = new Tile(0); Tile tile28 = new Tile(0); Tile tile29 = new Tile(0); Tile tile30 = new Tile(0); Tile tile31 = new Tile(0); // row 5 Tile tile32 = new Tile(0); Tile tile33 = new Tile(0); Tile tile34 = new Tile(0); Tile tile35 = new Tile(0); Tile tile36 = new Tile(0); Tile tile37 = new Tile(0); Tile tile38 = new Tile(0); Tile tile39 = new Tile(0); // row 6 Tile tile40 = new Tile(2); Tile tile41 = new Tile(0); Tile tile42 = new Tile(2); Tile tile43 = new Tile(0); Tile tile44 = new Tile(2); Tile tile45 = new Tile(0); Tile tile46 = new Tile(2); Tile tile47 = new Tile(0); // row 7 Tile tile48 = new Tile(0); Tile tile49 = new Tile(2); Tile tile50 = new Tile(0); Tile tile51 = new Tile(2); Tile tile52 = new Tile(0); Tile tile53 = new Tile(2); Tile tile54 = new Tile(0); Tile tile55 = new Tile(2); // row 8 Tile tile56 = new Tile(2); Tile tile57 = new Tile(0); Tile tile58 = new Tile(2); Tile tile59 = new Tile(0); Tile tile60 = new Tile(2); Tile tile61 = new Tile(0); Tile tile62 = new Tile(2); Tile tile63 = new Tile(0); Timer timer = new Timer(16, this); public GameEngine() { timer.start(); setFocusable(true); //allows keyboard input addKeyListener(this); addMouseListener(this); } private void paintChessBoard(Graphics g) { g.setColor(Color.white); g.fillRect(0, 0, 600, 600); g.setColor(Color.black); int i = 75; g.fillRect(i, 0, 75, 75); g.fillRect(i * 3, 0, 75, 75); g.fillRect(i * 5, 0, 75, 75); g.fillRect(i * 7, 0, 75, 75); g.fillRect(i, 75 * 2, 75, 75); g.fillRect(i * 3, 75 * 2, 75, 75); g.fillRect(i * 5, 75 * 2, 75, 75); g.fillRect(i * 7, 75 * 2, 75, 75); g.fillRect(i, 75 * 4, 75, 75); g.fillRect(i * 3, 75 * 4, 75, 75); g.fillRect(i * 5, 75 * 4, 75, 75); g.fillRect(i * 7, 75 * 4, 75, 75); g.fillRect(i, 75 * 6, 75, 75); g.fillRect(i * 3, 75 * 6, 75, 75); g.fillRect(i * 5, 75 * 6, 75, 75); g.fillRect(i * 7, 75 * 6, 75, 75); g.fillRect(0, 75, 75, 75); g.fillRect(75 * 2, 75, 75, 75); g.fillRect(75 * 4, 75, 75, 75); g.fillRect(75 * 6, 75, 75, 75); g.fillRect(0, 75 * 3, 75, 75); g.fillRect(75 * 2, 75 * 3, 75, 75); g.fillRect(75 * 4, 75 * 3, 75, 75); g.fillRect(75 * 6, 75 * 3, 75, 75); g.fillRect(0, 75 * 5, 75, 75); g.fillRect(75 * 2, 75 * 5, 75, 75); g.fillRect(75 * 4, 75 * 5, 75, 75); g.fillRect(75 * 6, 75 * 5, 75, 75); g.fillRect(0, 75 * 5, 75, 75); g.fillRect(75 * 2, 75 * 5, 75, 75); g.fillRect(75 * 4, 75 * 5, 75, 75); g.fillRect(75 * 6, 75 * 5, 75, 75); g.fillRect(0, 75 * 5, 75, 75); g.fillRect(75 * 2, 75 * 5, 75, 75); g.fillRect(75 * 4, 75 * 5, 75, 75); g.fillRect(75 * 6, 75 * 5, 75, 75); g.fillRect(0, 75 * 7, 75, 75); g.fillRect(75 * 2, 75 * 7, 75, 75); g.fillRect(75 * 4, 75 * 7, 75, 75); g.fillRect(75 * 6, 75 * 7, 75, 75); } int i = 0; public void paintComponent(Graphics g) { super.paintComponent(g); paintChessBoard(g); //Paints the background chess board. paintCurrentlySelectedBorder(g); paintPieces(g); } private void paintPieces(Graphics g) { // row 1 - blue if (tile0.tileID == 1) { g.setColor(Color.blue); g.fillOval(10, 10, 50, 50); } if (tile1.tileID == 1) { g.setColor(Color.blue); g.fillOval(85, 10, 50, 50); } if (tile2.tileID == 1) { g.setColor(Color.blue); g.fillOval(160, 10, 50, 50); } if (tile3.tileID == 1) { g.setColor(Color.blue); g.fillOval(235, 10, 50, 50); } if (tile4.tileID == 1) { g.setColor(Color.blue); g.fillOval(310, 10, 50, 50); } if (tile5.tileID == 1) { g.setColor(Color.blue); g.fillOval(385, 10, 50, 50); } if (tile6.tileID == 1) { g.setColor(Color.blue); g.fillOval(460, 10, 50, 50); } if (tile7.tileID == 1) { g.setColor(Color.blue); g.fillOval(535, 10, 50, 50); } // row 2 - blue if (tile8.tileID == 1) { g.setColor(Color.blue); g.fillOval(10, 90, 50, 50); } if (tile9.tileID == 1) { g.setColor(Color.blue); g.fillOval(85, 90, 50, 50); } if (tile10.tileID == 1) { g.setColor(Color.blue); g.fillOval(160, 90, 50, 50); } if (tile11.tileID == 1) { g.setColor(Color.blue); g.fillOval(235, 90, 50, 50); } if (tile12.tileID == 1) { g.setColor(Color.blue); g.fillOval(310, 90, 50, 50); } if (tile13.tileID == 1) { g.setColor(Color.blue); g.fillOval(385, 90, 50, 50); } if (tile14.tileID == 1) { g.setColor(Color.blue); g.fillOval(460, 90, 50, 50); } if (tile15.tileID == 1) { g.setColor(Color.blue); g.fillOval(535, 90, 50, 50); } } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == timer) { // System.out.println(currentlySelected); this.repaint(); } } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); if (code == KeyEvent.VK_E) { System.out.println("pressed E"); } if (code == KeyEvent.VK_ESCAPE) { System.out.println("pressed Escape"); currentlySelected = null; } } @Override public void keyReleased(KeyEvent e) { } @Override public void mouseClicked(MouseEvent e) { int x = e.getX(); int y = e.getY(); System.out.println("Click:" + x + "," + y); if (currentlySelected == null) { currentlySelected = fieldAt(x, y); } if (currentlySelected != null && fieldAt(x, y).tileID == 0) { fieldAt(x, y).tileID = currentlySelected.tileID; currentlySelected.tileID = 0; currentlySelected = null; } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { } private Tile fieldAt(int x, int y) { // ROW 1 if (x > 0 && x < 75 && y > 0 && y < 75) { return tile0; } if (x > 75 && x < 150 && y > 0 && y < 75) { return tile1; } if (x > 150 && x < 225 && y > 0 && y < 75) { return tile2; } if (x > 225 && x < 300 && y > 0 && y < 75) { return tile3; } if (x > 300 && x < 375 && y > 0 && y < 75) { return tile4; } if (x > 375 && x < 450 && y > 0 && y < 75) { return tile5; } if (x > 450 && x < 525 && y > 0 && y < 75) { return tile6; } if (x > 525 && x < 600 && y > 0 && y < 75) { return tile7; } if (x > 0 && x < 75 && y > 75 && y < 150) { return tile8; } if (x > 75 && x < 150 && y > 75 && y < 150) { return tile9; } if (x > 150 && x < 225 && y > 75 && y < 150) { return tile10; } if (x > 225 && x < 300 && y > 75 && y < 150) { return tile11; } if (x > 300 && x < 375 && y > 75 && y < 150) { return tile12; } if (x > 375 && x < 450 && y > 75 && y < 150) { return tile13; } if (x > 450 && x < 525 && y > 75 && y < 150) { return tile14; } if (x > 525 && x < 600 && y > 75 && y < 150) { return tile15; } return null; } private void paintCurrentlySelectedBorder(Graphics g) { // ROW 1 if (currentlySelected == tile0) { g.setColor(Color.orange); g.fillOval(8, 7, 55, 55); } else if (currentlySelected == tile1) { g.setColor(Color.orange); g.fillOval(83, 7, 55, 55); } else if (currentlySelected == tile2) { g.setColor(Color.orange); g.fillOval(157, 7, 55, 55); } else if (currentlySelected == tile3) { g.setColor(Color.orange); g.fillOval(233, 7, 55, 55); } else if (currentlySelected == tile4) { g.setColor(Color.orange); g.fillOval(317, 7, 55, 55); } else if (currentlySelected == tile5) { g.setColor(Color.orange); g.fillOval(382, 7, 55, 55); } else if (currentlySelected == tile6) { g.setColor(Color.orange); g.fillOval(457, 7, 55, 55); } else if (currentlySelected == tile7) { g.setColor(Color.orange); g.fillOval(532, 7, 55, 55); } // ROW 2 if (currentlySelected == tile8) { g.setColor(Color.orange); g.drawOval(10, 90, 50, 50); g.drawOval(9, 90, 50, 50); g.drawOval(8, 90, 50, 50); } else if (currentlySelected == tile9) { g.setColor(Color.orange); g.drawOval(85, 90, 50, 50); g.drawOval(84, 90, 50, 50); g.drawOval(83, 90, 50, 50); } else if (currentlySelected == tile10) { g.setColor(Color.orange); g.drawOval(160, 90, 50, 50); g.drawOval(159, 90, 50, 50); g.drawOval(158, 90, 50, 50); } else if (currentlySelected == tile11) { g.setColor(Color.orange); g.drawOval(235, 90, 50, 50); g.drawOval(234, 90, 50, 50); g.drawOval(233, 90, 50, 50); } else if (currentlySelected == tile12) { g.setColor(Color.orange); g.drawOval(310, 90, 50, 50); g.drawOval(309, 90, 50, 50); g.drawOval(309, 90, 50, 50); } else if (currentlySelected == tile13) { g.setColor(Color.orange); g.drawOval(385, 90, 50, 50); g.drawOval(384, 90, 50, 50); g.drawOval(383, 90, 50, 50); } else if (currentlySelected == tile14) { g.setColor(Color.orange); g.drawOval(460, 90, 50, 50); g.drawOval(459, 90, 50, 50); g.drawOval(458, 90, 50, 50); } else if (currentlySelected == tile15) { g.setColor(Color.orange); g.drawOval(535, 90, 50, 50); g.drawOval(534, 90, 50, 50); g.drawOval(532, 90, 50, 50); } } } class Tile { int tileID; public Tile(int tileID) { this.tileID = tileID; } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package wyc.builder; import java.util.*; import static wyc.lang.WhileyFile.internalFailure; import static wyc.lang.WhileyFile.syntaxError; import static wyil.util.ErrorMessages.*; import wybs.lang.Attribute; import wybs.lang.NameID; import wybs.lang.Path; import wybs.lang.SyntacticElement; import wybs.lang.SyntaxError; import wybs.util.Pair; import wybs.util.ResolveError; import wybs.util.Triple; import wyc.lang.*; import wyc.lang.Stmt.*; import wyc.lang.WhileyFile.Context; import wyil.lang.*; /** * <p> * Responsible for compiling the declarations, statements and expression found * in a WhileyFile into WyIL declarations and bytecode blocks. For example: * </p> * * <pre> * type nat is (int x) where x >= 0 * * int f(nat x): * return x-1 * </pre> * * <p> * The code generator is responsible for generating the code for the constraint * on <code>nat</code>, as well as compiling the function's statements into * their corresponding WyIL bytecodes. For example, the code generated * constraint on type <code>nat</code> would look like this: * </p> * * <pre> * type nat is int * where: * load x * const 0 * ifge goto exit * fail("type constraint not satisfied") * .exit: * </pre> * * This WyIL bytecode simply compares the local variable x against 0. Here, x * represents the value held in a variable of type <code>nat</code>. If the * constraint fails, then the given message is printed. * * @author David J. Pearce * */ public final class CodeGenerator { /** * The builder is needed to provide access to external resources (i.e. * external WyIL files compiled separately). This is required for expanding * types and their constraints in certain situations, such as runtime type * tests (e.g. <code>x is T</code> where <code>T</code> is defined * externally). */ private final WhileyBuilder builder; /** * The type checker provides access to the pool of resolved types. */ private final FlowTypeChecker resolver; /** * The lambdas are anonymous functions used within statements and * expressions in the source file. These are compiled into anonymised WyIL * functions, since WyIL does not have an internal notion of a lambda. */ private final ArrayList<WyilFile.MethodDeclaration> lambdas = new ArrayList<WyilFile.MethodDeclaration>(); /** * The scopes stack is used for determining the correct scoping for continue * and break statements. Whenever we begin translating a loop of some kind, * a <code>LoopScope</code> is pushed on the stack. Once the translation of * that loop is complete, this is then popped off the stack. */ private Stack<Scope> scopes = new Stack<Scope>(); /** * The name cache stores the translations of any code associated with a * named type or constant, which was previously computed. */ private final HashMap<NameID,Block> cache = new HashMap<NameID,Block>(); /** * Construct a code generator object for translating WhileyFiles into * WyilFiles. * * @param builder * The enclosing builder instance which provides access to the * global namespace. * @param resolver * The relevant type checker instance which provides access to * the pool of previously determined types. */ public CodeGenerator(WhileyBuilder builder, FlowTypeChecker resolver) { this.builder = builder; this.resolver = resolver; } // WhileyFile /** * Generate a WyilFile from a given WhileyFile by translating all of the * declarations, statements and expressions into WyIL declarations and * bytecode blocks. * * @param wf * The WhileyFile to be translated. * @return */ public WyilFile generate(WhileyFile wf) { ArrayList<WyilFile.Declaration> declarations = new ArrayList<WyilFile.Declaration>(); // Go through each declaration and translate in the order of appearance. for (WhileyFile.Declaration d : wf.declarations) { try { if (d instanceof WhileyFile.Type) { declarations.add(generate((WhileyFile.Type) d)); } else if (d instanceof WhileyFile.Constant) { declarations.add(generate((WhileyFile.Constant) d)); } else if (d instanceof WhileyFile.FunctionOrMethod) { declarations.add(generate((WhileyFile.FunctionOrMethod) d)); } } catch (SyntaxError se) { throw se; } catch (Throwable ex) { WhileyFile.internalFailure(ex.getMessage(), (WhileyFile.Context) d, d, ex); } } // Add any lambda functions which were used within some expression. Each // of these is guaranteed to have been given a unique and valid WyIL // name. declarations.addAll(lambdas); // Done return new WyilFile(wf.module, wf.filename, declarations); } // Constant Declarations /** * Generate a WyilFile constant declaration from a WhileyFile constant * declaration. This requires evaluating the given expression to produce a * constant value. If this cannot be done, then a syntax error is raised to * indicate an invalid constant declaration was encountered. */ private WyilFile.ConstantDeclaration generate(WhileyFile.Constant cd) { // TODO: this the point where were should an evaluator return new WyilFile.ConstantDeclaration(cd.modifiers, cd.name, cd.resolvedValue); } // Type Declarations /** * Generate a WyilFile type declaration from a WhileyFile type declaration. * If a type invariant is given, then this will need to be translated into * Wyil bytecode. * * @param td * @return * @throws Exception */ private WyilFile.TypeDeclaration generate(WhileyFile.Type td) throws Exception { Block invariant = null; if (td.invariant != null) { // Create an empty invariant block to be populated during constraint // generation. invariant = new Block(1); // Setup the environment which maps source variables to block // registers. This is determined by allocating the root variable to // register 0, and then creating any variables declared in the type // pattern by from this root. Environment environment = new Environment(); int root = environment.allocate(td.resolvedType.raw()); addDeclaredVariables(root, td.pattern, td.resolvedType.raw(), environment, invariant); // Finally, translate the invariant expression. int target = generate(td.invariant, environment, invariant, td); // TODO: assign target register to something? } return new WyilFile.TypeDeclaration(td.modifiers, td.name(), td.resolvedType.nominal(), invariant); } // Function / Method Declarations private WyilFile.MethodDeclaration generate( WhileyFile.FunctionOrMethod fd) throws Exception { Type.FunctionOrMethod ftype = fd.resolvedType().raw(); // The environment maintains the mapping from source-level variables to // the registers in WyIL block(s). Environment environment = new Environment(); // Generate pre-condition // First, allocate parameters to registers in the current block for (int i=0;i!=fd.parameters.size();++i) { WhileyFile.Parameter p = fd.parameters.get(i); environment.allocate(ftype.params().get(i), p.name()); } // TODO: actually translate pre-condition Block precondition = null; // Generate post-condition Block postcondition = null; if (fd.ensures.size() > 0) { // This indicates one or more explicit ensures clauses are given. // Therefore, we must translate each of these into Wyil bytecodes. // First, we need to create an appropriate environment within which // to translate the post-conditions. Environment postEnv = new Environment(); int root = postEnv.allocate(fd.resolvedType().ret().raw()); // FIXME: can't we reuse the original environment? Well, if we // allocated the return variable after the parameters then we // probably could. for (int i = 0; i != fd.parameters.size(); ++i) { WhileyFile.Parameter p = fd.parameters.get(i); postEnv.allocate(ftype.params().get(i), p.name()); } postcondition = new Block(postEnv.size()); addDeclaredVariables(root, fd.ret, fd.resolvedType().ret().raw(), postEnv, postcondition); for (Expr condition : fd.ensures) { // TODO: actually translate these conditions. } } // Generate body Block body = new Block(fd.parameters.size()); for (Stmt s : fd.statements) { generate(s, environment, body, fd); } // The following is sneaky. It guarantees that every method ends in a // return. For methods that actually need a value, this is either // removed as dead-code or remains and will cause an error. body.append(Code.Return(),attributes(fd)); List<WyilFile.Case> ncases = new ArrayList<WyilFile.Case>(); ArrayList<String> locals = new ArrayList<String>(); ncases.add(new WyilFile.Case(body,precondition,postcondition,locals)); // Done return new WyilFile.MethodDeclaration(fd.modifiers, fd.name(), fd .resolvedType().raw(), ncases); } // Statements public void generate(Stmt stmt, Environment environment, Block codes, Context context) { try { if (stmt instanceof VariableDeclaration) { generate((VariableDeclaration) stmt, environment, codes, context); } else if (stmt instanceof Assign) { generate((Assign) stmt, environment, codes, context); } else if (stmt instanceof Assert) { generate((Assert) stmt, environment, codes, context); } else if (stmt instanceof Assume) { generate((Assume) stmt, environment, codes, context); } else if (stmt instanceof Return) { generate((Return) stmt, environment, codes, context); } else if (stmt instanceof Debug) { generate((Debug) stmt, environment, codes, context); } else if (stmt instanceof IfElse) { generate((IfElse) stmt, environment, codes, context); } else if (stmt instanceof Switch) { generate((Switch) stmt, environment, codes, context); } else if (stmt instanceof TryCatch) { generate((TryCatch) stmt, environment, codes, context); } else if (stmt instanceof Break) { generate((Break) stmt, environment, codes, context); } else if (stmt instanceof Throw) { generate((Throw) stmt, environment, codes, context); } else if (stmt instanceof While) { generate((While) stmt, environment, codes, context); } else if (stmt instanceof DoWhile) { generate((DoWhile) stmt, environment, codes, context); } else if (stmt instanceof ForAll) { generate((ForAll) stmt, environment, codes, context); } else if (stmt instanceof Expr.MethodCall) { generate((Expr.MethodCall) stmt, Code.NULL_REG, environment, codes, context); } else if (stmt instanceof Expr.FunctionCall) { generate((Expr.FunctionCall) stmt, Code.NULL_REG, environment, codes, context); } else if (stmt instanceof Expr.IndirectMethodCall) { generate((Expr.IndirectMethodCall) stmt, Code.NULL_REG, environment, codes, context); } else if (stmt instanceof Expr.IndirectFunctionCall) { generate((Expr.IndirectFunctionCall) stmt, Code.NULL_REG, environment, codes, context); } else if (stmt instanceof Expr.New) { generate((Expr.New) stmt, environment, codes, context); } else if (stmt instanceof Skip) { generate((Skip) stmt, environment, codes, context); } else { // should be dead-code WhileyFile.internalFailure("unknown statement: " + stmt.getClass().getName(), context, stmt); } } catch (ResolveError rex) { WhileyFile.syntaxError(rex.getMessage(), context, stmt, rex); } catch (SyntaxError sex) { throw sex; } catch (Exception ex) { WhileyFile.internalFailure(ex.getMessage(), context, stmt, ex); } } public void generate(VariableDeclaration s, Environment environment, Block codes, Context context) { // First, we allocate this variable to a given slot in the environment. int target = environment.allocate(s.type.raw(), s.name); // Second, translate initialiser expression if it exists. if(s.expr != null) { int operand = generate(s.expr, environment, codes, context); codes.append(Code.Assign(s.expr.result().raw(), target, operand), attributes(s)); } } public void generate(Assign s, Environment environment, Block codes, Context context) { // First, we translate the right-hand side expression and assign it to a // temporary register. int operand = generate(s.rhs, environment, codes, context); // Second, we update the left-hand side of this assignment // appropriately. if (s.lhs instanceof Expr.AssignedVariable) { Expr.AssignedVariable v = (Expr.AssignedVariable) s.lhs; // This is the easiest case. Having translated the right-hand side // expression, we now assign it directly to the register allocated // for variable on the left-hand side. int target = environment.get(v.var); codes.append(Code.Assign(s.rhs.result().raw(), target, operand), attributes(s)); } else if(s.lhs instanceof Expr.RationalLVal) { Expr.RationalLVal tg = (Expr.RationalLVal) s.lhs; // Having translated the right-hand side expression, we now // destructure it using the numerator and denominator unary // bytecodes. Expr.AssignedVariable lv = (Expr.AssignedVariable) tg.numerator; Expr.AssignedVariable rv = (Expr.AssignedVariable) tg.denominator; codes.append(Code.UnArithOp(s.rhs.result() .raw(), environment.get(lv.var), operand, Code.UnArithKind.NUMERATOR), attributes(s)); codes.append(Code.UnArithOp(s.rhs.result().raw(), environment.get(rv.var), operand, Code.UnArithKind.DENOMINATOR), attributes(s)); } else if(s.lhs instanceof Expr.Tuple) { Expr.Tuple tg = (Expr.Tuple) s.lhs; // Having translated the right-hand side expression, we now // destructure it using tupleload bytecodes and assign to those // variables on the left-hand side. ArrayList<Expr> fields = new ArrayList<Expr>(tg.fields); for (int i = 0; i != fields.size(); ++i) { Expr.AssignedVariable v = (Expr.AssignedVariable) fields.get(i); codes.append(Code.TupleLoad((Type.EffectiveTuple) s.rhs .result().raw(), environment.get(v.var), operand, i), attributes(s)); } } else if (s.lhs instanceof Expr.IndexOf || s.lhs instanceof Expr.FieldAccess) { // This is the more complicated case, since the left-hand side // expression is recursive. However, the WyIL update bytecode comes // to the rescue here. All we need to do is extract the variable // being updated and give this to the update bytecode. For example, // in the expression "x.y.f = e" we have that variable "x" is being // updated. ArrayList<String> fields = new ArrayList<String>(); ArrayList<Integer> operands = new ArrayList<Integer>(); Expr.AssignedVariable lhs = extractLVal(s.lhs, fields, operands, environment, codes, context); int target = environment.get(lhs.var); codes.append(Code.Update(lhs.type.raw(), target, operand, operands, lhs.afterType.raw(), fields), attributes(s)); } else { WhileyFile.syntaxError("invalid assignment", context, s); } } /** * This function recurses down the left-hand side of an assignment (e.g. * x[i] = e, x.f = e, etc) with a complex lval. The primary goal is to * identify the left-most variable which is actually being updated. A * secondary goal is to collect the sequence of field names being updated, * and translate any index expressions and store them in temporary * registers. * * @param e * The LVal being extract from. * @param fields * The list of fields being used in the assignment. * Initially, this is empty and is filled by this method as it * traverses the lval. * @param operands * The list of temporary registers in which evaluated index * expression are stored. Initially, this is empty and is filled * by this method as it traverses the lval. * @param environment * Mapping from variable names to block registers. * @param codes * Code block into which this statement is to be translated. * @param context * Enclosing context of this statement (i.e. type, constant, * function or method declaration). The context is used to aid * with error reporting as it determines the enclosing file. * @return */ private Expr.AssignedVariable extractLVal(Expr.LVal e, ArrayList<String> fields, ArrayList<Integer> operands, Environment environment, Block codes, Context context) { if (e instanceof Expr.AssignedVariable) { Expr.AssignedVariable v = (Expr.AssignedVariable) e; return v; } else if (e instanceof Expr.Dereference) { Expr.Dereference pa = (Expr.Dereference) e; return extractLVal((Expr.LVal) pa.src, fields, operands, environment, codes, context); } else if (e instanceof Expr.IndexOf) { Expr.IndexOf la = (Expr.IndexOf) e; int operand = generate(la.index, environment, codes, context); Expr.AssignedVariable l = extractLVal((Expr.LVal) la.src, fields, operands, environment, codes, context); operands.add(operand); return l; } else if (e instanceof Expr.FieldAccess) { Expr.FieldAccess ra = (Expr.FieldAccess) e; Expr.AssignedVariable r = extractLVal((Expr.LVal) ra.src, fields, operands, environment, codes, context); fields.add(ra.name); return r; } else { WhileyFile.syntaxError(errorMessage(INVALID_LVAL_EXPRESSION), context, e); return null; // dead code } } public void generate(Assert s, Environment environment, Block codes, Context context) { // TODO: implement me } public void generate(Assume s, Environment environment, Block codes, Context context) { // TODO: need to implement this translation. } public void generate(Return s, Environment environment, Block codes, Context context) { if (s.expr != null) { int operand = generate(s.expr, environment, codes, context); // Here, we don't put the type propagated for the return expression. // Instead, we use the declared return type of this function. This // has the effect of forcing an implicit coercion between the // actual value being returned and its required type. Type ret = ((WhileyFile.FunctionOrMethod) context).resolvedType() .raw().ret(); codes.append(Code.Return(ret, operand), attributes(s)); } else { codes.append(Code.Return(), attributes(s)); } } public void generate(Skip s, Environment environment, Block codes, Context context) { codes.append(Code.Nop, attributes(s)); } public void generate(Debug s, Environment environment, Block codes, Context context) { int operand = generate(s.expr, environment, codes, context); codes.append(Code.Debug(operand), attributes(s)); } public void generate(IfElse s, Environment environment, Block codes, Context context) { String falseLab = Block.freshLabel(); String exitLab = s.falseBranch.isEmpty() ? falseLab : Block .freshLabel(); generateCondition(falseLab, invert(s.condition), environment, codes, context); for (Stmt st : s.trueBranch) { generate(st, environment, codes, context); } if (!s.falseBranch.isEmpty()) { codes.append(Code.Goto(exitLab)); codes.append(Code.Label(falseLab)); for (Stmt st : s.falseBranch) { generate(st, environment, codes, context); } } codes.append(Code.Label(exitLab)); } public void generate(Throw s, Environment environment, Block codes, Context context) { int operand = generate(s.expr, environment, codes, context); codes.append(Code.Throw(s.expr.result().raw(), operand), s.attributes()); } public void generate(Break s, Environment environment, Block codes, Context context) { BreakScope scope = findEnclosingScope(BreakScope.class); if (scope == null) { WhileyFile.syntaxError(errorMessage(BREAK_OUTSIDE_LOOP), context, s); } codes.append(Code.Goto(scope.label)); } public void generate(Switch s, Environment environment, Block codes, Context context) throws Exception { String exitLab = Block.freshLabel(); int operand = generate(s.expr, environment, codes, context); String defaultTarget = exitLab; HashSet<Constant> values = new HashSet(); ArrayList<Pair<Constant, String>> cases = new ArrayList(); int start = codes.size(); for (Stmt.Case c : s.cases) { if (c.expr.isEmpty()) { // A case with an empty match represents the default label. We // must check that we have not already seen a case with an empty // match (otherwise, we'd have two default labels ;) if (defaultTarget != exitLab) { WhileyFile.syntaxError( errorMessage(DUPLICATE_DEFAULT_LABEL), context, c); } else { defaultTarget = Block.freshLabel(); codes.append(Code.Label(defaultTarget), attributes(c)); for (Stmt st : c.stmts) { generate(st, environment, codes, context); } codes.append(Code.Goto(exitLab), attributes(c)); } } else if (defaultTarget == exitLab) { String target = Block.freshLabel(); codes.append(Code.Label(target), attributes(c)); // Case statements in Whiley may have multiple matching constant // values. Therefore, we iterate each matching value and // construct a mapping from that to a label indicating the start // of the case body. for (Constant constant : c.constants) { // Check whether this case constant has already been used as // a case constant elsewhere. If so, then report an error. if (values.contains(constant)) { WhileyFile.syntaxError( errorMessage(DUPLICATE_CASE_LABEL), context, c); } cases.add(new Pair(constant, target)); values.add(constant); } for (Stmt st : c.stmts) { generate(st, environment, codes, context); } codes.append(Code.Goto(exitLab), attributes(c)); } else { // This represents the case where we have another non-default // case after the default case. Such code cannot be executed, // and is therefore reported as an error. WhileyFile.syntaxError(errorMessage(UNREACHABLE_CODE), context, c); } } codes.insert(start, Code.Switch(s.expr.result().raw(), operand, defaultTarget, cases), attributes(s)); codes.append(Code.Label(exitLab), attributes(s)); } public void generate(TryCatch s, Environment environment, Block codes, Context context) throws Exception { int start = codes.size(); int exceptionRegister = environment.allocate(Type.T_ANY); String exitLab = Block.freshLabel(); for (Stmt st : s.body) { generate(st, environment, codes, context); } codes.append(Code.Goto(exitLab),attributes(s)); String endLab = null; ArrayList<Pair<Type,String>> catches = new ArrayList<Pair<Type,String>>(); for(Stmt.Catch c : s.catches) { Code.Label lab; if(endLab == null) { endLab = Block.freshLabel(); lab = Code.TryEnd(endLab); } else { lab = Code.Label(Block.freshLabel()); } Type pt = c.type.raw(); // TODO: deal with exception type constraints catches.add(new Pair<Type,String>(pt,lab.label)); codes.append(lab, attributes(c)); environment.put(exceptionRegister, c.variable); for (Stmt st : c.stmts) { generate(st, environment, codes, context); } codes.append(Code.Goto(exitLab),attributes(c)); } codes.insert(start, Code.TryCatch(exceptionRegister,endLab,catches),attributes(s)); codes.append(Code.Label(exitLab), attributes(s)); } public void generate(While s, Environment environment, Block codes, Context context) { String label = Block.freshLabel(); String exit = Block.freshLabel(); codes.append(Code.Loop(label, Collections.EMPTY_SET), attributes(s)); generateCondition(exit, invert(s.condition), environment, codes, context); scopes.push(new BreakScope(exit)); for (Stmt st : s.body) { generate(st, environment, codes, context); } scopes.pop(); // break // Must add NOP before loop end to ensure labels at the boundary // get written into Wyil files properly. See Issue #253. codes.append(Code.Nop); codes.append(Code.LoopEnd(label), attributes(s)); codes.append(Code.Label(exit), attributes(s)); } public void generate(DoWhile s, Environment environment, Block codes, Context context) { String label = Block.freshLabel(); String exit = Block.freshLabel(); codes.append(Code.Loop(label, Collections.EMPTY_SET), attributes(s)); scopes.push(new BreakScope(exit)); for (Stmt st : s.body) { generate(st, environment, codes, context); } scopes.pop(); // break generateCondition(exit, invert(s.condition), environment, codes, context); // Must add NOP before loop end to ensure labels at the boundary // get written into Wyil files properly. See Issue #253. codes.append(Code.Nop); codes.append(Code.LoopEnd(label), attributes(s)); codes.append(Code.Label(exit), attributes(s)); } public void generate(ForAll s, Environment environment, Block codes, Context context) { String label = Block.freshLabel(); String exit = Block.freshLabel(); int sourceRegister = generate(s.source, environment, codes, context); // FIXME: loss of nominal information Type.EffectiveCollection rawSrcType = s.srcType.raw(); if (s.variables.size() > 1) { // this is the destructuring case // FIXME: support destructuring of lists and sets if (!(rawSrcType instanceof Type.EffectiveMap)) { WhileyFile.syntaxError(errorMessage(INVALID_MAP_EXPRESSION), context, s.source); } Type.EffectiveMap dict = (Type.EffectiveMap) rawSrcType; Type.Tuple element = (Type.Tuple) Type.Tuple(dict.key(), dict.value()); int indexRegister = environment.allocate(element); codes.append(Code .ForAll((Type.EffectiveMap) rawSrcType, sourceRegister, indexRegister, Collections.EMPTY_SET, label), attributes(s)); for (int i = 0; i < s.variables.size(); ++i) { String var = s.variables.get(i); int varReg = environment.allocate(element.element(i), var); codes.append(Code.TupleLoad(element, varReg, indexRegister, i), attributes(s)); } } else { // easy case. int indexRegister = environment.allocate(rawSrcType.element(), s.variables.get(0)); codes.append(Code.ForAll(s.srcType.raw(), sourceRegister, indexRegister, Collections.EMPTY_SET, label), attributes(s)); } // FIXME: add a continue scope scopes.push(new BreakScope(exit)); for (Stmt st : s.body) { generate(st, environment, codes, context); } scopes.pop(); // break // Must add NOP before loop end to ensure labels at the boundary // get written into Wyil files properly. See Issue #253. codes.append(Code.Nop); codes.append(Code.LoopEnd(label), attributes(s)); codes.append(Code.Label(exit), attributes(s)); } // Conditions public void generateCondition(String target, Expr condition, Environment environment, Block codes, Context context) { try { if (condition instanceof Expr.Constant) { generateCondition(target, (Expr.Constant) condition, environment, codes, context); } else if (condition instanceof Expr.UnOp) { generateCondition(target, (Expr.UnOp) condition, environment, codes, context); } else if (condition instanceof Expr.BinOp) { generateCondition(target, (Expr.BinOp) condition, environment, codes, context); } else if (condition instanceof Expr.Comprehension) { generateCondition(target, (Expr.Comprehension) condition, environment, codes, context); } else if (condition instanceof Expr.ConstantAccess || condition instanceof Expr.LocalVariable || condition instanceof Expr.AbstractInvoke || condition instanceof Expr.AbstractIndirectInvoke || condition instanceof Expr.FieldAccess || condition instanceof Expr.IndexOf) { // The default case simply compares the computed value against // true. In some cases, we could do better. For example, !(x < // 5) could be rewritten into x>=5. int r1 = generate(condition, environment, codes, context); int r2 = environment.allocate(Type.T_BOOL); codes.append(Code.Const(r2, Constant.V_BOOL(true)), attributes(condition)); codes.append(Code.If(Type.T_BOOL, r1, r2, Code.Comparator.EQ, target), attributes(condition)); } else { syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION), context, condition); } } catch (SyntaxError se) { throw se; } catch (Exception ex) { internalFailure(ex.getMessage(), context, condition, ex); } } public void generateCondition(String target, Expr.Constant c, Environment environment, Block codes, Context context) { Constant.Bool b = (Constant.Bool) c.value; if (b.value) { codes.append(Code.Goto(target)); } else { // do nout } } public void generateCondition(String target, Expr.BinOp v, Environment environment, Block codes, Context context) throws Exception { Expr.BOp bop = v.op; if (bop == Expr.BOp.OR) { generateCondition(target, v.lhs, environment, codes, context); generateCondition(target, v.rhs, environment, codes, context); } else if (bop == Expr.BOp.AND) { String exitLabel = Block.freshLabel(); generateCondition(exitLabel, invert(v.lhs), environment, codes, context); generateCondition(target, v.rhs, environment, codes, context); codes.append(Code.Label(exitLabel)); } else if (bop == Expr.BOp.IS) { generateTypeCondition(target, v, environment, codes, context); } else { Code.Comparator cop = OP2COP(bop, v, context); if (cop == Code.Comparator.EQ && v.lhs instanceof Expr.LocalVariable && v.rhs instanceof Expr.Constant && ((Expr.Constant) v.rhs).value == Constant.V_NULL) { // this is a simple rewrite to enable type inference. Expr.LocalVariable lhs = (Expr.LocalVariable) v.lhs; if (environment.get(lhs.var) == null) { syntaxError(errorMessage(UNKNOWN_VARIABLE), context, v.lhs); } int slot = environment.get(lhs.var); codes.append( Code.IfIs(v.srcType.raw(), slot, Type.T_NULL, target), attributes(v)); } else if (cop == Code.Comparator.NEQ && v.lhs instanceof Expr.LocalVariable && v.rhs instanceof Expr.Constant && ((Expr.Constant) v.rhs).value == Constant.V_NULL) { // this is a simple rewrite to enable type inference. String exitLabel = Block.freshLabel(); Expr.LocalVariable lhs = (Expr.LocalVariable) v.lhs; if (environment.get(lhs.var) == null) { syntaxError(errorMessage(UNKNOWN_VARIABLE), context, v.lhs); } int slot = environment.get(lhs.var); codes.append(Code.IfIs(v.srcType.raw(), slot, Type.T_NULL, exitLabel), attributes(v)); codes.append(Code.Goto(target)); codes.append(Code.Label(exitLabel)); } else { int lhs = generate(v.lhs, environment, codes, context); int rhs = generate(v.rhs, environment, codes, context); codes.append(Code.If(v.srcType.raw(), lhs, rhs, cop, target), attributes(v)); } } } public void generateTypeCondition(String target, Expr.BinOp v, Environment environment, Block codes, Context context) throws Exception { int leftOperand; if (v.lhs instanceof Expr.LocalVariable) { Expr.LocalVariable lhs = (Expr.LocalVariable) v.lhs; if (environment.get(lhs.var) == null) { syntaxError(errorMessage(UNKNOWN_VARIABLE), context, v.lhs); } leftOperand = environment.get(lhs.var); } else { leftOperand = generate(v.lhs, environment, codes, context); } Expr.TypeVal rhs = (Expr.TypeVal) v.rhs; codes.append(Code.IfIs(v.srcType.raw(), leftOperand, rhs.type.raw(), target), attributes(v)); } public void generateCondition(String target, Expr.UnOp v, Environment environment, Block codes, Context context) { Expr.UOp uop = v.op; switch (uop) { case NOT: String label = Block.freshLabel(); generateCondition(label, v.mhs, environment, codes, context); codes.append(Code.Goto(target)); codes.append(Code.Label(label)); return; } syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION), context, v); } public void generateCondition(String target, Expr.Comprehension e, Environment environment, Block codes, Context context) { if (e.cop != Expr.COp.NONE && e.cop != Expr.COp.SOME && e.cop != Expr.COp.ALL) { syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION), context, e); } ArrayList<Triple<Integer, Integer, Type.EffectiveCollection>> slots = new ArrayList(); for (Pair<String, Expr> src : e.sources) { Nominal.EffectiveCollection srcType = (Nominal.EffectiveCollection) src .second().result(); int srcSlot; int varSlot = environment.allocate(srcType.raw().element(), src.first()); if (src.second() instanceof Expr.LocalVariable) { // this is a little optimisation to produce slightly better // code. Expr.LocalVariable v = (Expr.LocalVariable) src.second(); if (environment.get(v.var) != null) { srcSlot = environment.get(v.var); } else { // fall-back plan ... srcSlot = generate(src.second(), environment, codes, context); } } else { srcSlot = generate(src.second(), environment, codes, context); } slots.add(new Triple<Integer, Integer, Type.EffectiveCollection>( varSlot, srcSlot, srcType.raw())); } ArrayList<String> labels = new ArrayList<String>(); String loopLabel = Block.freshLabel(); for (Triple<Integer, Integer, Type.EffectiveCollection> p : slots) { Type.EffectiveCollection srcType = p.third(); String lab = loopLabel + "$" + p.first(); codes.append(Code.ForAll(srcType, p.second(), p.first(), Collections.EMPTY_LIST, lab), attributes(e)); labels.add(lab); } if (e.cop == Expr.COp.NONE) { String exitLabel = Block.freshLabel(); generateCondition(exitLabel, e.condition, environment, codes, context); for (int i = (labels.size() - 1); i >= 0; --i) { // Must add NOP before loop end to ensure labels at the boundary // get written into Wyil files properly. See Issue #253. codes.append(Code.Nop); codes.append(Code.LoopEnd(labels.get(i))); } codes.append(Code.Goto(target)); codes.append(Code.Label(exitLabel)); } else if (e.cop == Expr.COp.SOME) { generateCondition(target, e.condition, environment, codes, context); for (int i = (labels.size() - 1); i >= 0; --i) { // Must add NOP before loop end to ensure labels at the boundary // get written into Wyil files properly. See Issue #253. codes.append(Code.Nop); codes.append(Code.LoopEnd(labels.get(i))); } } else if (e.cop == Expr.COp.ALL) { String exitLabel = Block.freshLabel(); generateCondition(exitLabel, invert(e.condition), environment, codes, context); for (int i = (labels.size() - 1); i >= 0; --i) { // Must add NOP before loop end to ensure labels at the boundary // get written into Wyil files properly. See Issue #253. codes.append(Code.Nop); codes.append(Code.LoopEnd(labels.get(i))); } codes.append(Code.Goto(target)); codes.append(Code.Label(exitLabel)); } // LONE and ONE will be harder } // Expressions public int generate(Expr expression, Environment environment, Block codes, Context context) { try { if (expression instanceof Expr.Constant) { return generate((Expr.Constant) expression, environment, codes, context); } else if (expression instanceof Expr.LocalVariable) { return generate((Expr.LocalVariable) expression, environment, codes, context); } else if (expression instanceof Expr.ConstantAccess) { return generate((Expr.ConstantAccess) expression, environment, codes, context); } else if (expression instanceof Expr.Set) { return generate((Expr.Set) expression, environment, codes, context); } else if (expression instanceof Expr.List) { return generate((Expr.List) expression, environment, codes, context); } else if (expression instanceof Expr.SubList) { return generate((Expr.SubList) expression, environment, codes, context); } else if (expression instanceof Expr.SubString) { return generate((Expr.SubString) expression, environment, codes, context); } else if (expression instanceof Expr.BinOp) { return generate((Expr.BinOp) expression, environment, codes, context); } else if (expression instanceof Expr.LengthOf) { return generate((Expr.LengthOf) expression, environment, codes, context); } else if (expression instanceof Expr.Dereference) { return generate((Expr.Dereference) expression, environment, codes, context); } else if (expression instanceof Expr.Cast) { return generate((Expr.Cast) expression, environment, codes, context); } else if (expression instanceof Expr.IndexOf) { return generate((Expr.IndexOf) expression, environment, codes, context); } else if (expression instanceof Expr.UnOp) { return generate((Expr.UnOp) expression, environment, codes, context); } else if (expression instanceof Expr.FunctionCall) { return generate((Expr.FunctionCall) expression, environment, codes, context); } else if (expression instanceof Expr.MethodCall) { return generate((Expr.MethodCall) expression, environment, codes, context); } else if (expression instanceof Expr.IndirectFunctionCall) { return generate((Expr.IndirectFunctionCall) expression, environment, codes, context); } else if (expression instanceof Expr.IndirectMethodCall) { return generate((Expr.IndirectMethodCall) expression, environment, codes, context); } else if (expression instanceof Expr.Comprehension) { return generate((Expr.Comprehension) expression, environment, codes, context); } else if (expression instanceof Expr.FieldAccess) { return generate((Expr.FieldAccess) expression, environment, codes, context); } else if (expression instanceof Expr.Record) { return generate((Expr.Record) expression, environment, codes, context); } else if (expression instanceof Expr.Tuple) { return generate((Expr.Tuple) expression, environment, codes, context); } else if (expression instanceof Expr.Map) { return generate((Expr.Map) expression, environment, codes, context); } else if (expression instanceof Expr.FunctionOrMethod) { return generate((Expr.FunctionOrMethod) expression, environment, codes, context); } else if (expression instanceof Expr.Lambda) { return generate((Expr.Lambda) expression, environment, codes, context); } else if (expression instanceof Expr.New) { return generate((Expr.New) expression, environment, codes, context); } else { // should be dead-code internalFailure("unknown expression: " + expression.getClass().getName(), context, expression); } } catch (ResolveError rex) { syntaxError(rex.getMessage(), context, expression, rex); } catch (SyntaxError se) { throw se; } catch (Exception ex) { internalFailure(ex.getMessage(), context, expression, ex); } return -1; // deadcode } public int generate(Expr.MethodCall expr, Environment environment, Block codes, Context context) throws ResolveError { int target = environment.allocate(expr.result().raw()); generate(expr, target, environment, codes, context); return target; } public void generate(Expr.MethodCall expr, int target, Environment environment, Block codes, Context context) throws ResolveError { int[] operands = generate(expr.arguments, environment, codes, context); codes.append(Code.Invoke(expr.methodType.raw(), target, operands, expr.nid()), attributes(expr)); } public int generate(Expr.FunctionCall expr, Environment environment, Block codes, Context context) throws ResolveError { int target = environment.allocate(expr.result().raw()); generate(expr, target, environment, codes, context); return target; } public void generate(Expr.FunctionCall expr, int target, Environment environment, Block codes, Context context) throws ResolveError { int[] operands = generate(expr.arguments, environment, codes, context); codes.append( Code.Invoke(expr.functionType.raw(), target, operands, expr.nid()), attributes(expr)); } public int generate(Expr.IndirectFunctionCall expr, Environment environment, Block codes, Context context) throws ResolveError { int target = environment.allocate(expr.result().raw()); generate(expr, target, environment, codes, context); return target; } public void generate(Expr.IndirectFunctionCall expr, int target, Environment environment, Block codes, Context context) throws ResolveError { int operand = generate(expr.src, environment, codes, context); int[] operands = generate(expr.arguments, environment, codes, context); codes.append(Code.IndirectInvoke(expr.functionType.raw(), target, operand, operands), attributes(expr)); } public int generate(Expr.IndirectMethodCall expr, Environment environment, Block codes, Context context) throws ResolveError { int target = environment.allocate(expr.result().raw()); generate(expr, target, environment, codes, context); return target; } public void generate(Expr.IndirectMethodCall expr, int target, Environment environment, Block codes, Context context) throws ResolveError { int operand = generate(expr.src, environment, codes, context); int[] operands = generate(expr.arguments, environment, codes, context); codes.append(Code.IndirectInvoke(expr.methodType.raw(), target, operand, operands), attributes(expr)); } private int generate(Expr.Constant expr, Environment environment, Block codes, Context context) { Constant val = expr.value; int target = environment.allocate(val.type()); codes.append(Code.Const(target, expr.value), attributes(expr)); return target; } private int generate(Expr.FunctionOrMethod expr, Environment environment, Block codes, Context context) { Type.FunctionOrMethod type = expr.type.raw(); int target = environment.allocate(type); codes.append( Code.Lambda(type, target, Collections.EMPTY_LIST, expr.nid), attributes(expr)); return target; } private int generate(Expr.Lambda expr, Environment environment, Block codes, Context context) { Type.FunctionOrMethod tfm = expr.type.raw(); List<Type> tfm_params = tfm.params(); List<WhileyFile.Parameter> expr_params = expr.parameters; // Create environment for the lambda body. ArrayList<Integer> operands = new ArrayList<Integer>(); ArrayList<Type> paramTypes = new ArrayList<Type>(); Environment benv = new Environment(); for (int i = 0; i != tfm_params.size(); ++i) { Type type = tfm_params.get(i); benv.allocate(type, expr_params.get(i).name); paramTypes.add(type); operands.add(Code.NULL_REG); } for(Pair<Type,String> v : Exprs.uses(expr.body,context)) { if(benv.get(v.second()) == null) { Type type = v.first(); benv.allocate(type,v.second()); paramTypes.add(type); operands.add(environment.get(v.second())); } } // Generate body based on current environment Block body = new Block(expr_params.size()); if(tfm.ret() != Type.T_VOID) { int target = generate(expr.body, benv, body, context); body.append(Code.Return(tfm.ret(), target), attributes(expr)); } else { body.append(Code.Return(), attributes(expr)); } // Create concrete type for private lambda function Type.FunctionOrMethod cfm; if(tfm instanceof Type.Function) { cfm = Type.Function(tfm.ret(),tfm.throwsClause(),paramTypes); } else { cfm = Type.Method(tfm.ret(),tfm.throwsClause(),paramTypes); } // Construct private lambda function using generated body int id = expr.attribute(Attribute.Source.class).start; String name = "$lambda" + id; ArrayList<Modifier> modifiers = new ArrayList<Modifier>(); modifiers.add(Modifier.PRIVATE); ArrayList<WyilFile.Case> cases = new ArrayList<WyilFile.Case>(); cases.add(new WyilFile.Case(body, null, null, Collections.EMPTY_LIST, attributes(expr))); WyilFile.MethodDeclaration lambda = new WyilFile.MethodDeclaration( modifiers, name, cfm, cases, attributes(expr)); lambdas.add(lambda); Path.ID mid = context.file().module; NameID nid = new NameID(mid, name); // Finally, create the lambda int target = environment.allocate(tfm); codes.append( Code.Lambda(cfm, target, operands, nid), attributes(expr)); return target; } private int generate(Expr.ConstantAccess expr, Environment environment, Block codes, Context context) throws ResolveError { Constant val = expr.value; int target = environment.allocate(val.type()); codes.append(Code.Const(target, val), attributes(expr)); return target; } private int generate(Expr.LocalVariable expr, Environment environment, Block codes, Context context) throws ResolveError { if (environment.get(expr.var) != null) { Type type = expr.result().raw(); int operand = environment.get(expr.var); int target = environment.allocate(type); codes.append(Code.Assign(type, target, operand), attributes(expr)); return target; } else { syntaxError(errorMessage(VARIABLE_POSSIBLY_UNITIALISED), context, expr); return -1; } } private int generate(Expr.UnOp expr, Environment environment, Block codes, Context context) { int operand = generate(expr.mhs, environment, codes, context); int target = environment.allocate(expr.result().raw()); switch (expr.op) { case NEG: codes.append(Code.UnArithOp(expr.result().raw(), target, operand, Code.UnArithKind.NEG), attributes(expr)); break; case INVERT: codes.append(Code.Invert(expr.result().raw(), target, operand), attributes(expr)); break; case NOT: String falseLabel = Block.freshLabel(); String exitLabel = Block.freshLabel(); generateCondition(falseLabel, expr.mhs, environment, codes, context); codes.append(Code.Const(target, Constant.V_BOOL(true)), attributes(expr)); codes.append(Code.Goto(exitLabel)); codes.append(Code.Label(falseLabel)); codes.append(Code.Const(target, Constant.V_BOOL(false)), attributes(expr)); codes.append(Code.Label(exitLabel)); break; default: // should be dead-code internalFailure("unexpected unary operator encountered", context, expr); return -1; } return target; } private int generate(Expr.LengthOf expr, Environment environment, Block codes, Context context) { int operand = generate(expr.src, environment, codes, context); int target = environment.allocate(expr.result().raw()); codes.append(Code.LengthOf(expr.srcType.raw(), target, operand), attributes(expr)); return target; } private int generate(Expr.Dereference expr, Environment environment, Block codes, Context context) { int operand = generate(expr.src, environment, codes, context); int target = environment.allocate(expr.result().raw()); codes.append(Code.Dereference(expr.srcType.raw(), target, operand), attributes(expr)); return target; } private int generate(Expr.IndexOf expr, Environment environment, Block codes, Context context) { int srcOperand = generate(expr.src, environment, codes, context); int idxOperand = generate(expr.index, environment, codes, context); int target = environment.allocate(expr.result().raw()); codes.append(Code.IndexOf(expr.srcType.raw(), target, srcOperand, idxOperand), attributes(expr)); return target; } private int generate(Expr.Cast expr, Environment environment, Block codes, Context context) { int operand = generate(expr.expr, environment, codes, context); Type from = expr.expr.result().raw(); Type to = expr.result().raw(); int target = environment.allocate(to); // TODO: include constraints codes.append(Code.Convert(from, target, operand, to), attributes(expr)); return target; } private int generate(Expr.BinOp v, Environment environment, Block codes, Context context) throws Exception { // could probably use a range test for this somehow if (v.op == Expr.BOp.EQ || v.op == Expr.BOp.NEQ || v.op == Expr.BOp.LT || v.op == Expr.BOp.LTEQ || v.op == Expr.BOp.GT || v.op == Expr.BOp.GTEQ || v.op == Expr.BOp.SUBSET || v.op == Expr.BOp.SUBSETEQ || v.op == Expr.BOp.ELEMENTOF || v.op == Expr.BOp.AND || v.op == Expr.BOp.OR) { String trueLabel = Block.freshLabel(); String exitLabel = Block.freshLabel(); generateCondition(trueLabel, v, environment, codes, context); int target = environment.allocate(Type.T_BOOL); codes.append(Code.Const(target, Constant.V_BOOL(false)), attributes(v)); codes.append(Code.Goto(exitLabel)); codes.append(Code.Label(trueLabel)); codes.append(Code.Const(target, Constant.V_BOOL(true)), attributes(v)); codes.append(Code.Label(exitLabel)); return target; } else { Expr.BOp bop = v.op; int leftOperand = generate(v.lhs, environment, codes, context); int rightOperand = generate(v.rhs, environment, codes, context); Type result = v.result().raw(); int target = environment.allocate(result); switch (bop) { case UNION: codes.append(Code.BinSetOp((Type.EffectiveSet) result, target, leftOperand, rightOperand, Code.BinSetKind.UNION), attributes(v)); break; case INTERSECTION: codes.append(Code .BinSetOp((Type.EffectiveSet) result, target, leftOperand, rightOperand, Code.BinSetKind.INTERSECTION), attributes(v)); break; case DIFFERENCE: codes.append(Code.BinSetOp((Type.EffectiveSet) result, target, leftOperand, rightOperand, Code.BinSetKind.DIFFERENCE), attributes(v)); break; case LISTAPPEND: codes.append(Code.BinListOp((Type.EffectiveList) result, target, leftOperand, rightOperand, Code.BinListKind.APPEND), attributes(v)); break; case STRINGAPPEND: Type lhs = v.lhs.result().raw(); Type rhs = v.rhs.result().raw(); Code.BinStringKind op; if (lhs == Type.T_STRING && rhs == Type.T_STRING) { op = Code.BinStringKind.APPEND; } else if (lhs == Type.T_STRING && Type.isSubtype(Type.T_CHAR, rhs)) { op = Code.BinStringKind.LEFT_APPEND; } else if (rhs == Type.T_STRING && Type.isSubtype(Type.T_CHAR, lhs)) { op = Code.BinStringKind.RIGHT_APPEND; } else { // this indicates that one operand must be explicitly // converted // into a string. op = Code.BinStringKind.APPEND; } codes.append( Code.BinStringOp(target, leftOperand, rightOperand, op), attributes(v)); break; default: codes.append(Code.BinArithOp(result, target, leftOperand, rightOperand, OP2BOP(bop, v, context)), attributes(v)); } return target; } } private int generate(Expr.Set expr, Environment environment, Block codes, Context context) { int[] operands = generate(expr.arguments, environment, codes, context); int target = environment.allocate(expr.result().raw()); codes.append(Code.NewSet(expr.type.raw(), target, operands), attributes(expr)); return target; } private int generate(Expr.List expr, Environment environment, Block codes, Context context) { int[] operands = generate(expr.arguments, environment, codes, context); int target = environment.allocate(expr.result().raw()); codes.append(Code.NewList(expr.type.raw(), target, operands), attributes(expr)); return target; } private int generate(Expr.SubList expr, Environment environment, Block codes, Context context) { int srcOperand = generate(expr.src, environment, codes, context); int startOperand = generate(expr.start, environment, codes, context); int endOperand = generate(expr.end, environment, codes, context); int target = environment.allocate(expr.result().raw()); codes.append(Code.SubList(expr.type.raw(), target, srcOperand, startOperand, endOperand), attributes(expr)); return target; } private int generate(Expr.SubString v, Environment environment, Block codes, Context context) { int srcOperand = generate(v.src, environment, codes, context); int startOperand = generate(v.start, environment, codes, context); int endOperand = generate(v.end, environment, codes, context); int target = environment.allocate(v.result().raw()); codes.append( Code.SubString(target, srcOperand, startOperand, endOperand), attributes(v)); return target; } private int generate(Expr.Comprehension e, Environment environment, Block codes, Context context) { // First, check for boolean cases which are handled mostly by // generateCondition. if (e.cop == Expr.COp.SOME || e.cop == Expr.COp.NONE || e.cop == Expr.COp.ALL) { String trueLabel = Block.freshLabel(); String exitLabel = Block.freshLabel(); generateCondition(trueLabel, e, environment, codes, context); int target = environment.allocate(Type.T_BOOL); codes.append(Code.Const(target, Constant.V_BOOL(false)), attributes(e)); codes.append(Code.Goto(exitLabel)); codes.append(Code.Label(trueLabel)); codes.append(Code.Const(target, Constant.V_BOOL(true)), attributes(e)); codes.append(Code.Label(exitLabel)); return target; } else { // Ok, non-boolean case. ArrayList<Triple<Integer, Integer, Type.EffectiveCollection>> slots = new ArrayList(); for (Pair<String, Expr> p : e.sources) { Expr src = p.second(); Type.EffectiveCollection rawSrcType = (Type.EffectiveCollection) src .result().raw(); int varSlot = environment.allocate(rawSrcType.element(), p.first()); int srcSlot; if (src instanceof Expr.LocalVariable) { // this is a little optimisation to produce slightly better // code. Expr.LocalVariable v = (Expr.LocalVariable) src; if (environment.get(v.var) != null) { srcSlot = environment.get(v.var); } else { // fall-back plan ... srcSlot = generate(src, environment, codes, context); } } else { srcSlot = generate(src, environment, codes, context); } slots.add(new Triple(varSlot, srcSlot, rawSrcType)); } Type resultType; int target = environment.allocate(e.result().raw()); if (e.cop == Expr.COp.LISTCOMP) { resultType = e.type.raw(); codes.append(Code.NewList((Type.List) resultType, target, Collections.EMPTY_LIST), attributes(e)); } else { resultType = e.type.raw(); codes.append(Code.NewSet((Type.Set) resultType, target, Collections.EMPTY_LIST), attributes(e)); } // At this point, it would be good to determine an appropriate loop // invariant for a set comprehension. This is easy enough in the // case of // a single variable comprehension, but actually rather difficult // for a // multi-variable comprehension. // For example, consider <code>{x+y | x in xs, y in ys, x<0 && // y<0}</code> // What is an appropriate loop invariant here? String continueLabel = Block.freshLabel(); ArrayList<String> labels = new ArrayList<String>(); String loopLabel = Block.freshLabel(); for (Triple<Integer, Integer, Type.EffectiveCollection> p : slots) { String label = loopLabel + "$" + p.first(); codes.append(Code.ForAll(p.third(), p.second(), p.first(), Collections.EMPTY_LIST, label), attributes(e)); labels.add(label); } if (e.condition != null) { generateCondition(continueLabel, invert(e.condition), environment, codes, context); } int operand = generate(e.value, environment, codes, context); // FIXME: following broken for list comprehensions codes.append(Code.BinSetOp((Type.Set) resultType, target, target, operand, Code.BinSetKind.LEFT_UNION), attributes(e)); if (e.condition != null) { codes.append(Code.Label(continueLabel)); } for (int i = (labels.size() - 1); i >= 0; --i) { // Must add NOP before loop end to ensure labels at the boundary // get written into Wyil files properly. See Issue #253. codes.append(Code.Nop); codes.append(Code.LoopEnd(labels.get(i))); } return target; } } private int generate(Expr.Record expr, Environment environment, Block codes, Context context) { ArrayList<String> keys = new ArrayList<String>(expr.fields.keySet()); Collections.sort(keys); int[] operands = new int[expr.fields.size()]; for (int i = 0; i != operands.length; ++i) { String key = keys.get(i); Expr arg = expr.fields.get(key); operands[i] = generate(arg, environment, codes, context); } int target = environment.allocate(expr.result().raw()); codes.append(Code.NewRecord(expr.result().raw(), target, operands), attributes(expr)); return target; } private int generate(Expr.Tuple expr, Environment environment, Block codes, Context context) { int[] operands = generate(expr.fields, environment, codes, context); int target = environment.allocate(expr.result().raw()); codes.append(Code.NewTuple(expr.result().raw(), target, operands), attributes(expr)); return target; } private int generate(Expr.Map expr, Environment environment, Block codes, Context context) { int[] operands = new int[expr.pairs.size() * 2]; for (int i = 0; i != expr.pairs.size(); ++i) { Pair<Expr, Expr> e = expr.pairs.get(i); operands[i << 1] = generate(e.first(), environment, codes, context); operands[(i << 1) + 1] = generate(e.second(), environment, codes, context); } int target = environment.allocate(expr.result().raw()); codes.append(Code.NewMap(expr.result().raw(), target, operands), attributes(expr)); return target; } private int generate(Expr.FieldAccess expr, Environment environment, Block codes, Context context) { int operand = generate(expr.src, environment, codes, context); int target = environment.allocate(expr.result().raw()); codes.append( Code.FieldLoad(expr.srcType.raw(), target, operand, expr.name), attributes(expr)); return target; } private int generate(Expr.New expr, Environment environment, Block codes, Context context) throws ResolveError { int operand = generate(expr.expr, environment, codes, context); int target = environment.allocate(expr.result().raw()); codes.append(Code.NewObject(expr.type.raw(), target, operand)); return target; } private int[] generate(List<Expr> arguments, Environment environment, Block codes, Context context) { int[] operands = new int[arguments.size()]; for (int i = 0; i != operands.length; ++i) { Expr arg = arguments.get(i); operands[i] = generate(arg, environment, codes, context); } return operands; } // Helpers @SuppressWarnings("incomplete-switch") private Code.BinArithKind OP2BOP(Expr.BOp bop, SyntacticElement elem, Context context) { switch (bop) { case ADD: return Code.BinArithKind.ADD; case SUB: return Code.BinArithKind.SUB; case MUL: return Code.BinArithKind.MUL; case DIV: return Code.BinArithKind.DIV; case REM: return Code.BinArithKind.REM; case RANGE: return Code.BinArithKind.RANGE; case BITWISEAND: return Code.BinArithKind.BITWISEAND; case BITWISEOR: return Code.BinArithKind.BITWISEOR; case BITWISEXOR: return Code.BinArithKind.BITWISEXOR; case LEFTSHIFT: return Code.BinArithKind.LEFTSHIFT; case RIGHTSHIFT: return Code.BinArithKind.RIGHTSHIFT; } syntaxError(errorMessage(INVALID_BINARY_EXPRESSION), context, elem); return null; } @SuppressWarnings("incomplete-switch") private Code.Comparator OP2COP(Expr.BOp bop, SyntacticElement elem, Context context) { switch (bop) { case EQ: return Code.Comparator.EQ; case NEQ: return Code.Comparator.NEQ; case LT: return Code.Comparator.LT; case LTEQ: return Code.Comparator.LTEQ; case GT: return Code.Comparator.GT; case GTEQ: return Code.Comparator.GTEQ; case SUBSET: return Code.Comparator.SUBSET; case SUBSETEQ: return Code.Comparator.SUBSETEQ; case ELEMENTOF: return Code.Comparator.ELEMOF; } syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION), context, elem); return null; } /** * The purpose of this method is to construct aliases for variables declared * as part of type patterns. For example: * * <pre> * type tup as {int x, int y} where x < y * </pre> * * Here, variables <code>x</code> and <code>y</code> are declared as part of * the type pattern, and we translate them into the aliases : $.x and $.y, * where "$" is the root variable passed as a parameter. * * @param src * @param t * @param environment */ public static void addDeclaredVariables(int root, TypePattern pattern, Type type, Environment environment, Block blk) { if(pattern instanceof TypePattern.Record) { TypePattern.Record tp = (TypePattern.Record) pattern; Type.Record tt = (Type.Record) type; for(TypePattern element : tp.elements) { String fieldName = element.var; Type fieldType = tt.field(fieldName); int target = environment.allocate(fieldType); blk.append(Code.FieldLoad(tt, target, root, fieldName)); addDeclaredVariables(target, element, fieldType, environment, blk); } } else if(pattern instanceof TypePattern.Tuple){ TypePattern.Tuple tp = (TypePattern.Tuple) pattern; Type.Tuple tt = (Type.Tuple) type; for(int i=0;i!=tp.elements.size();++i) { TypePattern element = tp.elements.get(i); Type elemType = tt.element(i); int target = environment.allocate(elemType); blk.append(Code.TupleLoad(tt, target, root, i)); addDeclaredVariables(target, element, elemType, environment, blk); } } else { // do nothing for leaf } if (pattern.var != null) { environment.put(root, pattern.var); } } @SuppressWarnings("incomplete-switch") private static Expr invert(Expr e) { if (e instanceof Expr.BinOp) { Expr.BinOp bop = (Expr.BinOp) e; Expr.BinOp nbop = null; switch (bop.op) { case AND: nbop = new Expr.BinOp(Expr.BOp.OR, invert(bop.lhs), invert(bop.rhs), attributes(e)); break; case OR: nbop = new Expr.BinOp(Expr.BOp.AND, invert(bop.lhs), invert(bop.rhs), attributes(e)); break; case EQ: nbop = new Expr.BinOp(Expr.BOp.NEQ, bop.lhs, bop.rhs, attributes(e)); break; case NEQ: nbop = new Expr.BinOp(Expr.BOp.EQ, bop.lhs, bop.rhs, attributes(e)); break; case LT: nbop = new Expr.BinOp(Expr.BOp.GTEQ, bop.lhs, bop.rhs, attributes(e)); break; case LTEQ: nbop = new Expr.BinOp(Expr.BOp.GT, bop.lhs, bop.rhs, attributes(e)); break; case GT: nbop = new Expr.BinOp(Expr.BOp.LTEQ, bop.lhs, bop.rhs, attributes(e)); break; case GTEQ: nbop = new Expr.BinOp(Expr.BOp.LT, bop.lhs, bop.rhs, attributes(e)); break; } if (nbop != null) { nbop.srcType = bop.srcType; return nbop; } } else if (e instanceof Expr.UnOp) { Expr.UnOp uop = (Expr.UnOp) e; switch (uop.op) { case NOT: return uop.mhs; } } Expr.UnOp r = new Expr.UnOp(Expr.UOp.NOT, e); r.type = Nominal.T_BOOL; return r; } /** * The attributes method extracts those attributes of relevance to WyIL, and * discards those which are only used for the wyc front end. * * @param elem * @return */ private static Collection<Attribute> attributes(SyntacticElement elem) { ArrayList<Attribute> attrs = new ArrayList<Attribute>(); attrs.add(elem.attribute(Attribute.Source.class)); return attrs; } public static final class Environment { private final HashMap<String, Integer> var2idx; private final ArrayList<Type> idx2type; public Environment() { var2idx = new HashMap<String, Integer>(); idx2type = new ArrayList<Type>(); } public Environment(Environment env) { var2idx = new HashMap<String, Integer>(env.var2idx); idx2type = new ArrayList<Type>(env.idx2type); } public int allocate(Type t) { int idx = idx2type.size(); idx2type.add(t); return idx; } public int allocate(Type t, String v) { int r = allocate(t); var2idx.put(v, r); return r; } public int size() { return idx2type.size(); } public Integer get(String v) { return var2idx.get(v); } public String get(int idx) { for (Map.Entry<String, Integer> e : var2idx.entrySet()) { int jdx = e.getValue(); if (jdx == idx) { return e.getKey(); } } return null; } public void put(int idx, String v) { var2idx.put(v, idx); } public ArrayList<Type> asList() { return idx2type; } public String toString() { return idx2type.toString() + "," + var2idx.toString(); } } @SuppressWarnings("unchecked") private <T extends Scope> T findEnclosingScope(Class<T> c) { for(int i=scopes.size()-1;i>=0;--i) { Scope s = scopes.get(i); if(c.isInstance(s)) { return (T) s; } } return null; } private abstract class Scope {} private class BreakScope extends Scope { public String label; public BreakScope(String l) { label = l; } } private class ContinueScope extends Scope { public String label; public ContinueScope(String l) { label = l; } } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package wyjc.testing; import static org.junit.Assert.fail; import java.io.*; import wyc.WycMain; import wyjc.WyjcMain; import wyjc.util.WyjcBuildTask; public class TestHarness { private static final String WYJC_PATH="../../../modules/wyjc/src/"; private static final String WYIL_PATH="../../../modules/wyil/src/"; private static String WYRT_PATH; static { // The purpose of this is to figure out what the proper name for the // wyrt file is. File file = new File("../../lib/"); for(String f : file.list()) { if(f.startsWith("wyrt-v")) { WYRT_PATH="../../lib/" + f; } } } private String sourcepath; // path to source files private String outputPath; // path to output files private String outputExtension; // the extension of output files /** * Construct a test harness object. * * @param srcPath * The path to the source files to be tested * @param outputPath * The path to the sample output files to compare against. * @param outputExtension * The extension of output files * @param verification * if true, the verifier is used. */ public TestHarness(String srcPath, String outputPath, String outputExtension) { this.sourcepath = srcPath.replace('/', File.separatorChar); this.outputPath = outputPath.replace('/', File.separatorChar); this.outputExtension = outputExtension; } /** * Compile and execute a test case, whilst comparing its output against the * sample output. The test fails if either it does not compile, or running * it does not produce the sample output. * * @param name * Name of the test to run. This must correspond to an executable * Java file in the srcPath of the same name. */ protected void runTest(String name) { String filename = sourcepath + File.separatorChar + name + ".whiley"; if (compile("-wd", sourcepath, "-wp", WYRT_PATH, filename) != 0) { fail("couldn't compile test!"); } else { String output = run(sourcepath, name); compare(output, outputPath + File.separatorChar + name + "." + outputExtension); } } /** * Compile and execute a test case with verification enabled, whilst * comparing its output against the sample output. The test fails if either * it does not compile, or running it does not produce the sample output. * Enabling verification means that the verified must pass the given files * and, hence, this is all about testing the verifier. * * @param name * Name of the test to run. This must correspond to an executable * Java file in the srcPath of the same name. */ protected void verifyRunTest(String name) { String filename = sourcepath + File.separatorChar + name + ".whiley"; if (compile("-wd", sourcepath, "-wp", WYRT_PATH, "-X", "verification:enable=true", filename) != 0) { fail("couldn't compile test!"); } else { String output = run(sourcepath, name); compare(output, outputPath + File.separatorChar + name + "." + outputExtension); } } /** * Compile a syntactically invalid test case. The expectation is that * compilation should fail with an error and, hence, the test fails if * compilation does not. * * @param name * Name of the test to run. This must correspond to an executable * Java file in the srcPath of the same name. */ protected void contextFailTest(String name) { name = sourcepath + File.separatorChar + name + ".whiley"; int r = compile("-wd", sourcepath, "-wp", WYRT_PATH, name); if (r == 0) { fail("Test compiled when it shouldn't have!"); } else if (r == WycMain.INTERNAL_FAILURE) { fail("Test caused internal failure!"); } } /** * Compile a syntactically invalid test case with verification enabled. The * expectation is that compilation should fail with an error and, hence, the * test fails if compilation does not. This differs from the contextFailTest * in that the test cases are expected to fail only in the verifier, and not * the ordinary course of things. * * @param name * Name of the test to run. This must correspond to an executable * Java file in the srcPath of the same name. */ protected void verifyFailTest(String name) { // this will need to turn on verification at some point. name = sourcepath + File.separatorChar + name + ".whiley"; int r = compile("-wd", sourcepath, "-wp", WYRT_PATH, "-X", "verification:enable=true", name); if (r == 0) { fail("Test compiled when it shouldn't have!"); } else if (r == WycMain.INTERNAL_FAILURE) { fail("Test caused internal failure!"); } } /** * Compile and execute a syntactically invalid test case with verification * disabled. Since verification is disabled, runtime checks are instead * inserted to catch constraint violations (which would otherwise be caught * by the verifier). Therefore, the expectation is that it should fail at * runtime with an assertion failure and, hence, the test fails if it * doesn't do this. * * @param name * Name of the test to run. This must correspond to an executable * Java file in the srcPath of the same name. */ protected void runtimeFailTest(String name) { String fullName = sourcepath + File.separatorChar + name + ".whiley"; if(compile("-wd",sourcepath,"-wp", WYRT_PATH,fullName) != 0) { fail("couldn't compile test!"); } else { String output = run(sourcepath,name); if(output != null) { fail("test should have failed at runtime!"); } } } private static int compile(String... args) { return new WycMain(new WyjcBuildTask(), WycMain.DEFAULT_OPTIONS).run(args); } private static String run(String path, String name) { try { // We need to have String classpath = "." + File.pathSeparator + WYIL_PATH + File.pathSeparator + WYJC_PATH; classpath = classpath.replace('/', File.separatorChar); String tmp = "java -cp " + classpath + " " + name; Process p = Runtime.getRuntime().exec(tmp, null, new File(path)); StringBuffer syserr = new StringBuffer(); StringBuffer sysout = new StringBuffer(); new StreamGrabber(p.getErrorStream(), syserr); new StreamGrabber(p.getInputStream(), sysout); int exitCode = p.waitFor(); if (exitCode != 0) { System.err.println("============================================================"); System.err.println(name); System.err.println("============================================================"); System.err.println(syserr); return null; } else { return sysout.toString(); } } catch (Exception ex) { ex.printStackTrace(); fail("Problem running compiled test"); } return null; } /** * Compare the output of executing java on the test case with a reference * file. * * @param output * This provides the output from executing java on the test case. * @param referenceFile * The full path to the reference file. This should use the * appropriate separator char for the host operating system. */ private static void compare(String output, String referenceFile) { try { BufferedReader outReader = new BufferedReader(new StringReader(output)); BufferedReader refReader = new BufferedReader(new FileReader( new File(referenceFile))); while (refReader.ready() && outReader.ready()) { String a = refReader.readLine(); String b = outReader.readLine(); if (a.equals(b)) { continue; } else { System.err.println(" > " + a); System.err.println(" < " + b); throw new Error("Output doesn't match reference"); } } String l1 = outReader.readLine(); String l2 = refReader.readLine(); if (l1 == null && l2 == null) return; do { l1 = outReader.readLine(); l2 = refReader.readLine(); if (l1 != null) { System.err.println(" < " + l1); } else if (l2 != null) { System.err.println(" > " + l2); } } while(l1 != null && l2 != null); fail("Files do not match"); } catch (Exception ex) { ex.printStackTrace(); fail(); } } static public class StreamGrabber extends Thread { private InputStream input; private StringBuffer buffer; StreamGrabber(InputStream input,StringBuffer buffer) { this.input = input; this.buffer = buffer; start(); } public void run() { try { int nextChar; // keep reading!! while ((nextChar = input.read()) != -1) { buffer.append((char) nextChar); } } catch (IOException ioe) { } } } }
package org.project.openbaton.catalogue.nfvo; import org.project.openbaton.catalogue.util.IdGenerator; import javax.persistence.*; import java.io.Serializable; import java.util.Set; @Entity public class VNFPackage implements Serializable{ @Id private String id = IdGenerator.createUUID(); @Version private int version = 0; private String name; private String extId; private String imageLink; private String scriptsLink; @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) private NFVImage image; @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) private Set<Script> scripts; public VNFPackage() { } @Override public String toString() { return "VNFPackage{" + "id='" + id + '\'' + ", version=" + version + ", name='" + name + '\'' + ", extId='" + extId + '\'' + ", imageLink='" + imageLink + '\'' + ", scriptsLink='" + scriptsLink + '\'' + ", image=" + image + ", scripts=" + scripts + '}'; } public String getImageLink() { return imageLink; } public void setImageLink(String imageLink) { this.imageLink = imageLink; } public String getScriptsLink() { return scriptsLink; } public void setScriptsLink(String scriptsLink) { this.scriptsLink = scriptsLink; } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getExtId() { return extId; } public void setExtId(String extId) { this.extId = extId; } public Set<Script> getScripts() { return scripts; } public void setScripts(Set<Script> scripts) { this.scripts = scripts; } public void setImage(NFVImage image) { this.image = image; } public NFVImage getImage() { return image; } }
package org.jboss.as.cli.handlers; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.jboss.as.cli.ArgumentValueConverter; import org.jboss.as.cli.CommandArgument; import org.jboss.as.cli.CommandContext; import org.jboss.as.cli.CommandFormatException; import org.jboss.as.cli.CommandLineCompleter; import org.jboss.as.cli.Util; import org.jboss.as.cli.impl.ArgumentWithValue; import org.jboss.as.cli.impl.ArgumentWithoutValue; import org.jboss.as.cli.impl.DefaultCompleter; import org.jboss.as.cli.impl.DefaultCompleter.CandidatesProvider; import org.jboss.as.cli.operation.OperationFormatException; import org.jboss.as.cli.operation.OperationRequestAddress; import org.jboss.as.cli.operation.CommandLineParser; import org.jboss.as.cli.operation.ParsedCommandLine; import org.jboss.as.cli.operation.impl.DefaultCallbackHandler; import org.jboss.as.cli.operation.impl.DefaultOperationRequestAddress; import org.jboss.as.cli.operation.impl.DefaultOperationRequestBuilder; import org.jboss.as.cli.parsing.ParserUtil; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.dmr.Property; /** * * @author Alexey Loubyansky */ public class GenericTypeOperationHandler extends BatchModeCommandHandler { protected final String commandName; protected final String type; protected final String idProperty; protected final OperationRequestAddress nodePath; protected final ArgumentWithValue profile; protected final ArgumentWithValue name; protected final ArgumentWithValue operation; protected final List<String> excludeOps; // help arguments protected final ArgumentWithoutValue helpProperties; protected final ArgumentWithoutValue helpCommands; // these are caching vars private final List<CommandArgument> staticArgs = new ArrayList<CommandArgument>(); private Map<String, CommandArgument> nodeProps; private Map<String, Map<String, CommandArgument>> propsByOp; public GenericTypeOperationHandler(String nodeType, String idProperty) { this(nodeType, idProperty, Arrays.asList("read-attribute", "read-children-names", "read-children-resources", "read-children-types", "read-operation-description", "read-operation-names", "read-resource", "read-resource-description", "validate-address", "write-attribute")); } public GenericTypeOperationHandler(String nodeType, String idProperty, List<String> excludeOperations) { super("generic-type-operation", true); helpArg = new ArgumentWithoutValue(this, "--help", "-h") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if(ctx.isDomainMode() && !profile.isValueComplete(ctx.getParsedCommandLine())) { return false; } return super.canAppearNext(ctx); } }; nodePath = new DefaultOperationRequestAddress(); CommandLineParser.CallbackHandler handler = new DefaultCallbackHandler(nodePath); try { ParserUtil.parseOperationRequest(nodeType, handler); } catch (CommandFormatException e) { throw new IllegalArgumentException("Failed to parse nodeType: " + e.getMessage()); } if(!nodePath.endsOnType()) { throw new IllegalArgumentException("The node path doesn't end on a type: '" + nodeType + "'"); } this.type = nodePath.getNodeType(); nodePath.toParentNode(); addRequiredPath(nodePath); this.commandName = type; this.idProperty = idProperty; this.excludeOps = excludeOperations; profile = new ArgumentWithValue(this, new DefaultCompleter(new CandidatesProvider(){ @Override public List<String> getAllCandidates(CommandContext ctx) { return Util.getNodeNames(ctx.getModelControllerClient(), null, "profile"); }}), "--profile") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if(!ctx.isDomainMode()) { return false; } return super.canAppearNext(ctx); } }; //profile.addCantAppearAfter(helpArg); operation = new ArgumentWithValue(this, new DefaultCompleter(new CandidatesProvider(){ @Override public Collection<String> getAllCandidates(CommandContext ctx) { DefaultOperationRequestAddress address = new DefaultOperationRequestAddress(); if(ctx.isDomainMode()) { final String profileName = profile.getValue(ctx.getParsedCommandLine()); if(profileName == null) { return Collections.emptyList(); } address.toNode("profile", profileName); } for(OperationRequestAddress.Node node : nodePath) { address.toNode(node.getType(), node.getName()); } address.toNode(type, "?"); Collection<String> ops = ctx.getOperationCandidatesProvider().getOperationNames(ctx, address); ops.removeAll(excludeOps); return ops; }}), 0, "--operation") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if(ctx.isDomainMode() && !profile.isValueComplete(ctx.getParsedCommandLine())) { return false; } return super.canAppearNext(ctx); } }; operation.addCantAppearAfter(helpArg); name = new ArgumentWithValue(this, new DefaultCompleter(new DefaultCompleter.CandidatesProvider() { @Override public List<String> getAllCandidates(CommandContext ctx) { ModelControllerClient client = ctx.getModelControllerClient(); if (client == null) { return Collections.emptyList(); } DefaultOperationRequestAddress address = new DefaultOperationRequestAddress(); if(ctx.isDomainMode()) { final String profileName = profile.getValue(ctx.getParsedCommandLine()); if(profile == null) { return Collections.emptyList(); } address.toNode("profile", profileName); } for(OperationRequestAddress.Node node : nodePath) { address.toNode(node.getType(), node.getName()); } return Util.getNodeNames(ctx.getModelControllerClient(), address, type); } }), (idProperty == null ? "--name" : "--" + idProperty)) { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if(ctx.isDomainMode() && !profile.isValueComplete(ctx.getParsedCommandLine())) { return false; } return super.canAppearNext(ctx); } }; name.addCantAppearAfter(helpArg); helpArg.addCantAppearAfter(name); helpProperties = new ArgumentWithoutValue(this, "--properties"); helpProperties.addRequiredPreceding(helpArg); helpProperties.addCantAppearAfter(operation); helpCommands = new ArgumentWithoutValue(this, "--commands"); helpCommands.addRequiredPreceding(helpArg); helpCommands.addCantAppearAfter(operation); helpCommands.addCantAppearAfter(helpProperties); helpProperties.addCantAppearAfter(helpCommands); staticArgs.add(helpArg); staticArgs.add(helpCommands); staticArgs.add(helpProperties); staticArgs.add(profile); staticArgs.add(name); staticArgs.add(operation); } @Override public Collection<CommandArgument> getArguments(CommandContext ctx) { ParsedCommandLine args = ctx.getParsedCommandLine(); try { if(!name.isValueComplete(args)) { return staticArgs; } } catch (CommandFormatException e) { return Collections.emptyList(); } final String op = operation.getValue(args); return loadArguments(ctx, op).values(); } private Map<String,CommandArgument> loadArguments(CommandContext ctx, String op) { if(op == null) { // list node properties if(nodeProps == null) { final List<Property> propList = getNodeProperties(ctx); final Map<String, CommandArgument> argMap = new HashMap<String, CommandArgument>(propList.size()); for(int i = 0; i < propList.size(); ++i) { final Property prop = propList.get(i); final ModelNode propDescr = prop.getValue(); if(propDescr.has("access-type") && "read-write".equals(propDescr.get("access-type").asString())) { ModelType type = null; CommandLineCompleter valueCompleter = null; ArgumentValueConverter valueConverter = ArgumentValueConverter.DEFAULT; if(propDescr.has("type")) { type = propDescr.get("type").asType(); if(ModelType.BOOLEAN == type) { valueCompleter = SimpleTabCompleter.BOOLEAN; //TODO } else if(ModelType.PROPERTY == type) { } else if(prop.getName().endsWith("properties")) { valueConverter = ArgumentValueConverter.PROPERTIES; } else if(ModelType.LIST == type) { valueConverter = ArgumentValueConverter.LIST; } } final CommandArgument arg = new ArgumentWithValue(GenericTypeOperationHandler.this, valueCompleter, valueConverter, "--" + prop.getName()); argMap.put(arg.getFullName(), arg); } } nodeProps = argMap; } return nodeProps; } else { // list operation properties if(propsByOp == null) { propsByOp = new HashMap<String, Map<String, CommandArgument>>(); } Map<String, CommandArgument> opProps = propsByOp.get(op); if(opProps == null) { final ModelNode descr; try { descr = getOperationDescription(ctx, op); } catch (IOException e1) { return Collections.emptyMap(); } if(descr == null || !descr.has("request-properties")) { opProps = Collections.emptyMap(); } else { final List<Property> propList = descr.get("request-properties").asPropertyList(); opProps = new HashMap<String,CommandArgument>(propList.size()); for (Property prop : propList) { final ModelNode propDescr = prop.getValue(); ModelType type = null; CommandLineCompleter valueCompleter = null; ArgumentValueConverter valueConverter = ArgumentValueConverter.DEFAULT; if(propDescr.has("type")) { type = propDescr.get("type").asType(); if(ModelType.BOOLEAN == type) { valueCompleter = SimpleTabCompleter.BOOLEAN; //TODO } else if(ModelType.PROPERTY == type) { } else if(prop.getName().endsWith("properties")) { valueConverter = ArgumentValueConverter.PROPERTIES; } else if(ModelType.LIST == type) { valueConverter = ArgumentValueConverter.LIST; } } final CommandArgument arg = new ArgumentWithValue(GenericTypeOperationHandler.this, valueCompleter, valueConverter, "--" + prop.getName()); opProps.put(arg.getFullName(), arg); } } propsByOp.put(op, opProps); } return opProps; } } @Override public boolean hasArgument(String name) { return true; } @Override public boolean hasArgument(int index) { return true; } public void addArgument(CommandArgument arg) { } @Override public ModelNode buildRequest(CommandContext ctx) throws CommandFormatException { final String operation = this.operation.getValue(ctx.getParsedCommandLine()); if(operation == null) { return buildWritePropertyRequest(ctx); } return buildOperationRequest(ctx, operation); } protected ModelNode buildWritePropertyRequest(CommandContext ctx) throws CommandFormatException { final String name = this.name.getValue(ctx.getParsedCommandLine(), true); ModelNode composite = new ModelNode(); composite.get("operation").set("composite"); composite.get("address").setEmptyList(); ModelNode steps = composite.get("steps"); ParsedCommandLine args = ctx.getParsedCommandLine(); final String profile; if(ctx.isDomainMode()) { profile = this.profile.getValue(args); if(profile == null) { throw new OperationFormatException("--profile argument value is missing."); } } else { profile = null; } final Map<String,CommandArgument> nodeProps = loadArguments(ctx, null); for(String argName : args.getPropertyNames()) { if(argName.equals("--profile") || this.name.getFullName().equals(argName)) { continue; } final ArgumentWithValue arg = (ArgumentWithValue) nodeProps.get(argName); if(arg == null) { throw new CommandFormatException("Unrecognized argument name '" + argName + "'"); } DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder(); if (profile != null) { builder.addNode("profile", profile); } for(OperationRequestAddress.Node node : nodePath) { builder.addNode(node.getType(), node.getName()); } builder.addNode(type, name); builder.setOperationName("write-attribute"); final String propName; if(argName.charAt(1) == '-') { propName = argName.substring(2); } else { propName = argName.substring(1); } builder.addProperty("name", propName); final String valueString = args.getPropertyValue(argName); ModelNode nodeValue = arg.getValueConverter().fromString(valueString); builder.getModelNode().get("value").set(nodeValue); steps.add(builder.buildRequest()); } return composite; } protected ModelNode buildOperationRequest(CommandContext ctx, final String operation) throws CommandFormatException { ParsedCommandLine args = ctx.getParsedCommandLine(); DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder(); if(ctx.isDomainMode()) { final String profile = this.profile.getValue(args); if(profile == null) { throw new OperationFormatException("Required argument --profile is missing."); } builder.addNode("profile", profile); } final String name = this.name.getValue(ctx.getParsedCommandLine(), true); for(OperationRequestAddress.Node node : nodePath) { builder.addNode(node.getType(), node.getName()); } builder.addNode(type, name); builder.setOperationName(operation); final Map<String, CommandArgument> argsMap = loadArguments(ctx, operation); for(String argName : args.getPropertyNames()) { if(argName.equals("--profile")) { continue; } if(argsMap == null) { if(argName.equals(this.name.getFullName())) { continue; } throw new CommandFormatException("Command '" + operation + "' is not expected to have arguments other than " + this.name.getFullName() + "."); } final ArgumentWithValue arg = (ArgumentWithValue) argsMap.get(argName); if(arg == null) { if(argName.equals(this.name.getFullName())) { continue; } throw new CommandFormatException("Unrecognized argument " + argName + " for command '" + operation + "'."); } final String propName; if(argName.charAt(1) == '-') { propName = argName.substring(2); } else { propName = argName.substring(1); } final String valueString = args.getPropertyValue(argName); ModelNode nodeValue = arg.getValueConverter().fromString(valueString); builder.getModelNode().get(propName).set(nodeValue); } return builder.buildRequest(); } protected void printHelp(CommandContext ctx) { ParsedCommandLine args = ctx.getParsedCommandLine(); try { if(helpProperties.isPresent(args)) { try { printProperties(ctx, getNodeProperties(ctx)); } catch(Exception e) { ctx.printLine("Failed to obtain the list or properties: " + e.getLocalizedMessage()); return; } return; } } catch (CommandFormatException e) { ctx.printLine(e.getLocalizedMessage()); return; } try { if(helpCommands.isPresent(args)) { printCommands(ctx); return; } } catch (CommandFormatException e) { ctx.printLine(e.getLocalizedMessage()); return; } final String operationName = operation.getValue(args); if(operationName == null) { printNodeDescription(ctx); return; } try { ModelNode result = getOperationDescription(ctx, operationName); if(!result.hasDefined("description")) { ctx.printLine("Operation description is not available."); return; } final StringBuilder buf = new StringBuilder(); buf.append("\nDESCRIPTION:\n\n"); buf.append(result.get("description").asString()); ctx.printLine(buf.toString()); if(result.hasDefined("request-properties")) { printProperties(ctx, result.get("request-properties").asPropertyList()); } else { printProperties(ctx, Collections.<Property>emptyList()); } } catch (Exception e) { } } protected void printProperties(CommandContext ctx, List<Property> props) { final Map<String, StringBuilder> requiredProps = new LinkedHashMap<String,StringBuilder>(); requiredProps.put(this.name.getFullName(), new StringBuilder().append("Required argument in commands which identifies the instance to execute the command against.")); final Map<String, StringBuilder> optionalProps = new LinkedHashMap<String, StringBuilder>(); String accessType = null; for (Property attr : props) { final ModelNode value = attr.getValue(); // filter metrics if (value.has("access-type")) { accessType = value.get("access-type").asString(); // if("metric".equals(accessType)) { // continue; } final boolean required = value.hasDefined("required") ? value.get("required").asBoolean() : false; final StringBuilder descr = new StringBuilder(); final String type = value.has("type") ? value.get("type").asString() : "no type info"; if (value.hasDefined("description")) { descr.append('('); descr.append(type); if(accessType != null) { descr.append(',').append(accessType); } descr.append(") "); descr.append(value.get("description").asString()); } else if(descr.length() == 0) { descr.append("no description."); } if(required) { if(idProperty != null && idProperty.equals(attr.getName())) { if(descr.charAt(descr.length() - 1) != '.') { descr.append('.'); } requiredProps.get(this.name.getFullName()).insert(0, ' ').insert(0, descr.toString()); } else { requiredProps.put("--" + attr.getName(), descr); } } else { optionalProps.put("--" + attr.getName(), descr); } } ctx.printLine("\n"); if(accessType == null) { ctx.printLine("REQUIRED ARGUMENTS:\n"); } for(String argName : requiredProps.keySet()) { final StringBuilder prop = new StringBuilder(); prop.append(' ').append(argName); int spaces = 28 - prop.length(); do { prop.append(' '); --spaces; } while(spaces >= 0); prop.append("- ").append(requiredProps.get(argName)); ctx.printLine(prop.toString()); } if(!optionalProps.isEmpty()) { if(accessType == null ) { ctx.printLine("\n\nOPTIONAL ARGUMENTS:\n"); } for(String argName : optionalProps.keySet()) { final StringBuilder prop = new StringBuilder(); prop.append(' ').append(argName); int spaces = 28 - prop.length(); do { prop.append(' '); --spaces; } while(spaces >= 0); prop.append("- ").append(optionalProps.get(argName)); ctx.printLine(prop.toString()); } } } protected void printNodeDescription(CommandContext ctx) { ModelNode request = initRequest(ctx); if(request == null) { return; } request.get("operation").set("read-resource-description"); try { ModelNode result = ctx.getModelControllerClient().execute(request); if(!result.hasDefined("result")) { ctx.printLine("Node description is not available."); return; } result = result.get("result"); if(!result.hasDefined("description")) { ctx.printLine("Node description is not available."); return; } ctx.printLine(result.get("description").asString()); } catch (Exception e) { } } protected void printCommands(CommandContext ctx) { ModelNode request = initRequest(ctx); if(request == null) { return; } request.get("operation").set("read-operation-names"); try { ModelNode result = ctx.getModelControllerClient().execute(request); if(!result.hasDefined("result")) { ctx.printLine("Operation names aren't available."); return; } final List<String> list = Util.getList(result); list.removeAll(this.excludeOps); list.add("To read the description of a specific command execute '" + this.commandName + " command_name --help'."); for(String name : list) { ctx.printLine(name); } } catch (Exception e) { } } protected List<Property> getNodeProperties(CommandContext ctx) { ModelNode request = initRequest(ctx); if(request == null) { return Collections.emptyList(); } request.get("operation").set("read-resource-description"); ModelNode result; try { result = ctx.getModelControllerClient().execute(request); } catch (IOException e) { return Collections.emptyList(); } if(!result.hasDefined("result")) { return Collections.emptyList(); } result = result.get("result"); if(!result.hasDefined("attributes")) { return Collections.emptyList(); } return result.get("attributes").asPropertyList(); } protected ModelNode getOperationDescription(CommandContext ctx, String operationName) throws IOException { ModelNode request = initRequest(ctx); if(request == null) { return null; } request.get("operation").set("read-operation-description"); request.get("name").set(operationName); ModelNode result = ctx.getModelControllerClient().execute(request); if (!result.hasDefined("result")) { return null; } return result.get("result"); } protected ModelNode initRequest(CommandContext ctx) { ModelNode request = new ModelNode(); ModelNode address = request.get("address"); if(ctx.isDomainMode()) { final String profileName = profile.getValue(ctx.getParsedCommandLine()); if(profile == null) { ctx.printLine("--profile argument is required to get the node description."); return null; } address.add("profile", profileName); } for(OperationRequestAddress.Node node : nodePath) { address.add(node.getType(), node.getName()); } address.add(type, "?"); return request; } }
package org.llama.llama.services; import android.content.Context; import android.util.Log; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.MutableData; import com.google.firebase.database.Query; import com.google.firebase.database.Transaction; import com.google.firebase.database.ValueEventListener; import com.google.firebase.iid.FirebaseInstanceId; import org.jdeferred.Deferred; import org.jdeferred.Promise; import org.jdeferred.impl.DeferredObject; import org.llama.llama.MyApp; import org.llama.llama.model.Country; import org.llama.llama.model.User; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; public class UserService implements IUserService { private static final String TAG = "UserService"; private static Map<String, User> userCache = new HashMap<>(); private static Map<String, Promise> userRequestCache = new HashMap<>(); private static final String cacheFile = "UserServiceCache.bin"; public UserService() { Map<String, User> userCache = StorageService.readFromFile(MyApp.getAppContext(), cacheFile); if (userCache != null) { UserService.userCache = userCache; } } @Override public String getCurrentUserId() { return FirebaseAuth.getInstance().getCurrentUser().getUid(); } @Override public synchronized Promise getUserInfo(final String userId) { if (userRequestCache.containsKey(userId)) { return userRequestCache.get(userId); } final Deferred deferred = new DeferredObject(); final Promise promise = deferred.promise(); userRequestCache.put(userId, promise); User user = userCache.get(userId); if (user == null) { final FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference ref = database.getReference().child("users").child(userId); ref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { User user = dataSnapshot.getValue(User.class); user.setId(userId); // userCache.put(userId, user); updateUserCache(user); deferred.resolve(user); } @Override public void onCancelled(DatabaseError databaseError) { userRequestCache.remove(userId); deferred.reject(null); } }); } else { deferred.resolve(user); } return promise; } public synchronized void updateUserCache(User user) { userCache.put(user.getId(), user); // TODO probably make async call to storageService StorageService.writeToFile(MyApp.getAppContext(), cacheFile, userCache); } @Override public void updateFirebaseInstanceIdToken(String token) { if (FirebaseAuth.getInstance().getCurrentUser() == null) { return; } final FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference ref = database.getReference().child("users").child(getCurrentUserId()).child("firebaseInstanceIdToken"); ref.setValue(token); } // public void updateProfile(String name, String photoUri){ // FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); // UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder() // .setDisplayName(name) // .setPhotoUri(Uri.parse(photoUri)) // .build(); // user.updateProfile(profileUpdates) // .addOnCompleteListener(new OnCompleteListener<Void>() { // @Override // public void onComplete(@NonNull Task<Void> task) { // if (task.isSuccessful()) { // Log.d(TAG, "User profile updated."); private <T> String updateUserProperty(String property, T value) { String userId = getCurrentUserId(); FirebaseDatabase.getInstance().getReference() .child("users") .child(userId) .child(property) .setValue(value); return userId; } @Override public void updateCurrentUserName(final String username, final Runnable alreadyTakenAction) { final DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference().child("users"); Query query = usersRef.orderByChild("username").startAt(username).endAt(username); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.getChildrenCount() == 1) { Log.d("SETTINGS", "Username already existed!"); alreadyTakenAction.run(); return; } String userId = getCurrentUserId(); usersRef.child(userId) .child("username") .setValue(username); User user = userCache.get(userId); if (user != null) user.setUsername(username); } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override public void updateCurrentUserDisplayName(String displayName) { User user = userCache.get(updateUserProperty("displayname", displayName)); if (user != null) user.setName(displayName); } @Override public void updateCurrentUserMood(String mood) { User user = userCache.get(updateUserProperty("mood", mood)); if (user != null) user.setMood(mood); } @Override public void updateCurrentUserEmail(String email) { User user = userCache.get(updateUserProperty("email", email)); if (user != null) user.setEmail(email); } @Override public void updateCurrentUserCountry(String countryId) { User user = userCache.get(updateUserProperty("country", countryId)); if (user != null) user.setCountry(countryId); } @Override public void updateCurrentUserDefaultLanguage(String defaultLanguageId) { User user = userCache.get(updateUserProperty("defaultLanguage", defaultLanguageId)); if (user != null) user.setDefaultLanguage(defaultLanguageId); } @Override public void updateCurrentUserLanguages(final Set<String> languages) { Map<String, Object> langs = new HashMap<>(); for (String lang : languages) { langs.put(lang, true); } User user = userCache.get(updateUserProperty("languages", langs)); if (user != null) user.setLanguages(langs); } @Override public void updateCurrentUserNotifications(Boolean notifications) { User user = userCache.get(updateUserProperty("notifications", notifications)); if (user != null) user.setNotifications(notifications); } @Override public void createUserIfNotExists() { final FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference ref = database.getReference().child("users").child(getCurrentUserId()); ref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.getValue() == null) { User user = new User(); user.setFirebaseInstanceIdToken(FirebaseInstanceId.getInstance().getToken()); FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); String email = firebaseUser.getEmail(); user.setEmail(email); String displayName = firebaseUser.getDisplayName(); user.setName(displayName == null ? email : displayName); user.setMood(""); user.setNotifications(true); user.setUsername(firebaseUser.getEmail()); user.setLocation(0.0, 0.0); final String phoneLanguage = Locale.getDefault().getLanguage(); final String phoneCountry = Locale.getDefault().getCountry(); user.setLanguages(new HashMap<String, Object>() { { put(phoneLanguage, true); } }); user.setDefaultLanguage(phoneLanguage); user.setCountry(phoneCountry); // save user database.getReference().child("users").child(getCurrentUserId()).setValue(user); }else{ updateFirebaseInstanceIdToken(FirebaseInstanceId.getInstance().getToken()); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } }
package org.croudtrip.fragments.offer; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.location.Location; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewManager; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import com.google.maps.android.PolyUtil; import org.croudtrip.Constants; import org.croudtrip.R; import org.croudtrip.api.TripsResource; import org.croudtrip.api.directions.NavigationResult; import org.croudtrip.api.directions.Route; import org.croudtrip.api.directions.RouteLocation; import org.croudtrip.api.trips.JoinTripRequest; import org.croudtrip.api.trips.JoinTripStatus; import org.croudtrip.api.trips.TripOffer; import org.croudtrip.api.trips.TripOfferDescription; import org.croudtrip.api.trips.TripOfferUpdate; import org.croudtrip.api.trips.UserWayPoint; import org.croudtrip.fragments.OfferTripFragment; import org.croudtrip.fragments.SubscriptionFragment; import org.croudtrip.location.LocationUpdater; import org.croudtrip.trip.MyTripDriverPassengersAdapter; import org.croudtrip.utils.DefaultTransformer; import java.util.List; import java.util.NoSuchElementException; import javax.inject.Inject; import it.neokree.materialnavigationdrawer.MaterialNavigationDrawer; import it.neokree.materialnavigationdrawer.elements.MaterialSection; import roboguice.inject.InjectView; import rx.Observable; import rx.Subscriber; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; import timber.log.Timber; /** * This class shows a screen for the driver after he has offered a trip and hence is currently * already on his way. He is shown a map, his earnings and the passengers that he has accepted. * * @author Frederik Simon, Vanessa Lange */ public class MyTripDriverFragment extends SubscriptionFragment { // // Route/Navigation public static final String ARG_ACTION = "ARG_ACTION"; public static final String ACTION_LOAD = "ACTION_LOAD"; public static final String ACTION_CREATE = "ACTION_CREATE"; private GoogleMap googleMap; private NfcAdapter nfcAdapter; private NdefMessage ndefMessage; private long offerID = -1; // Passengers list private MyTripDriverPassengersAdapter adapter; @InjectView(R.id.rv_my_trip_driver_passengers) private RecyclerView recyclerView; @InjectView(R.id.pb_my_trip_progressBar) private ProgressBar progressBar; @InjectView(R.id.iv_transparent_image) private ImageView transparentImageView; @Inject private TripsResource tripsResource; @Inject private LocationUpdater locationUpdater; private Button finishButton; // Detect if a passenger cancels his trip or has reached his destination private BroadcastReceiver passengersChangeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Load the whole offer incl. passengers etc. again loadOffer(); } }; // @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); setHasOptionsMenu(true); nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); NdefRecord ndefRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], null); ndefMessage = new NdefMessage(new NdefRecord[] { ndefRecord }); return inflater.inflate(R.layout.fragment_my_trip_driver, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Fill the passengers list View header = view.findViewById(R.id.ll_my_trip_driver_info); adapter = new MyTripDriverPassengersAdapter(header); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); setupCancelButton(header); setupFinishButton(header); // Get the route to display it on the map SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager() .findFragmentById(R.id.f_my_trip_driver_map); // TODO: Make it asynchronously googleMap = mapFragment.getMap(); Bundle bundle = getArguments(); if (bundle == null) { bundle = new Bundle(); } String action = bundle.getString(ARG_ACTION, ACTION_LOAD); if (action.equals(ACTION_CREATE)) { Timber.d("Create Offer"); createOffer(bundle); } else { Timber.d("Load Offer"); loadOffer(); } transparentImageView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: recyclerView.requestDisallowInterceptTouchEvent(true); return false; case MotionEvent.ACTION_UP: recyclerView.requestDisallowInterceptTouchEvent(false); return true; case MotionEvent.ACTION_MOVE: recyclerView.requestDisallowInterceptTouchEvent(true); return false; default: return true; } } }); // Remove the header from the layout. Otherwise it exists twice ((ViewManager) view).removeView(header); } @Override public void onResume() { super.onResume(); if (nfcAdapter != null) { nfcAdapter.setNdefPushMessage(ndefMessage, getActivity()); } // Get notified if a passenger cancels his trip or has reached his destination IntentFilter filter = new IntentFilter(); filter.addAction(Constants.EVENT_PASSENGER_CANCELLED_TRIP); filter.addAction(Constants.EVENT_PASSENGER_REACHED_DESTINATION); LocalBroadcastManager.getInstance(getActivity().getApplicationContext()) .registerReceiver(passengersChangeReceiver, filter); } @Override public void onPause() { super.onPause(); LocalBroadcastManager.getInstance(getActivity().getApplicationContext()) .unregisterReceiver(passengersChangeReceiver); } private void setupCancelButton(View header) { (header.findViewById(R.id.btn_my_trip_driver_cancel_trip)) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { subscriptions.add(tripsResource.getOffers(false) .compose(new DefaultTransformer<List<TripOffer>>()) .flatMap(new Func1<List<TripOffer>, Observable<TripOffer>>() { @Override public Observable<TripOffer> call(List<TripOffer> tripOffers) { // Cancel all the offers for the time being to be changed to // get the specific offer at a later stage if (!tripOffers.isEmpty()) for (int i = 0; i < tripOffers.size(); i++) cancelTripOffer(tripOffers.get(i).getId()); return Observable.just(tripOffers.get(0)); } }) .subscribe(new Action1<TripOffer>() { @Override public void call(TripOffer offer) { } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { Timber.e(throwable.getMessage()); } }) ); } }); } private void setupFinishButton(View header) { finishButton = ((Button) (header.findViewById(R.id.btn_my_trip_driver_finish_trip))); finishButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Tell the server to finish this trip subscriptions.add( tripsResource.updateOffer(offerID, TripOfferUpdate.createFinishUpdate()) .compose(new DefaultTransformer<TripOffer>()) .subscribe(new Action1<TripOffer>() { @Override public void call(TripOffer offer) { // After the server has been contacted successfully, clean // up the SharedPref and show "Offer Trip" screen again removeRunningTripOfferState(); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { Timber.i("Error when finishing trip with ID " + offerID + ": " + throwable.getMessage()); Toast.makeText(getActivity(), "Error: " + throwable.getMessage(), Toast.LENGTH_LONG).show(); } })); } }); } /** * Downloads the current offer and processes its information with the {@link LoadOfferSubscriber} */ private synchronized void loadOffer() { subscriptions.add(tripsResource.getActiveOffers() .compose(new DefaultTransformer<List<TripOffer>>()) .flatMap(new Func1<List<TripOffer>, Observable<TripOffer>>() { @Override public Observable<TripOffer> call(List<TripOffer> tripOffers) { if (tripOffers.isEmpty()) { // Inform user String errorMsg = getString(R.string.navigation_error_no_offer); Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_LONG).show(); removeRunningTripOfferState(); throw new NoSuchElementException(errorMsg); } return Observable.just(tripOffers.get(0)); } }).subscribe(new LoadOfferSubscriber())); } private void loadPassengers() { subscriptions.add(tripsResource.getJoinRequests(false) .compose(new DefaultTransformer<List<JoinTripRequest>>()) .subscribe(new ImportantPassengersSubscriber()) ); } private void removeRunningTripOfferState() { SharedPreferences prefs = getActivity().getSharedPreferences(Constants.SHARED_PREF_FILE_PREFERENCES, Context.MODE_PRIVATE); prefs.edit().remove(Constants.SHARED_PREF_KEY_RUNNING_TRIP_OFFER).apply(); // Change "My Trip" (driver) to "Offer Trip" in navigation drawer MaterialNavigationDrawer drawer = ((MaterialNavigationDrawer) getActivity()); // Find "last" "My Trip", so we don't accidentally rename the join-trip-my trip List<MaterialSection> sections = drawer.getSectionList(); MaterialSection section = null; for (MaterialSection s : sections) { if (s.getTitle().equals(getString(R.string.menu_my_trip))) { section = s; } } section.setTitle(getString(R.string.menu_offer_trip)); // The next fragment shows the "Offer trip" screen drawer.setFragment(new OfferTripFragment(), getString(R.string.menu_offer_trip)); } private void generateRouteOnMap(TripOffer offer, NavigationResult navigationResult) { // only one route will be shown (old route will be deleted googleMap.clear(); // Show route information on the map googleMap.addPolyline(new PolylineOptions().addAll(PolyUtil.decode(navigationResult.getRoute().getPolyline()))); googleMap.setMyLocationEnabled(true); for( UserWayPoint userWp : navigationResult.getUserWayPoints() ){ if( !userWp.getUser().equals(offer.getDriver()) ){ googleMap.addMarker( new MarkerOptions() .position( new LatLng( userWp.getLocation().getLat(), userWp.getLocation().getLng())) .icon(BitmapDescriptorFactory.fromResource( R.drawable.ic_marker )) .anchor(0.5f, 0.5f) .flat(true) ); } } // Move camera to current position Location location = locationUpdater.getLastLocation(); if (location == null) return; LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10); googleMap.animateCamera(cameraUpdate); } private void createOffer(Bundle arguments) { int maxDiversion = arguments.getInt("maxDiversion"); int pricePerKilometer = arguments.getInt("pricePerKilometer"); double fromLat = arguments.getDouble("fromLat"); double fromLng = arguments.getDouble("fromLng"); double toLat = arguments.getDouble("toLat"); double toLng = arguments.getDouble("toLng"); long vehicleId = arguments.getLong("vehicle_id"); TripOfferDescription tripOffer = new TripOfferDescription( new RouteLocation(fromLat, fromLng), new RouteLocation(toLat, toLng), maxDiversion * 1000L, pricePerKilometer, vehicleId); tripsResource.addOffer(tripOffer) .compose(new DefaultTransformer<TripOffer>()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<TripOffer>() { @Override public void call(TripOffer tripOffer) { // SUCCESS Timber.d("Your offer was successfully sent to the server"); offerID = tripOffer.getId(); // show route information on the map generateRouteOnMap( tripOffer, NavigationResult.createNavigationResultForDriverRoute( tripOffer )); loadPassengers(); // Remember that a trip was offered to show "My Trip" instead of "Offer Trip" // in the Navigation drawer getActivity().getSharedPreferences(Constants.SHARED_PREF_FILE_PREFERENCES, Context.MODE_PRIVATE) .edit().putBoolean(Constants.SHARED_PREF_KEY_RUNNING_TRIP_OFFER, true).apply(); progressBar.setVisibility(View.GONE); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { // ERROR Timber.e(throwable.getMessage()); progressBar.setVisibility(View.GONE); // Inform user Toast.makeText(getActivity(), getString(R.string.offer_trip_failed), Toast.LENGTH_LONG).show(); removeRunningTripOfferState(); } }); } private void cancelTripOffer(final long id) { Subscription subscription = tripsResource.updateOffer(id, TripOfferUpdate.createCancelUpdate()) .compose(new DefaultTransformer<TripOffer>()) .subscribe(new Action1<TripOffer>() { @Override public void call(TripOffer offer) { // After the server has been contacted successfully, clean up the SharedPref // and show "Offer Trip" screen again removeRunningTripOfferState(); Toast.makeText(getActivity(), "Trip with id: " + id + " was canceled!", Toast.LENGTH_SHORT).show(); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { Timber.i("Error when cancelling trip with ID " + id + " : " + throwable.getMessage()); Toast.makeText(getActivity(), "Error: " + throwable.getMessage(), Toast.LENGTH_LONG).show(); } }); subscriptions.add(subscription); } // /** * This Subscriber loads the current route on the map and load the passengers with the help of * {@link ImportantPassengersSubscriber} */ private class LoadOfferSubscriber extends Subscriber<TripOffer> { @Override public void onNext(final TripOffer offer) { if (offer == null) { throw new NoSuchElementException(getString(R.string.navigation_error_no_offer)); } Timber.d("Received Offer with ID " + offer.getId()); // Remember the offerID for later and load the passengers for this offer offerID = offer.getId(); loadPassengers(); // Load the Route tripsResource.computeNavigationResultForOffer(offerID) .compose(new DefaultTransformer<NavigationResult>()) .subscribe(new Action1<NavigationResult>() { @Override public void call(NavigationResult navigationResult) { if (navigationResult == null) { throw new NoSuchElementException("No route available"); } generateRouteOnMap( offer, navigationResult ); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { onError(throwable); } } ); } @Override public void onCompleted() { progressBar.setVisibility(View.GONE); } @Override public void onError(Throwable throwable) { progressBar.setVisibility(View.GONE); Timber.e(throwable.getMessage()); Toast.makeText(getActivity(), getString(R.string.load_trip_failed), Toast.LENGTH_LONG).show(); } } /** * This Subscriber checks if there are still "important" passengers to take care of. That is, * e.g. there are still passengers sitting in the car or there are still passengers accepted. * If there are none, the driver may click the finishButton. Furthermore, all * relevant passengers (all that were not declined or canceled), will be shown in the RecyclerView-list. */ private class ImportantPassengersSubscriber extends Subscriber<List<JoinTripRequest>> { @Override public synchronized void onNext(List<JoinTripRequest> joinTripRequests) { // Only allow finish if there are no passengers in the car or accepted boolean allowFinish = true; for (JoinTripRequest joinTripRequest : joinTripRequests) { // TODO: Filter already on server if (joinTripRequest.getOffer().getId() != offerID) { continue; } JoinTripStatus status = joinTripRequest.getStatus(); if (status != JoinTripStatus.DRIVER_DECLINED && status != JoinTripStatus.PASSENGER_ACCEPTED) { if (status == JoinTripStatus.PASSENGER_CANCELLED || status == JoinTripStatus.DRIVER_CANCELLED) { // Remove any cancelled passengers from the adapter adapter.removeRequest(joinTripRequest.getId()); } else if (status == JoinTripStatus.DRIVER_ACCEPTED || status == JoinTripStatus.PASSENGER_IN_CAR || status == JoinTripStatus.PASSENGER_AT_DESTINATION){ // Simply update (or implicitly add) this passenger request adapter.updateRequest(joinTripRequest); if (status == JoinTripStatus.DRIVER_ACCEPTED || status == JoinTripStatus.PASSENGER_IN_CAR) { Timber.d("There is still an important passenger: " + status); allowFinish = false; } } } } // Dis-/Allow the driver to finish the trip finishButton.setEnabled(allowFinish); adapter.updateEarnings(); } @Override public void onCompleted() { } @Override public void onError(Throwable e) { Timber.e("Receiving Passengers (JoinTripRequest) failed:\n" + e.getMessage()); Toast.makeText(getActivity(), getString(R.string.load_passengers_failed), Toast.LENGTH_LONG).show(); } } }
package org.jetel.graph; import java.io.*; import java.util.*; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import javax.xml.parsers.*; import org.xml.sax.SAXParseException; import org.jetel.util.FileUtils; import org.jetel.metadata.DataRecordMetadata; import org.jetel.metadata.DataRecordMetadataXMLReaderWriter; import org.jetel.component.ComponentFactory; import org.jetel.database.DBConnection; import org.jetel.util.PropertyRefResolver; import java.util.logging.Logger; /** * Helper class which reads transformation graph definition from XML data * * The XML DTD describing the internal structure is as follows: * * <pre> * &lt;!ELEMENT Graph (Global , Phase+)&gt; * &lt;!ATTLIST Graph * name ID #REQUIRED &gt; * * &lt;!ELEMENT Global (Metadata+, DBConnection*)&gt; * * &lt;!ELEMENT Metadata (#PCDATA)&gt; * &lt;!ATTLIST Metadata * id ID #REQUIRED * fileURL CDATA #REQUIRED &gt; * * &lt;!ELEMENT DBConnection (#PCDATA)&gt; * &lt;!ATTLIST DBConnection * id ID #REQUIRED * dbDriver CDATA #REQUIRED * dbURL CDATA #REQUIRED * user CDATA * password CDATA &gt; * * &lt;!ELEMENT Phase (Node+ , Edge+)&gt; * &lt;!ATTLIST Phase * number NMTOKEN #REQUIRED&gt; * * &lt;!ELEMENT Node (#PCDATA)&gt; * &lt;!ATTLIST Node * type NMTOKEN #REQUIRED * id ID #REQUIRED&gt; * * &lt;!ELEMENT Edge (#PCDATA)&gt; * &lt;!ATTLIST Edge * id ID #REQUIRED * metadata NMTOKEN #REQUIRED * fromNode NMTOKEN #REQUIRED * toNode NMTOKEN #REQUIRED&gt; * * * </pre> * Node & port specified in Edge element (fromNode & toNode attributes) must comply with following pattern: <br> * * <i>&lt;Node ID&gt;</i><b>:</b><i>&lt;Port Number&gt;</i><br><br> * * Example: * <pre> * &lt;Graph name="MyTransformation"&gt; * &lt;Global&gt; * &lt;Metadata id="DataTypeA" fileURL="$HOME/myMetadata/dataTypeA.xml"/&gt; * &lt;Metadata id="DataTypeB" fileURL="$HOME/myMetadata/dataTypeB.xml"/&gt; * &lt;/Global&gt; * &lt;Phase number="0"&gt; * &lt;Node id="INPUT" type="DELIMITED_DATA_READER" fileURL="c:\projects\jetel\pins.ftdglacc.dat" /&gt; * &lt;Node id="COPY" type="SIMPLE_COPY"/&gt; * &lt;Node id="OUTPUT" type="DELIMITED_DATA_WRITER" append="false" fileURL="c:\projects\jetel\pins.ftdglacc.dat.out" /&gt; * &lt;Edge id="INEDGE" fromNode="INPUT:0" toNode="COPY:0" metadata="InMetadata"/&gt; * &lt;Edge id="OUTEDGE" fromNode="COPY:0" toNode="OUTPUT:0" metadata="InMetadata"/&gt; * &lt;/Phase&gt; * &lt;/Graph&gt; * </pre> * * @author dpavlis * @since May 21, 2002 */ public class TransformationGraphXMLReaderWriter { private final static String GRAPH_ELEMENT = "Graph"; private final static String GLOBAL_ELEMENT = "Global"; private final static String NODE_ELEMENT = "Node"; private final static String EDGE_ELEMENT = "Edge"; private final static String METADATA_ELEMENT = "Metadata"; private final static String PHASE_ELEMENT = "Phase"; private final static String DBCONNECTION_ELEMENT = "DBConnection"; private final static int ALLOCATE_MAP_SIZE=64; /** * Default parser name. * * @since May 21, 2002 */ //not needed any more private final static String DEFAULT_PARSER_NAME = ""; private static final boolean validation = false; private static final boolean ignoreComments = true; private static final boolean ignoreWhitespaces = true; private static final boolean putCDATAIntoText = false; private static final boolean createEntityRefs = false; private static TransformationGraphXMLReaderWriter graphXMLReaderWriter = new TransformationGraphXMLReaderWriter(); private static Logger logger = Logger.getLogger("org.jetel.graph"); /** *Constructor for the TransformationGraphXMLReaderWriter object * * @since May 24, 2002 */ private TransformationGraphXMLReaderWriter() { } /** *Constructor for the read object * * @param in Description of Parameter * @param graph Description of Parameter * @return Description of the Returned Value * @since May 21, 2002 */ public boolean read(TransformationGraph graph, InputStream in) { Document document; Iterator colIterator; Map metadata = new HashMap(ALLOCATE_MAP_SIZE); List phases = new LinkedList(); Map allNodes = new LinkedHashMap(ALLOCATE_MAP_SIZE); Map edges = new HashMap(ALLOCATE_MAP_SIZE); // delete all Nodes & Edges possibly held by TransformationGraph graph.deleteEdges(); graph.deleteNodes(); graph.deletePhases(); graph.deleteDBConnections(); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); // Optional: set various configuration options dbf.setValidating(validation); dbf.setIgnoringComments(ignoreComments); dbf.setIgnoringElementContentWhitespace(ignoreWhitespaces); dbf.setCoalescing(putCDATAIntoText); dbf.setExpandEntityReferences(!createEntityRefs); DocumentBuilder db = dbf.newDocumentBuilder(); document = db.parse(new BufferedInputStream(in)); document.normalize(); }catch(SAXParseException ex){ System.err.print(ex.getMessage()); System.err.println(" --> on line "+ex.getLineNumber()+" row "+ex.getColumnNumber()); return false; }catch (ParserConfigurationException ex) { System.err.println(ex.getMessage()); return false; }catch (Exception ex) { System.err.println(ex.getMessage()); return false; } try { // process document // get graph name NodeList graphElement = document.getElementsByTagName(GRAPH_ELEMENT); org.w3c.dom.NamedNodeMap grfAttributes = graphElement.item(0).getAttributes(); graph.setName(grfAttributes.getNamedItem("name").getNodeValue()); //create metadata NodeList metadataElements = document.getElementsByTagName(METADATA_ELEMENT); instantiateMetadata(metadataElements, metadata); NodeList phaseElements = document.getElementsByTagName(PHASE_ELEMENT); instantiatePhases(phaseElements, phases,allNodes); NodeList edgeElements = document.getElementsByTagName(EDGE_ELEMENT); instantiateEdges(edgeElements, edges, metadata, allNodes); NodeList dbConnectionElements = document.getElementsByTagName(DBCONNECTION_ELEMENT); instantiateDBConnections(dbConnectionElements, graph); } catch (Exception ex) { ex.printStackTrace(System.err); return false; } // register all PHASEs, NODEs & EDGEs within transformation graph; colIterator = phases.iterator(); while (colIterator.hasNext()) { graph.addPhase((org.jetel.graph.Phase) colIterator.next()); } colIterator = allNodes.values().iterator(); while (colIterator.hasNext()) { Node node=(org.jetel.graph.Node) colIterator.next(); graph.addNode(node,node.getPhase()); } colIterator = edges.values().iterator(); while (colIterator.hasNext()) { graph.addEdge((org.jetel.graph.Edge) colIterator.next()); } return true; } /** * Description of the Method * * @param metadataElements Description of Parameter * @param metadata Description of Parameter * @exception IOException Description of Exception * @since May 24, 2002 */ private void instantiateMetadata(NodeList metadataElements, Map metadata) throws IOException { org.w3c.dom.NamedNodeMap attributes; String metadataID; String fileURL; DataRecordMetadataXMLReaderWriter metadataXMLRW = new DataRecordMetadataXMLReaderWriter(); DataRecordMetadata recordMetadata; PropertyRefResolver refResolver=new PropertyRefResolver(); // loop through all Metadata elements & create appropriate Metadata objects for (int i = 0; i < metadataElements.getLength(); i++) { attributes = metadataElements.item(i).getAttributes(); // process metadata element attributes "id" & "fileURL" metadataID = attributes.getNamedItem("id").getNodeValue(); fileURL = refResolver.resolveRef(attributes.getNamedItem("fileURL").getNodeValue()); if ((metadataID != null) && (fileURL != null)) { recordMetadata=metadataXMLRW.read( new BufferedInputStream(new FileInputStream(FileUtils.getFullPath(fileURL)))); if (recordMetadata==null){ logger.severe("Error when reading/parsing record metadata definition file: "+fileURL); throw new RuntimeException("Can't parse metadata: "+metadataID); }else{ if (metadata.put(metadataID, recordMetadata)!=null){ throw new RuntimeException("Metadata "+metadataID+" already defined - duplicate ID detected!"); } } } else { throw new RuntimeException("Attributes missing"); } } // we successfully instantiated all metadata } private void instantiatePhases(NodeList phaseElements, List phases,Map allNodes) { org.w3c.dom.NamedNodeMap attributes; org.jetel.graph.Phase phase; String phaseNum; NodeList nodeElements; // loop through all Node elements & create appropriate Metadata objects for (int i = 0; i < phaseElements.getLength(); i++) { attributes = phaseElements.item(i).getAttributes(); // process Phase element attribute "number" phaseNum = attributes.getNamedItem("number").getNodeValue(); if (phaseNum != null){ phase=new Phase(Integer.parseInt(phaseNum)); phases.add(phase); } else { throw new RuntimeException("Attribute \"number\" missing for phase"); } // get all nodes defined in this phase and instantiate them // we expect that all childern of phase are Nodes //phaseElements.item(i).normalize(); nodeElements=phaseElements.item(i).getChildNodes(); instantiateNodes(phase.getPhaseNum(),nodeElements,allNodes); } } /** * Description of the Method * * @param nodeElements Description of Parameter * @param nodes Description of Parameter * @since May 24, 2002 */ private void instantiateNodes(int phaseNum,NodeList nodeElements, Map nodes) { org.w3c.dom.NamedNodeMap attributes; org.jetel.graph.Node graphNode; String nodeType; String nodeID; // loop through all Node elements & create appropriate Metadata objects for (int i = 0; i < nodeElements.getLength(); i++) { if (NODE_ELEMENT.compareToIgnoreCase(nodeElements.item(i).getNodeName())!=0){ continue; } attributes = nodeElements.item(i).getAttributes(); // process Node element attributes "id" & "type" nodeID = attributes.getNamedItem("id").getNodeValue(); nodeType = attributes.getNamedItem("type").getNodeValue(); if ((nodeID != null) && (nodeType != null)) { graphNode = ComponentFactory.createComponent(nodeType, nodeElements.item(i)); graphNode.setPhase(phaseNum); if (graphNode != null) { if (nodes.put(nodeID, graphNode)!=null){ throw new RuntimeException("Duplicate NodeID detected: "+nodeID); } } else { throw new RuntimeException("Error when creating Component type :" + nodeType); } } else { throw new RuntimeException("Attribute missing"); } } } /** * Description of the Method * * @param edgeElements Description of Parameter * @param edges Description of Parameter * @param metadata Description of Parameter * @param nodes Description of Parameter * @since May 24, 2002 */ private void instantiateEdges(NodeList edgeElements, Map edges, Map metadata, Map nodes) { org.w3c.dom.NamedNodeMap attributes; String edgeID; String edgeMetadataID; String fromNodeAttr; String toNodeAttr; String[] specNodePort; String fromNode; int fromPort; String toNode; int toPort; DataRecordMetadata edgeMetadata; org.jetel.graph.Edge graphEdge; org.jetel.graph.Node graphNode; // loop through all Node elements & create appropriate Metadata objects for (int i = 0; i < edgeElements.getLength(); i++) { attributes = edgeElements.item(i).getAttributes(); // process edge element attributes "id" & "fileURL" edgeID = attributes.getNamedItem("id").getNodeValue(); edgeMetadataID = attributes.getNamedItem("metadata").getNodeValue(); fromNodeAttr = attributes.getNamedItem("fromNode").getNodeValue(); toNodeAttr = attributes.getNamedItem("toNode").getNodeValue(); if ((edgeID != null) && (edgeMetadataID != null) && (fromNodeAttr != null) && (toNodeAttr != null)) { edgeMetadata = (DataRecordMetadata) metadata.get(edgeMetadataID); if (edgeMetadata == null) { throw new RuntimeException("Can't find metadata ID: " + edgeMetadataID); } graphEdge = new Edge(edgeID, edgeMetadata); if (edges.put(edgeID, graphEdge)!=null){ throw new RuntimeException("Duplicate EdgeID detected: "+edgeID); } // assign edge to fromNode specNodePort = fromNodeAttr.split(":"); graphNode = (org.jetel.graph.Node) nodes.get(specNodePort[0]); fromPort=Integer.parseInt(specNodePort[1]); if (graphNode == null) { throw new RuntimeException("Can't find node ID: " + fromNodeAttr); } // check whether port isn't already assigned if (graphNode.getOutputPort(fromPort)!=null){ throw new RuntimeException("Output port ["+fromPort+"] of "+graphNode.getID()+" already assigned !"); } graphNode.addOutputPort(fromPort, graphEdge); // assign edge to toNode specNodePort = toNodeAttr.split(":"); // Node & port specified in form of: <nodeID>:<portNum> graphNode = (org.jetel.graph.Node) nodes.get(specNodePort[0]); toPort=Integer.parseInt(specNodePort[1]); if (graphNode == null) { throw new RuntimeException("Can't find node ID: " + fromNodeAttr); } // check whether port isn't already assigned if (graphNode.getInputPort(toPort)!=null){ throw new RuntimeException("Input port ["+toPort+"] of "+graphNode.getID()+" already assigned !"); } graphNode.addInputPort(toPort, graphEdge); } else { // TODO : some error reporting should take place here // attribute missing should be handled by validating parser throw new RuntimeException("Attribute missing"); } } } /** * Description of the Method * * @param dbConnectionElements Description of Parameter * @param graph Description of Parameter * @since October 1, 2002 */ private void instantiateDBConnections(NodeList dbConnectionElements, TransformationGraph graph) { String connectionID; DBConnection dbConnection; for (int i = 0; i < dbConnectionElements.getLength(); i++) { connectionID = dbConnectionElements.item(i).getAttributes().getNamedItem("id").getNodeValue(); dbConnection = DBConnection.fromXML(dbConnectionElements.item(i)); if (dbConnection != null && connectionID != null) { graph.addDBConnection(connectionID, dbConnection); } } } /** * Gets the reference to GraphXMLReaderWriter static object * * @return object reference * @since May 28, 2002 */ public static TransformationGraphXMLReaderWriter getReference() { return graphXMLReaderWriter; } }
package com.bbn.bue.common.parameters; import com.bbn.bue.common.StringUtils; import com.bbn.bue.common.converters.*; import com.bbn.bue.common.parameters.exceptions.*; import com.bbn.bue.common.parameters.serifstyle.SerifStyleParameterFileLoader; import com.bbn.bue.common.symbols.Symbol; import com.bbn.bue.common.validators.*; import com.google.common.annotations.Beta; import com.google.common.base.Optional; import com.google.common.collect.*; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; /** * Represents a set of parameters passed into a program. The parameters are * assumed to originate as key-value pairs of <code>String</code>s, which * can then be accessed in various validated ways. This class is immutable. Keys will * never be null or empty. Values will never be null. * * For all methods to get parameters, looking up a missing parameter throws an unchecked * {@link MissingRequiredParameter} exception. * * @author rgabbard * */ @Beta public final class Parameters { public static final String DO_OS_CONVERSION_PARAM = "os_filepath_conversion"; /** * Constructs a Parameters object from a <code>Map</code>. The Map may contain neither * null keys, empty keys, or null values. * * @param params */ public Parameters(final Map<String, String> params) { this(params,ImmutableList.<String>of()); } private Parameters(final Map<String, String> params, final List<String> namespace) { this.namespace = ImmutableList.copyOf(namespace); this.params = ImmutableMap.copyOf(params); for (final Map.Entry<String, String> param : params.entrySet()) { checkNotNull(param.getKey()); checkNotNull(param.getValue()); checkArgument(!param.getKey().isEmpty()); } } /** * Creates a new set of parameters with only those parameters in the specified namespace * (that is, prefixed by "namespace.". The namespace prefix and period will be removed * from parameter names in the new {@code Parameters}. * @param requestedNamespace * @return */ public Parameters copyNamespace(final String requestedNamespace) { checkArgument(!requestedNamespace.isEmpty()); final ImmutableMap.Builder<String,String> ret = ImmutableMap.builder(); final String dottedNamespace = requestedNamespace + "."; for (final Map.Entry<String, String> param : params.entrySet()) { if (param.getKey().startsWith(dottedNamespace)) { ret.put(param.getKey().substring(dottedNamespace.length()), param.getValue()); } } final List<String> newNamespace = Lists.newArrayList(); newNamespace.addAll(namespace); newNamespace.add(requestedNamespace); return new Parameters(ret.build(), newNamespace); } /** * If the specified namespace is present, return a copy of that namespace * as a parameter set. Otherwise, return a copy of this parameter set. * @param requestedNamespace * @return */ public Parameters copyNamespaceIfPresent(final String requestedNamespace) { if (isNamespacePresent(requestedNamespace)) { return copyNamespace(requestedNamespace); } else { return copy(); } } /** * Returns if any parameter in this parameter set begins the the specified * string, followed by a dot. The argument may not be empty. * @param requestedNamespace * @return */ public boolean isNamespacePresent(final String requestedNamespace) { checkArgument(requestedNamespace.length() > 0); final String probe = requestedNamespace + "."; return Iterables.any(params.keySet(), StringUtils.startsWith(probe)); } /** * Creates a copy of this parameter set. * @return */ public Parameters copy() { return new Parameters(params, namespace); } public String dump() { return dump(true, true); } public String dumpWithoutNamespacePrefix() { return dump(true, false); } public String dump(final boolean printDateTime) { return dump(printDateTime, true); } /** * Dumps the parameters object as colon-separated key-value pairs. If {@code printDateTime} * is true, will put a #-style comment with the current date and time at the top. * If includeNamespacePrefix is true, will prefix its parameter with its full namespace * instead of writing all keys relative to the current namespace. */ public String dump(final boolean printDateTime, final boolean includeNamespacePrefix) { final StringWriter sOut = new StringWriter(); final PrintWriter out = new PrintWriter(sOut); if (printDateTime) { // output a timestamp comment final SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); out.format("#%s\n", timeFormat.format(new Date())); } for (final Map.Entry<String, String> param : params.entrySet()) { final String key; if (includeNamespacePrefix) { key = fullString(param.getKey()); } else { key = param.getKey(); } out.format("%s: %s\n", key, param.getValue()); } out.close(); return sOut.toString(); } public static Parameters loadSerifStyle(final File f) throws IOException { final SerifStyleParameterFileLoader loader = new SerifStyleParameterFileLoader(); return new Parameters(loader.load(f)); } /** * Combines these parameters with the others supplied to make a new <code>Parameters</code>. The new parameters * will contain all mappings present in either. If a mapping is present in both, the <code>other</code> argument * parameters take precedence. */ // this is currently unused anywhere, and it will require a little // thought how best to make it interact with namespacing /*public Parameters compose(final Parameters other) { checkNotNull(other); final Map<String, String> newMap = Maps.newHashMap(); newMap.putAll(params); newMap.putAll(other.params); return new Parameters(newMap); }*/ /** * Returns true iff the key <code>param</code> is assigned a value. */ public boolean isPresent(final String param) { return params.containsKey(checkNotNull(param)); } /** * Gets the value for a parameter as a raw string. */ public String getString(final String param) { checkNotNull(param); checkArgument(!param.isEmpty()); final String ret = params.get(param); if (ret != null) { return ret; } else { throw new MissingRequiredParameter(fullString(param)); } } private String fullString(final String param) { if (namespace.isEmpty()) { return param; } else { return StringUtils.DotJoiner.join(namespace)+"."+param; } } /** * Gets the parameter string for the key <code>param</code>, then runs it * throught the converter and checks it with the validator. * @param expectation What we expected to see, for produceing error messages. e.g. "integer" or "comma-separated list of strings" * @return */ public <T> T get(final String param, final StringConverter<T> converter, final Validator<T> validator, final String expectation) { checkNotNull(param); checkNotNull(converter); checkNotNull(validator); checkNotNull(expectation); final String value = getString(param); T ret; try { ret = converter.decode(value); } catch (final Exception e) { throw new ParameterConversionException(fullString(param), value, e, expectation); } try { validator.validate(ret); } catch (final ValidationException e) { throw new ParameterValidationException(fullString(param), value, e); } if (ret == null) { throw new RuntimeException("Parameter converters not allowed to return null for non-null input."); } return ret; } /** * Gets the parameter string *list* for the key <code>param</code>, then runs each element * throught the converter and checks it with the validator. * @param expectation What we expected to see, for produceing error messages. e.g. "integer" or "comma-separated list of strings" * @return */ public <T> List<T> getList(final String param, final StringConverter<T> converter, final Validator<T> validator, final String expectation) { checkNotNull(param); checkNotNull(converter); checkNotNull(validator); checkNotNull(expectation); final List<String> values = getStringList(param); final ImmutableList.Builder<T> retList = ImmutableList.builder(); for (final String value : values) { T ret; try { ret = converter.decode(value); } catch (final Exception e) { throw new ParameterConversionException(fullString(param), value, e, expectation); } try { validator.validate(ret); } catch (final ValidationException e) { throw new ParameterValidationException(fullString(param), value, e); } if (ret == null) { throw new RuntimeException( "Parameter converters not allowed to return null for non-null input."); } retList.add(ret); } return retList.build(); } /** * Looks up a parameter. If the value is not in <code>possibleValues</code>, throws and exception. * @param possibleValues May not be null. May not be empty. * @throws InvalidEnumeratedPropertyException if the parameter value is not on the list. */ public String getStringOf(final String param, final List<String> possibleValues) { checkNotNull(possibleValues); checkArgument(!possibleValues.isEmpty()); final String value = getString(param); if (possibleValues.contains(value)) { return value; } else { throw new InvalidEnumeratedPropertyException(fullString(param), value, possibleValues); } } /** * Looks up a parameter, then uses the value as a key in a map lookup. If the value is not * a key in the map, throws an exception. * * @param possibleValues May not be null. May not be empty. * @throws InvalidEnumeratedPropertyException if the parameter value is not on the list. */ public <T> T getMapped(final String param, final Map<String, T> possibleValues) { checkNotNull(possibleValues); checkArgument(!possibleValues.isEmpty()); final String value = getString(param); final T ret = possibleValues.get(value); if (ret == null) { throw new InvalidEnumeratedPropertyException(fullString(param), value, possibleValues.keySet()); } return ret; } public <T extends Enum<T>> T getEnum(final String param, final Class<T> clazz) { return this.<T>get(param, new StringToEnum<T>(clazz), new AlwaysValid<T>(), "enumeration"); } public <T extends Enum<T>> List<T> getEnumList(final String param, final Class<T> clazz) { return this.<T>getList(param, new StringToEnum<T>(clazz), new AlwaysValid<T>(), "enumeration"); } public Class<?> getClassObjectForString(final String className) throws ClassNotFoundException { return Class.forName(className); } public Class<?> getClassObject(final String param) { final String className = getString(param); try { return getClassObjectForString(className); } catch (final ClassNotFoundException e) { throw new ParameterConversionException(fullString(param), className, e, "class"); } } @SuppressWarnings("unchecked") public <T> T getParameterInitializedObject(final String param, final Class<T> superClass) { final Class<?> clazz = getClassObject(param); return parameterInitializedObjectForClass(clazz, param, superClass); } public <T> Optional<T> getOptionalParameterInitializedObject(final String param, final Class<T> superClass) { if (isPresent(param)) { return Optional.of(getParameterInitializedObject(param, superClass)); } else { return Optional.absent(); } } private <T> T parameterInitializedObjectForClass(final Class<?> clazz, final String param, final Class<T> superClass) { Object ret; try { ret = createViaConstructor(clazz, param); } catch (NoSuchMethodException nsme) { try { ret = createViaStaticFactoryMethod(clazz, param); } catch (NoSuchMethodException nsme2) { throw new ParameterValidationException(fullString(param), getString(param), new RuntimeException(String.format("Class %s has neither fromParameters(params) " +"static factory method or constructor which takes params", clazz.getName()))); } } if (superClass.isInstance(ret)) { return (T)ret; } else { throw new ParameterValidationException(fullString(param), getString(param), new RuntimeException(String.format("Can't cast %s to %s", clazz.getName(), superClass.getName()))); } } private Object createViaConstructor(Class<?> clazz, String param) throws NoSuchMethodException { try { return clazz.getConstructor(Parameters.class).newInstance(this); } catch (final IllegalArgumentException e) { throw new ParameterValidationException(fullString(param), getString(param), e); } catch (final InstantiationException e) { throw new ParameterValidationException(fullString(param), getString(param), e); } catch (final IllegalAccessException e) { throw new ParameterValidationException(fullString(param), getString(param), e); } catch (final InvocationTargetException e) { throw new ParameterValidationException(fullString(param), getString(param), e); } } private Object createViaStaticFactoryMethod(Class<?> clazz, String param) throws NoSuchMethodException { try { return clazz.getMethod("fromParameters", Parameters.class).invoke(null, this); } catch (IllegalAccessException e) { throw new ParameterValidationException(fullString(param), getString(param), e); } catch (InvocationTargetException e) { throw new ParameterValidationException(fullString(param), getString(param), e); } } @SuppressWarnings("unchecked") public <T,S> ImmutableList<T> getParameterInitializedObjects( final String param, final Class<S> superClass) { final List<String> classNames = getStringList(param); final ImmutableList.Builder<T> ret = ImmutableList.builder(); for (final String className : classNames) { Class<?> clazz; try { clazz = getClassObjectForString(className); } catch (final ClassNotFoundException e) { throw new ParameterValidationException(fullString(param), getString(param), e); } ret.add((T)parameterInitializedObjectForClass(clazz, param, superClass)); } return ret.build(); } public List<Integer> getIntegerList(final String param) { final List<String> intStrings = getStringList(param); final ImmutableList.Builder<Integer> ret = ImmutableList.builder(); for (final String intString : intStrings) { try { ret.add(Integer.parseInt(intString)); } catch (final NumberFormatException nfe) { throw new ParameterValidationException(fullString(param), intString, nfe); } } return ret.build(); } /** * Gets a "true/false" parameter. */ public boolean getBoolean(final String param) { return get(param, new StrictStringToBoolean(), new AlwaysValid<Boolean>(), "boolean"); } public Optional<Boolean> getOptionalBoolean(final String param) { if(isPresent(param)) { return Optional.of(getBoolean(param)); } else { return Optional.absent(); } } public Optional<String> getOptionalString(final String param) { if(isPresent(param)) { return Optional.of(getString(param)); } else { return Optional.absent(); } } /** * Gets an integer parameter. */ public int getInteger(final String param) { return get(param, new StringToInteger(), new AlwaysValid<Integer>(), "integer"); } public Optional<Integer> getOptionalInteger(final String param) { if (isPresent(param)) { return Optional.of(getInteger(param)); } else { return Optional.absent(); } } /** * Gets an positive integer parameter. */ public int getPositiveInteger(final String param) { return get(param, new StringToInteger(), new IsPositive<Integer>(), "positive integer"); } /** * Gets an positive integer list parameter. */ public List<Integer> getPositiveIntegerList(final String param) { return getList(param, new StringToInteger(), new IsPositive<Integer>(), "positive integer"); } /** * Gets a positive double parameter. */ public double getPositiveDouble(final String param) { return get(param, new StringToDouble(), new IsPositive<Double>(), "positive double"); } public Optional<Double> getOptionalPositiveDouble(final String param) { if (isPresent(param)) { return Optional.of(getPositiveDouble(param)); } return Optional.absent(); } /** * Gets a parameter whose value is a list of positive doubles. */ public List<Double> getPositiveDoubleList(final String param) { return getList(param, new StringToDouble(), new IsPositive<Double>(), "positive double"); } /** * Gets a non-negative double parameter. */ public double getNonNegativeDouble(final String param) { return get(param, new StringToDouble(), new IsNonNegative<Double>(), "non-negative double"); } /** * Gets a parameter whose value is a list of non-negative doubles. */ public List<Double> getNonNegativeDoubleList(final String param) { return getList(param, new StringToDouble(), new IsNonNegative<Double>(), "non-negative double"); } /** * Gets a non-negative integer number parameter. */ public int getNonNegativeInteger(final String param) { return get(param, new StringToInteger(), new IsNonNegative<Integer>(), "non-negative integer"); } /** * Gets a double parameter. */ public double getDouble(final String param) { return get(param, new StringToDouble(), new AlwaysValid<Double>(), "double"); } /** * Gets a double between 0.0 and 1.0, inclusive. */ public double getProbability(final String param) { return get(param, new StringToDouble(), new IsInRange<Double>(Range.closed(0.0, 1.0)), "probability"); } private StringConverter<File> getFileConverter() { if (isPresent(DO_OS_CONVERSION_PARAM) && getBoolean(DO_OS_CONVERSION_PARAM)) { return new StringToOSFile(); } else { return new StringToFile(); } } /** * Gets a file, which is required to exist. */ public File getExistingFile(final String param) { return get(param,getFileConverter(), new And<File>(new FileExists(), new IsFile()), "existing file"); } /** * Gets a file or directory, which is required to exist. */ public File getExistingFileOrDirectory(final String param) { return get(param, getFileConverter(), new FileExists(), "existing file or directory"); } /** * Gets a directory which is guaranteed to exist after the execution of this * method. If the directory does not already exist, it and its parents * are created. If this is not possible, an exception is throws. */ public File getAndMakeDirectory(final String param) { final File f = get(param, new StringToFile(), new AlwaysValid<File>(), "existing or creatable directory"); if (f.exists()) { if (f.isDirectory()) { return f.getAbsoluteFile(); } else { throw new ParameterValidationException(fullString(param), f .getAbsolutePath().toString(), new ValidationException("Not an existing or creatable directory")); } } else { f.getAbsoluteFile().mkdirs(); return f.getAbsoluteFile(); } } /** * Gets a directory which already exists. */ public File getExistingDirectory(final String param) { return get(param, new StringToFile(), new And<File>(new FileExists(), new IsDirectory()), "existing directory"); } /** * Gets a (possibly empty) list of existing directories. * Will throw a {@link com.bbn.bue.common.parameters.exceptions.ParameterValidationException} * if any of the supplied paths are not existing directories. */ public ImmutableList<File> getExistingDirectories(String param) { final List<String> fileStrings = getStringList(param); final ImmutableList.Builder<File> ret = ImmutableList.builder(); for (final String dirName : fileStrings) { final File dir = new File(dirName.trim()); if (!dir.isDirectory()) { throw new ParameterValidationException(fullString(param), dirName, "path does not exist or is not a directory"); } ret.add(dir); } return ret.build(); } public Optional<File> getOptionalExistingDirectory(final String param) { if (isPresent(param)) { return Optional.of(getExistingDirectory(param)); } return Optional.absent(); } /** * Gets a ,-separated set of Strings. */ public Set<String> getStringSet(final String param) { return get(param, new StringToStringSet(","), new AlwaysValid<Set<String>>(), "comma-separated list of strings"); } /** * Gets a ,-separated list of Strings */ public List<String> getStringList(final String param) { return get(param, new StringToStringList(","), new AlwaysValid<List<String>>(), "comma-separated list of strings"); } /** * Gets a ,-separated list of Strings, if available */ public Optional<List<String>> getOptionalStringList(final String param) { if (isPresent(param)) { return Optional.of(getStringList(param)); } return Optional.absent(); } /** * Gets a ,-separated set of Symbols */ public Set<Symbol> getSymbolSet(final String param) { return get(param, new StringToSymbolSet(","), new AlwaysValid<Set<Symbol>>(), "comma-separated list of strings"); } /** * Gets a ,-separated list of Symbols */ public List<Symbol> getSymbolList(final String param) { return get(param, new StringToSymbolList(","), new AlwaysValid<List<Symbol>>(), "comma-separated list of strings"); } public File getCreatableFile(final String param) { final String val = getString(param); final File ret = new File(val); if (ret.exists()) { if (ret.isDirectory()) { throw new ParameterValidationException(fullString(param), val, "Requested a file, but directory exists with that filename"); } } else { ret.getAbsoluteFile().getParentFile().mkdirs(); } return ret; } /** * Gets a file, with no requirements about whether it exists or not. */ public File getPossiblyNonexistentFile(final String param) { return new File(getString(param)); } public File getCreatableDirectory(final String param) { final String val = getString(param); final File ret = new File(val); if (ret.exists()) { if (!ret.isDirectory()) { throw new ParameterValidationException(fullString(param), val, "Requested a directory, but a file exists with that filename"); } } else { ret.getAbsoluteFile().mkdirs(); } return ret; } public File getEmptyDirectory(final String param) { final File dir = getCreatableDirectory(param); final int numFilesContained = dir.list().length; if (numFilesContained != 0) { throw new ParameterValidationException(fullString(param), getString(param), String.format("Requested an empty directory, but directory contains %d files.", numFilesContained)); } return dir; } public Parameters getSubParameters(final String param) throws IOException { final File paramFile = getExistingFile(param); return Parameters.loadSerifStyle(paramFile); } /** * Throws a ParameterException if neither parameter is defined. * @param param1 * @param param2 */ public void assertAtLeastOneDefined(final String param1, final String param2) { if (!isPresent(param1) && !isPresent(param2)) { throw new ParameterException(String.format("At least one of %s and %s must be defined.", param1, param2)); } } public Optional<File> getOptionalExistingFile(final String param) { if (isPresent(param)) { return Optional.of(getExistingFile(param)); } else { return Optional.absent(); } } public Optional<File> getOptionalCreatableFile(final String param) { if (isPresent(param)) { return Optional.of(getCreatableFile(param)); } else { return Optional.absent(); } } public File getExistingFileRelativeTo(final File root, final String param) { if (!root.exists()) { throw new ParameterException(String.format("Cannot resolve parameter %s relative to non-existent directory", param), new FileNotFoundException(String.format("Not found: %s", root))); } final String val = getString(param); final File ret = new File(root, val); if (!ret.exists()) { throw new ParameterValidationException(fullString(param), ret.getAbsolutePath(), "Requested existing file, but the file does not exist"); } return ret; } private final Map<String, String> params; private final List<String> namespace; }
package common.db.model.log; import java.io.Serializable; import java.lang.reflect.Array; import java.sql.Timestamp; import javax.annotation.PreDestroy; import javax.persistence.*; import javax.validation.constraints.Max; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.NotFound; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.mchange.util.FailSuppressedMessageLogger; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @AssertTrue //Booleantrue @AssertFalse//false @CreditCardNumber// @DecimalMax// @DecimalMin// @Digits(integer=2,fraction=20)//, @Email//email @Future// @Length(min=,max=)//minmax, @Max// @Min// @NotNull//null @NotBlank// @NotEmpty// @Null// @Past// @Size(min=, max=)//sizeminmaxMap @URL(protocol=,host,port)//URLprotocolhostURL @Valid//map // * @author cz_jjq * */ /** * The persistent class for the sys_users database table. * @Table(name = "user_roles", catalog = "test", uniqueConstraints = @UniqueConstraint( columnNames = { "role", "username" })) // */ @Entity @DynamicInsert //true,insert,insert,nullinsert.false @DynamicUpdate //true,update,update,nullupdate,false @Table(name="COMMON_LOG_ERROR") @NamedQueries({ //@NamedQuery(name="findAll",query="SELECT u FROM User u"), //@NamedQuery(name="findUserWithId",query="SELECT u FROM User u WHERE u.id = ?1"), //@NamedQuery(name="User.findByName",query="SELECT u FROM User u WHERE u.userName = :name") }) //JsonIgnoreProperties //@JsonIgnoreProperties(value={"sysRoles"/*,"password","salt"*/}) public class ErrorLog implements Serializable{ private static final long serialVersionUID = 1L; @PrePersist void populateDBFields(){} @PreUpdate void preUpdate() { //createTime=null;//create } @PreRemove void preRemove() { } @PreDestroy void preDestroy(){} @PostLoad public void populateTransientFields(){ /* if (this.roles == null){ this.roles = new ArrayList<Role>(); } for (Role role : this.roles) { roleIds.add(role.getId()); }*/ } /** *ID @Id @GeneratedValue(generator = "idGenerator") @GenericGenerator(name = "idGenerator", strategy = "uuid2") //hibernate/32UUID protected String id; */ @Id @Column(name="ID") @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private Long userId; private Long sessionLogId; private Date createTime; }
package foam.mlang; import foam.dao.Sink; import foam.mlang.predicate.*; import foam.mlang.sink.*; /** * Static helper functions for creating MLangs. * * Usage: import foam.mlang.MLang.*; */ public class MLang { public static Expr prepare(Object o) { return o instanceof Expr ? (Expr) o : new Constant().setValue(o); } public static Predicate LT(Object o1, Object o2) { return new Lt().setArg1(MLang.prepare(o1)).setArg2(MLang.prepare(o2)); } public static Predicate LTE(Object o1, Object o2) { return new Lte().setArg1(MLang.prepare(o1)).setArg2(MLang.prepare(o2)); } public static Predicate EQ(Object o1, Object o2) { return new Eq().setArg1(MLang.prepare(o1)).setArg2(MLang.prepare(o2)); } public static Predicate GTE(Object o1, Object o2) { return new Gte().setArg1(MLang.prepare(o1)).setArg2(MLang.prepare(o2)); } public static Predicate GT(Object o1, Object o2) { return new Gt().setArg1(MLang.prepare(o1)).setArg2(MLang.prepare(o2)); } public static Predicate AND(Predicate... args) { return new And().setArgs(args); } public static Predicate OR(Predicate... args) { return new Or().setArgs(args); } public static Sink MAX(Object o1) { return new Max().setArg1(MLang.prepare(o1)); } public static Sink MIN(Object o1) { return new Min().setArg1(MLang.prepare(o1)); } }
package cgeo.geocaching.connector.ec; import cgeo.geocaching.CgeoApplication; import cgeo.geocaching.R; import cgeo.geocaching.connector.AbstractLogin; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.network.Network; import cgeo.geocaching.network.Parameters; import cgeo.geocaching.settings.Credentials; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.utils.JsonUtils; import cgeo.geocaching.utils.Log; import ch.boye.httpclientandroidlib.HttpResponse; import com.fasterxml.jackson.databind.JsonNode; import org.apache.commons.lang3.StringUtils; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import java.io.IOException; public class ECLogin extends AbstractLogin { private final CgeoApplication app = CgeoApplication.getInstance(); private String sessionId = null; private ECLogin() { // singleton } private static class SingletonHolder { @NonNull private final static ECLogin INSTANCE = new ECLogin(); } @NonNull public static ECLogin getInstance() { return SingletonHolder.INSTANCE; } @Override @NonNull protected StatusCode login(final boolean retry) { final Credentials login = Settings.getCredentials(ECConnector.getInstance()); if (login.isInvalid()) { clearLoginInfo(); Log.e("ECLogin.login: No login information stored"); return StatusCode.NO_LOGIN_INFO_STORED; } setActualStatus(app.getString(R.string.init_login_popup_working)); final Parameters params = new Parameters("user", login.getUsername(), "pass", login.getPassword()); final HttpResponse loginResponse = Network.postRequest("https://extremcaching.com/exports/apilogin.php", params); final String loginData = Network.getResponseData(loginResponse); if (StringUtils.isBlank(loginData)) { Log.e("ECLogin.login: Failed to retrieve login data"); return StatusCode.CONNECTION_FAILED_EC; // no login page } assert loginData != null; if (loginData.contains("Wrong username or password")) { // hardcoded in English Log.i("Failed to log in Extremcaching.com as " + login.getUsername() + " because of wrong username/password"); return StatusCode.WRONG_LOGIN_DATA; // wrong login } if (getLoginStatus(loginData)) { Log.i("Successfully logged in Extremcaching.com as " + login.getUsername()); return StatusCode.NO_ERROR; // logged in } Log.i("Failed to log in Extremcaching.com as " + login.getUsername() + " for some unknown reason"); if (retry) { return login(false); } return StatusCode.UNKNOWN_ERROR; // can't login } /** * Check if the user has been logged in when he retrieved the data. * * @return {@code true} if user is logged in, {@code false} otherwise */ private boolean getLoginStatus(@Nullable final String data) { if (StringUtils.isBlank(data) || StringUtils.equals(data, "[]")) { Log.e("ECLogin.getLoginStatus: No or empty data given"); return false; } assert data != null; setActualStatus(app.getString(R.string.init_login_popup_ok)); try { final JsonNode json = JsonUtils.reader.readTree(data); final String sid = json.get("sid").asText(); if (!StringUtils.isBlank(sid)) { sessionId = sid; setActualLoginStatus(true); setActualUserName(json.get("username").asText()); setActualCachesFound(json.get("found").asInt()); return true; } resetLoginStatus(); } catch (IOException | NullPointerException e) { Log.e("ECLogin.getLoginStatus", e); } setActualStatus(app.getString(R.string.init_login_popup_failed)); return false; } @Override protected void resetLoginStatus() { sessionId = null; setActualLoginStatus(false); } public String getSessionId() { if (!StringUtils.isBlank(sessionId) || login() == StatusCode.NO_ERROR) { return sessionId; } return StringUtils.EMPTY; } }
package org.apollo.cache; import java.io.Closeable; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import java.util.zip.CRC32; import com.google.common.base.Preconditions; import org.apollo.cache.archive.Archive; /** * A file system based on top of the operating system's file system. It consists of a data file and index files. Index * files point to blocks in the data file, which contains the actual data. * * @author Graham */ public final class IndexedFileSystem implements Closeable { /** * The Map that caches already-decoded Archives. */ private final Map<FileDescriptor, Archive> cache = new HashMap<>(FileSystemConstants.ARCHIVE_COUNT); /** * The index files. */ private final RandomAccessFile[] indices = new RandomAccessFile[256]; /** * Read only flag. */ private final boolean readOnly; /** * The cached CRC table. */ private ByteBuffer crcTable; /** * The {@link #crcTable} represented as an {@code int} array. */ private int[] crcs; /** * The data file. */ private RandomAccessFile data; /** * Creates the file system with the specified base directory. * * @param base The base directory. * @param readOnly Indicates whether the file system will be read only or not. * @throws FileNotFoundException If the data files could not be found. */ public IndexedFileSystem(Path base, boolean readOnly) throws FileNotFoundException { this.readOnly = readOnly; detectLayout(base); } @Override public void close() throws IOException { if (data != null) { synchronized (data) { data.close(); } } for (RandomAccessFile index : indices) { if (index != null) { synchronized (index) { index.close(); } } } } /** * Gets the {@link Archive} pointed to by the specified {@link FileDescriptor}. * * @param type The file type. * @param file The file id. * @return The Archive. * @throws IOException If there is an error decoding the Archive. */ public Archive getArchive(int type, int file) throws IOException { FileDescriptor descriptor = new FileDescriptor(type, file); Archive cached = cache.get(descriptor); if (cached == null) { cached = Archive.decode(getFile(descriptor)); synchronized (this) { cache.put(descriptor, cached); } } return cached; } public ByteBuffer getCrcTable() throws IOException { if (readOnly) { synchronized (this) { if (crcTable != null) { return crcTable.duplicate(); } } int archives = getFileCount(0); int hash = 1234; int[] crcs = new int[archives]; CRC32 crc32 = new CRC32(); for (int i = 1; i < crcs.length; i++) { crc32.reset(); ByteBuffer buffer = getFile(0, i); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes, 0, bytes.length); crc32.update(bytes, 0, bytes.length); crcs[i] = (int) crc32.getValue(); } ByteBuffer buffer = ByteBuffer.allocate((crcs.length + 1) * Integer.BYTES); for (int crc : crcs) { hash = (hash << 1) + crc; buffer.putInt(crc); } buffer.putInt(hash); buffer.flip(); synchronized (this) { crcTable = buffer.asReadOnlyBuffer(); return crcTable.duplicate(); } } throw new IllegalStateException("Cannot get CRC table from a writable file system."); } /** * Gets the CRC table as an {@code int} array. * * @return The CRC table as an {@code int} array. * @throws IOException If there is an error accessing files to create the table. */ public int[] getCrcs() throws IOException { if (crcs == null) { ByteBuffer buffer = getCrcTable(); crcs = new int[(buffer.remaining() / Integer.BYTES) - 1]; Arrays.setAll(crcs, crc -> buffer.getInt()); } return crcs; } /** * Gets a file. * * @param descriptor The {@link FileDescriptor} pointing to the file. * @return A {@link ByteBuffer} containing the contents of the file. * @throws IOException If there is an error decoding the file. */ public ByteBuffer getFile(FileDescriptor descriptor) throws IOException { Index index = getIndex(descriptor); ByteBuffer buffer = ByteBuffer.allocate(index.getSize()); long position = index.getBlock() * FileSystemConstants.BLOCK_SIZE; int read = 0; int size = index.getSize(); int blocks = size / FileSystemConstants.CHUNK_SIZE; if (size % FileSystemConstants.CHUNK_SIZE != 0) { blocks++; } for (int i = 0; i < blocks; i++) { byte[] header = new byte[FileSystemConstants.HEADER_SIZE]; synchronized (data) { data.seek(position); data.readFully(header); } position += FileSystemConstants.HEADER_SIZE; int nextFile = (header[0] & 0xFF) << 8 | header[1] & 0xFF; int curChunk = (header[2] & 0xFF) << 8 | header[3] & 0xFF; int nextBlock = (header[4] & 0xFF) << 16 | (header[5] & 0xFF) << 8 | header[6] & 0xFF; int nextType = header[7] & 0xFF; Preconditions.checkArgument(i == curChunk, "Chunk id mismatch."); int chunkSize = size - read; if (chunkSize > FileSystemConstants.CHUNK_SIZE) { chunkSize = FileSystemConstants.CHUNK_SIZE; } byte[] chunk = new byte[chunkSize]; synchronized (data) { data.seek(position); data.readFully(chunk); } buffer.put(chunk); read += chunkSize; position = (long) nextBlock * (long) FileSystemConstants.BLOCK_SIZE; // if we still have more data to read, check the validity of the header if (size > read) { if (nextType != descriptor.getType() + 1) { throw new IOException("File type mismatch."); } if (nextFile != descriptor.getFile()) { throw new IOException("File id mismatch."); } } } buffer.flip(); return buffer; } /** * Gets a file. * * @param type The file type. * @param file The file id. * @return A {@link ByteBuffer} which contains the contents of the file. * @throws IOException If an I/O error occurs. */ public ByteBuffer getFile(int type, int file) throws IOException { return getFile(new FileDescriptor(type, file)); } /** * Checks if this {@link IndexedFileSystem} is read only. * * @return {@code true} if so, {@code false} if not. */ public boolean isReadOnly() { return readOnly; } /** * Automatically detect the layout of the specified directory. * * @param base The base directory. * @throws FileNotFoundException If the data files could not be found. */ private void detectLayout(Path base) throws FileNotFoundException { int indexCount = 0; for (int index = 0; index < indices.length; index++) { Path idx = base.resolve("main_file_cache.idx" + index); if (Files.exists(idx) && !Files.isDirectory(idx)) { indexCount++; indices[index] = new RandomAccessFile(idx.toFile(), readOnly ? "r" : "rw"); } } if (indexCount <= 0) { throw new FileNotFoundException("No index file(s) present."); } Path resources = base.resolve("main_file_cache.dat"); if (Files.exists(resources) && !Files.isDirectory(resources)) { data = new RandomAccessFile(resources.toFile(), readOnly ? "r" : "rw"); } else { throw new FileNotFoundException("No data file present."); } } /** * Gets the number of files with the specified type. * * @param type The type. * @return The number of files. * @throws IOException If there is an error getting the length of the specified index file. * @throws IndexOutOfBoundsException If {@code type} is less than 0, or greater than or equal to the amount of * indices. */ private int getFileCount(int type) throws IOException { Preconditions.checkElementIndex(type, indices.length, "File type out of bounds."); RandomAccessFile indexFile = indices[type]; synchronized (indexFile) { return (int) (indexFile.length() / FileSystemConstants.INDEX_SIZE); } } /** * Gets the index of a file. * * @param descriptor The {@link FileDescriptor} which points to the file. * @return The {@link Index}. * @throws IOException If there is an error reading from the index file. * @throws IndexOutOfBoundsException If the descriptor type is less than 0, or greater than or equal to the amount * of indices. */ private Index getIndex(FileDescriptor descriptor) throws IOException { int index = descriptor.getType(); Preconditions.checkElementIndex(index, indices.length, "File descriptor type out of bounds."); byte[] buffer = new byte[FileSystemConstants.INDEX_SIZE]; RandomAccessFile indexFile = indices[index]; synchronized (indexFile) { long position = descriptor.getFile() * FileSystemConstants.INDEX_SIZE; if (position >= 0 && indexFile.length() >= position + FileSystemConstants.INDEX_SIZE) { indexFile.seek(position); indexFile.readFully(buffer); } else { throw new FileNotFoundException("Could not find find index."); } } return Index.decode(buffer); } }
package us.kbase.typedobj.tests; import static org.junit.Assert.*; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.apache.commons.io.FileUtils; import org.junit.AfterClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.fge.jsonpatch.diff.JsonDiff; import us.kbase.typedobj.core.TypeDefId; import us.kbase.typedobj.core.TypeDefName; import us.kbase.typedobj.core.TypedObjectValidationReport; import us.kbase.typedobj.core.TypedObjectValidator; import us.kbase.typedobj.db.FileTypeStorage; import us.kbase.typedobj.db.TypeDefinitionDB; import us.kbase.typedobj.db.UserInfoProviderForTests; import us.kbase.workspace.kbase.Util; /** * Tests that ensure the proper subset is extracted from a typed object instance * * To add new tests of the ID processing machinery, add files named in the format: * [ModuleName].[TypeName].instance.[label] * - json encoding of a valid type instance * [ModuleName].[TypeName].instance.[label].subset * - json encoding of the expected '\@searchable ws_subset' output * * @author msneddon */ @RunWith(value = Parameterized.class) public class TestWsSubsetExtraction { /** * location to stash the temporary database for testing * WARNING: THIS DIRECTORY WILL BE WIPED OUT AFTER TESTS!!!! */ private final static String TEST_DB_LOCATION = "test/typedobj_temp_test_files/t3"; /** * relative location to find the input files */ private final static String TEST_RESOURCE_LOCATION = "files/t3/"; private final static boolean VERBOSE = true; private static TypeDefinitionDB db; private static TypedObjectValidator validator; /** * List to stash the handle to the test case files */ private static List<TestInstanceInfo> instanceResources = new ArrayList <TestInstanceInfo> (); private static class TestInstanceInfo { public TestInstanceInfo(String resourceName, String moduleName, String typeName) { this.resourceName = resourceName; this.moduleName = moduleName; this.typeName = typeName; } public String resourceName; public String moduleName; public String typeName; } /** * As each test instance object is created, this sets which instance to actually test */ private TestInstanceInfo instance; public TestWsSubsetExtraction(TestInstanceInfo tii) { this.instance = tii; } /** * This is invoked before anything else, so here we invoke the creation of the db * @return * @throws Exception */ @Parameters public static Collection<Object[]> assembleTestInstanceList() throws Exception { prepareDb(); Object [][] instanceInfo = new Object[instanceResources.size()][1]; for(int k=0; k<instanceResources.size(); k++) { instanceInfo[k][0] = instanceResources.get(k); } return Arrays.asList(instanceInfo); } /** * Setup the typedef database, load and release the types in the simple specs, and * identify all the files containing instances to validate. * @throws Exception */ public static void prepareDb() throws Exception { //ensure test location is available File dir = new File(TEST_DB_LOCATION); if (dir.exists()) { //fail("database at location: "+TEST_DB_LOCATION+" already exists, remove/rename this directory first"); removeDb(); } if(!dir.mkdirs()) { fail("unable to create needed test directory: "+TEST_DB_LOCATION); } if(VERBOSE) System.out.println("setting up the typed obj database at '"+dir.getAbsolutePath()+"'"); // point the type definition db to point there File tempdir = new File("temp_files"); if (!dir.exists()) dir.mkdir(); db = new TypeDefinitionDB(new FileTypeStorage(TEST_DB_LOCATION), tempdir, new UserInfoProviderForTests(),new Util().getKIDLpath()); // create a validator that uses the type def db validator = new TypedObjectValidator(db); String username = "wstester1"; String kbSpec = loadResourceFile(TEST_RESOURCE_LOCATION+"KB.spec"); List<String> kb_types = Arrays.asList("SimpleStructure","MappingStruct","ListStruct","DeepMaps","NestedData"); db.requestModuleRegistration("KB", username); db.approveModuleRegistrationRequest(username, "KB"); db.registerModule(kbSpec ,kb_types, username); db.releaseModule("KB", username); if(VERBOSE) System.out.print("finding test instances..."); String [] resources = getResourceListing(TEST_RESOURCE_LOCATION); for(int k=0; k<resources.length; k++) { String [] tokens = resources[k].split("\\."); if(tokens.length!=4) { continue; } if(tokens[2].equals("instance")) { instanceResources.add(new TestInstanceInfo(resources[k],tokens[0],tokens[1])); } } if(VERBOSE) System.out.println(" " + instanceResources.size() + "found"); } @AfterClass public static void removeDb() throws IOException { File dir = new File(TEST_DB_LOCATION); FileUtils.deleteDirectory(dir); if(VERBOSE) System.out.println("deleting typed obj database"); } @Test public void testValidInstances() throws Exception { ObjectMapper mapper = new ObjectMapper(); //read the instance data if(VERBOSE) System.out.println(" -("+instance.resourceName+")"); String instanceJson = loadResourceFile(TEST_RESOURCE_LOCATION+instance.resourceName); JsonNode instanceRootNode = mapper.readTree(instanceJson); // read the ids file, which provides the list of ids we expect to extract from the instance String expectedSubsetString = loadResourceFile(TEST_RESOURCE_LOCATION+instance.resourceName+".subset"); JsonNode expectedSubset = mapper.readTree(expectedSubsetString); // perform the initial validation, which must validate! TypedObjectValidationReport report = validator.validate( instanceRootNode, new TypeDefId(new TypeDefName(instance.moduleName,instance.typeName)) ); List <String> mssgs = report.getErrorMessagesAsList(); for(int i=0; i<mssgs.size(); i++) { System.out.println(" ["+i+"]:"+mssgs.get(i)); } assertTrue(" -("+instance.resourceName+") does not validate, but should", report.isInstanceValid()); JsonNode actualSubset = report.extractSearchableWsSubset(); // we can just check if they are equal like so: //assertTrue(" -("+instance.resourceName+") extracted subset does not match expected extracted subset", // actualSubset.equals(expectedSubset)); // this method generates a patch, so that if they differ you can see what's up JsonNode diff = JsonDiff.asJson(actualSubset,expectedSubset); if(VERBOSE) if(diff.size()!=0) System.out.println(" FAIL: diff:"+diff); //System.out.println(actualSubset); //System.out.println(expectedSubset); assertTrue(" -("+instance.resourceName+") extracted subset does not match expected extracted subset; diff="+diff, diff.size()==0); } /** * helper method to load test files, mostly copied from TypeRegistering test */ private static String loadResourceFile(String resourceName) throws Exception { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); InputStream is = TestWsSubsetExtraction.class.getResourceAsStream(resourceName); if (is == null) throw new IllegalStateException("Resource not found: " + resourceName); BufferedReader br = new BufferedReader(new InputStreamReader(is)); while (true) { String line = br.readLine(); if (line == null) break; pw.println(line); } br.close(); pw.close(); return sw.toString(); } private static String[] getResourceListing(String path) throws URISyntaxException, IOException { URL dirURL = TestWsSubsetExtraction.class.getResource(path); if (dirURL != null && dirURL.getProtocol().equals("file")) { /* A file path: easy enough */ return new File(dirURL.toURI()).list(); } if (dirURL == null) { // In case of a jar file, we can't actually find a directory. // Have to assume the same jar as the class. String me = TestWsSubsetExtraction.class.getName().replace(".", "/")+".class"; dirURL = TestWsSubsetExtraction.class.getResource(me); } if (dirURL.getProtocol().equals("jar")) { /* A JAR path */ String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory while(entries.hasMoreElements()) { String name = entries.nextElement().getName(); // construct internal jar path relative to the class String fullPath = TestWsSubsetExtraction.class.getPackage().getName().replace(".","/") + "/" + path; if (name.startsWith(fullPath)) { //filter according to the path String entry = name.substring(fullPath.length()); int checkSubdir = entry.indexOf("/"); if (checkSubdir >= 0) { // if it is a subdirectory, we just return the directory name entry = entry.substring(0, checkSubdir); } result.add(entry); } } jar.close(); return result.toArray(new String[result.size()]); } throw new UnsupportedOperationException("Cannot list files for URL "+dirURL); } }
package imagej.legacy.translate; import ij.VirtualStack; import ij.process.ColorProcessor; import ij.process.ImageProcessor; import imagej.data.Dataset; import net.imglib2.RandomAccess; import net.imglib2.meta.Axes; import net.imglib2.meta.AxisType; import net.imglib2.type.numeric.RealType; import net.imglib2.util.IntervalIndexer; /** * This class allows a merged color {@link Dataset} to be treated as a * {@link VirtualStack} of int[] data. * * @author Barry DeZonia */ public class MergedRgbVirtualStack extends VirtualStack { private final Dataset ds; private final int[] plane; private final RandomAccess<? extends RealType<?>> accessor; private final ImageProcessor processor; private final int w; private final int h; private final int xAxis; private final int yAxis; private final int cAxis; private final int size; private final long[] planeDims; private final long[] planePos; private final long[] pos; public MergedRgbVirtualStack(Dataset ds) { if (!ds.isRGBMerged()) { throw new IllegalArgumentException("Dataset is not merged color"); } long[] dims = ds.getDims(); AxisType[] axes = ds.getAxes(); planeDims = new long[dims.length - 3]; planePos = new long[dims.length - 3]; int pDims = 0; long sz = 1; for (int i = 0; i < axes.length; i++) { AxisType at = axes[i]; if (at.equals(Axes.X)) continue; if (at.equals(Axes.Y)) continue; if (at.equals(Axes.CHANNEL)) continue; sz *= dims[i]; planeDims[pDims++] = dims[i]; } if (sz > Integer.MAX_VALUE) { throw new IllegalArgumentException("Dataset has too many planes"); } xAxis = ds.getAxisIndex(Axes.X); yAxis = ds.getAxisIndex(Axes.Y); cAxis = ds.getAxisIndex(Axes.CHANNEL); if (xAxis == -1 || yAxis == -1 || cAxis == -1) { throw new IllegalArgumentException("Dataset does not have correct axes"); } if (dims[xAxis] * dims[yAxis] > Integer.MAX_VALUE) { throw new IllegalArgumentException("XY dims too large"); } this.ds = ds; this.w = (int) dims[xAxis]; this.h = (int) dims[yAxis]; this.plane = new int[w * h]; this.accessor = ds.getImgPlus().randomAccess(); this.processor = new ColorProcessor(w, h, plane); this.size = (int) sz; this.pos = new long[dims.length]; } public Dataset getDataset() { return ds; } @Override public ImageProcessor getProcessor(int n) { positionToPlane(n); for (int x = 0; x < w; x++) { accessor.setPosition(x, xAxis); for (int y = 0; y < h; y++) { accessor.setPosition(y, yAxis); accessor.setPosition(0, cAxis); int r = (int) accessor.get().getRealDouble(); accessor.fwd(cAxis); int g = (int) accessor.get().getRealDouble(); accessor.fwd(cAxis); int b = (int) accessor.get().getRealDouble(); int argb = (255 << 24) | (r << 16) | (g << 8) | b; int index = y * w + x; plane[index] = argb; } } return processor; } private void positionToPlane(int pNum) { IntervalIndexer.indexToPosition(pNum - 1, planeDims, planePos); int j = 0; for (int i = 0; i < pos.length; i++) { if (i == xAxis || i == yAxis || i == cAxis) pos[i] = 0; else pos[i] = planePos[j++]; } accessor.setPosition(pos); } @Override public int getBitDepth() { return 24; } /** Obsolete. Short images are always unsigned. */ @Override public void addUnsignedShortSlice(final String sliceLabel, final Object pixels) {} /** Adds the image in 'ip' to the end of the stack. */ @Override public void addSlice(final String sliceLabel, final ImageProcessor ip) {} /** * Adds the image in 'ip' to the stack following slice 'n'. Adds the slice to * the beginning of the stack if 'n' is zero. */ @Override public void addSlice(final String sliceLabel, final ImageProcessor ip, final int n) {} @Override public void addSlice(ImageProcessor ip) {} @Override public void addSlice(String name) {} @Override public void addSlice(String sliceLabel, Object pixels) {} /** Deletes the specified slice, were 1<=n<=nslices. */ @Override public void deleteSlice(final int n) {} /** Deletes the last slice in the stack. */ @Override public void deleteLastSlice() {} /** * Updates this stack so its attributes, such as min, max, calibration table * and color model, are the same as 'ip'. */ @Override public void update(final ImageProcessor ip) {} /** Returns the pixel array for the specified slice, were 1<=n<=nslices. */ @Override public Object getPixels(final int n) { return getProcessor(n).getPixels(); } /** * Assigns a pixel array to the specified slice, were 1<=n<=nslices. */ @Override public void setPixels(final Object pixels, final int n) {} /** * Returns the stack as an array of 1D pixel arrays. Note that the size of the * returned array may be greater than the number of slices currently in the * stack, with unused elements set to null. */ @Override public Object[] getImageArray() { return null; } /** * Returns the slice labels as an array of Strings. Note that the size of the * returned array may be greater than the number of slices currently in the * stack. Returns null if the stack is empty or the label of the first slice * is null. */ @Override public String[] getSliceLabels() { return null; } /** * Returns the label of the specified slice, were 1<=n<=nslices. Returns null * if the slice does not have a label. For DICOM and FITS stacks, labels may * contain header information. */ @Override public String getSliceLabel(final int n) { return "" + n; } /** * Returns a shortened version (up to the first 60 characters or first newline * and suffix removed) of the label of the specified slice. Returns null if * the slice does not have a label. */ @Override public String getShortSliceLabel(final int n) { return getSliceLabel(n); } /** Sets the label of the specified slice, were 1<=n<=nslices. */ @Override public void setSliceLabel(final String label, final int n) {} /** Returns true if this is a 3-slice RGB stack. */ @Override public boolean isRGB() { return false; } /** Returns true if this is a 3-slice HSB stack. */ @Override public boolean isHSB() { return false; } /** * Returns true if this is a virtual (disk resident) stack. This method is * overridden by the VirtualStack subclass. */ @Override public boolean isVirtual() { return true; } /** Frees memory by deleting a few slices from the end of the stack. */ @Override public void trim() {} /** Returns the number of slices in this stack */ @Override public int getSize() { return size; } @Override public void setBitDepth(final int bitDepth) {} @Override public String getDirectory() { return null; } @Override public String getFileName(final int n) { return null; } }
package com.annimon.stream; import com.annimon.stream.function.BiConsumer; import com.annimon.stream.function.BiFunction; import com.annimon.stream.function.BinaryOperator; import com.annimon.stream.function.Consumer; import com.annimon.stream.function.Function; import com.annimon.stream.function.IntUnaryOperator; import com.annimon.stream.function.LongUnaryOperator; import com.annimon.stream.function.Predicate; import com.annimon.stream.function.Supplier; import com.annimon.stream.function.ToDoubleFunction; import com.annimon.stream.function.ToIntFunction; import com.annimon.stream.function.ToLongFunction; import com.annimon.stream.function.UnaryOperator; import com.annimon.stream.test.hamcrest.DoubleStreamMatcher; import com.annimon.stream.test.hamcrest.OptionalMatcher; import java.math.BigInteger; 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.NoSuchElementException; import org.junit.Test; import static com.annimon.stream.test.hamcrest.OptionalMatcher.hasValue; import static com.annimon.stream.test.hamcrest.OptionalMatcher.isPresent; import static com.annimon.stream.test.hamcrest.StreamMatcher.elements; import static com.annimon.stream.test.hamcrest.StreamMatcher.isEmpty; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.array; import static org.hamcrest.Matchers.closeTo; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; /** * Tests {@code Stream}. * * @see com.annimon.stream.Stream */ public class StreamTest { @Test public void testStreamEmpty() { assertThat(Stream.empty(), isEmpty()); } @Test public void testStreamOfList() { final PrintConsumer<String> consumer = new PrintConsumer<String>(); final List<String> list = new ArrayList<String>(4); list.add("This"); list.add(" is "); list.add("a"); list.add(" test"); Stream.of(list) .forEach(consumer); assertEquals("This is a test", consumer.toString()); } @Test public void testStreamOfMap() { final PrintConsumer<String> consumer = new PrintConsumer<String>(); final Map<String, Integer> map = new HashMap<String, Integer>(4); map.put("This", 1); map.put(" is ", 2); map.put("a", 3); map.put(" test", 4); long count = Stream.of(map) .sortBy(Functions.<String, Integer>entryValue()) .map(Functions.<String, Integer>entryKey()) .peek(consumer) .count(); assertEquals(4, count); assertEquals("This is a test", consumer.toString()); } @Test(expected = NullPointerException.class) public void testStreamOfMapNull() { Stream.of((Map<?, ?>)null); } @Test public void testStreamOfIterator() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); long count = Stream.of(Functions.counterIterator()) .limit(5) .peek(consumer) .count(); assertEquals(5, count); assertEquals("01234", consumer.toString()); } @Test(expected = NullPointerException.class) public void testStreamOfIteratorNull() { Stream.of((Iterator<?>)null); } @Test public void testStreamOfIterable() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Iterable<Integer> iterable = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return Functions.counterIterator(); } }; long count = Stream.of(iterable) .limit(5) .peek(consumer) .count(); assertEquals(5, count); assertEquals("01234", consumer.toString()); } @Test(expected = NullPointerException.class) public void testStreamOfIterableNull() { Stream.of((Iterable<?>)null); } @Test public void testStreamOfNullable() { assertThat(Stream.ofNullable(null), isEmpty()); assertThat(Stream.ofNullable(5), elements(is(Arrays.asList(5)))); } @Test public void testStreamOfNullableWithIterable() { assertThat(Stream.ofNullable((List<?>) null), isEmpty()); assertThat(Stream.ofNullable(Arrays.asList(5, 10, 15)), elements(is(Arrays.asList(5, 10, 15)))); } @Test public void testStreamRange() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Stream.range(0, 5) .forEach(consumer); assertEquals("01234", consumer.toString()); } @Test public void testStreamRangeOnMaxValues() { long count = Stream.range(Integer.MAX_VALUE - 10, Integer.MAX_VALUE).count(); assertEquals(10L, count); } @Test public void testStreamRangeOnMaxLongValues() { long count = Stream.range(Long.MAX_VALUE - 10, Long.MAX_VALUE).count(); assertEquals(10L, count); } @Test public void testStreamRangeClosed() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Stream.rangeClosed(0, 5) .forEach(consumer); assertEquals("012345", consumer.toString()); } @Test public void testStreamRangeClosedOnMaxValues() { long count = Stream.rangeClosed(Integer.MAX_VALUE - 10, Integer.MAX_VALUE).count(); assertEquals(11L, count); } @Test public void testStreamRangeClosedOnMaxLongValues() { long count = Stream.rangeClosed(Long.MAX_VALUE - 10, Long.MAX_VALUE).count(); assertEquals(11L, count); } @Test @SuppressWarnings("deprecation") public void testStreamOfRange() { long count = Stream.ofRange(0, 5).count(); assertEquals(5, count); } @Test @SuppressWarnings("deprecation") public void testStreamOfRangeLong() { long count = Stream.ofRange(Long.MAX_VALUE - 10, Long.MAX_VALUE).count(); assertEquals(10L, count); } @Test @SuppressWarnings("deprecation") public void testStreamOfRangeClosed() { long count = Stream.ofRangeClosed(0, 5).count(); assertEquals(6, count); } @Test @SuppressWarnings("deprecation") public void testStreamOfRangeClosedLong() { long count = Stream.ofRangeClosed(Long.MAX_VALUE - 10, Long.MAX_VALUE).count(); assertEquals(11L, count); } @Test public void testGenerate() { List<Long> expected = Arrays.asList(0L, 1L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L); Stream<Long> stream = Stream.generate(Functions.fibonacci()).limit(10); assertThat(stream, elements(is(expected))); } @Test(expected = NullPointerException.class) public void testGenerateNull() { Stream.generate(null); } @Test public void testIterate() { final BigInteger two = BigInteger.valueOf(2); BigInteger sum = Stream .iterate(BigInteger.ONE, new UnaryOperator<BigInteger>() { @Override public BigInteger apply(BigInteger value) { return value.multiply(two); } }) .limit(100) .reduce(BigInteger.ZERO, new BinaryOperator<BigInteger>() { @Override public BigInteger apply(BigInteger value1, BigInteger value2) { return value1.add(value2); } }); assertEquals(new BigInteger("1267650600228229401496703205375"), sum); } @Test(expected = NullPointerException.class) public void testIterateNull() { Stream.iterate(1, null); } @Test(timeout=2000) public void testIterateIssue53() { Optional<Integer> res = Stream .iterate(0, new UnaryOperator<Integer>() { @Override public Integer apply(Integer value) { return value + 1; } }) .filter(new Predicate<Integer>() { @Override public boolean test(Integer value) { return value == 0; } }) .findFirst(); assertThat(res, isPresent()); assertThat(res.get(), is(0)); } @Test public void testIterateWithPredicate() { Predicate<Integer> condition = new Predicate<Integer>() { @Override public boolean test(Integer value) { return value < 20; } }; UnaryOperator<Integer> increment = new UnaryOperator<Integer>() { @Override public Integer apply(Integer t) { return t + 5; } }; Stream<Integer> stream = Stream.iterate(0, condition, increment); assertThat(stream, elements(is(Arrays.asList(0, 5, 10, 15)))); } @Test public void testConcat() { final PrintConsumer<String> consumer = new PrintConsumer<String>(); Stream<String> stream1 = Stream.of("a", "b", "c", "d"); Stream<String> stream2 = Stream.of("e", "f", "g", "h"); Stream<String> stream = Stream.concat(stream1, stream2); stream.forEach(consumer); assertEquals("abcdefgh", consumer.toString()); } @Test(expected = NullPointerException.class) public void testConcatNull1() { Stream.concat(null, Stream.empty()); } @Test(expected = NullPointerException.class) public void testConcatNull2() { Stream.concat(Stream.empty(), null); } @Test public void testConcatOfFilter() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Stream<Integer> stream1 = Stream.range(0, 5).filter(Functions.remainder(1)); Stream<Integer> stream2 = Stream.range(5, 10).filter(Functions.remainder(1)); Stream.concat(stream1, stream2).forEach(consumer); assertEquals("0123456789", consumer.toString()); } @Test public void testConcatOfFlatMap() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); final Function<Integer, Stream<Integer>> flatmapFunc = new Function<Integer, Stream<Integer>>() { @Override public Stream<Integer> apply(Integer value) { return Stream.of(value, value); } }; Stream<Integer> stream1 = Stream.range(1, 3).flatMap(flatmapFunc); // 1122 Stream<Integer> stream2 = Stream.range(3, 5).flatMap(flatmapFunc); // 3344 Stream.concat(stream1, stream2).forEach(consumer); assertEquals("11223344", consumer.toString()); } @Test public void testZip() { Stream<Integer> shorter = Stream.rangeClosed(1, 5); Stream<Integer> longer = Stream.rangeClosed(1, 10); Stream<Integer> zipped = Stream.zip(shorter, longer, new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer value1, Integer value2) { return value1 + value2; } }); assertThat(zipped, elements(is(Arrays.asList(2, 4, 6, 8, 10)))); } @Test(expected = NullPointerException.class) public void testZipNull1() { Stream.zip(null, Stream.<Integer>empty(), Functions.addition()); } @Test(expected = NullPointerException.class) public void testZipNull2() { Stream.zip(Stream.<Integer>empty(), null, Functions.addition()); } @Test public void testZipIterator() { List<Integer> shorter = Arrays.asList(1, 2, 3, 4, 5); Stream<Integer> longer = Stream.rangeClosed(1, 10); Stream<Integer> zipped = Stream.zip(shorter.iterator(), longer.iterator(), new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer value1, Integer value2) { return value1 + value2; } }); assertThat(zipped, elements(is(Arrays.asList(2, 4, 6, 8, 10)))); } @Test @SuppressWarnings("deprecation") public void testGetIterator() { assertThat(Stream.of(1).getIterator(), is(not(nullValue()))); } @Test public void testIterator() { assertThat(Stream.of(1).iterator(), is(not(nullValue()))); } @Test public void testFilter() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Stream.range(0, 10) .filter(Functions.remainder(2)) .forEach(consumer); assertEquals("02468", consumer.toString()); } @Test public void testFilterNot() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Stream.range(0, 10) .filterNot(Functions.remainder(2)) .forEach(consumer); assertEquals("13579", consumer.toString()); } @Test public void testNotNull() { final long notNullAmount = Stream.range(0, 10) .map(new Function<Integer, String>() { @Override public String apply(Integer integer) { return integer % 3 == 0 ? null : ""; } }) .notNull() .count(); assertEquals(6, notNullAmount); } @Test public void testNullsOnly() { final long nullsAmount = Stream.range(0, 10) .map(new Function<Integer, String>() { @Override public String apply(Integer integer) { return integer % 3 == 0 ? null : ""; } }) .nullsOnly() .count(); assertEquals(4, nullsAmount); } @Test(expected = NoSuchElementException.class) public void testFilterIteratorNextOnEmpty() { Stream.<Integer>empty() .filter(Functions.remainder(2)) .iterator() .next(); } @Test(expected = UnsupportedOperationException.class) public void testFilterIteratorRemove() { Stream.range(0, 10) .filter(Functions.remainder(2)) .iterator() .remove(); } @Test @SuppressWarnings("unchecked") public void testSelect() { final PrintConsumer<String> consumer = new PrintConsumer<String>(); Stream.of(1, "a", 2, "b", 3, "cc").select(String.class) .filter(new Predicate<String>() { @Override public boolean test(String value) { return value.length() == 1; } }).forEach(consumer); assertEquals("ab", consumer.toString()); } @Test public void testFilterWithOrPredicate() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Predicate<Integer> predicate = Predicate.Util.or(Functions.remainder(2), Functions.remainder(3)); Stream.range(0, 10) .filter(predicate) .forEach(consumer); assertEquals("0234689", consumer.toString()); } @Test public void testFilterWithAndPredicate() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Predicate<Integer> predicate = Predicate.Util.and(Functions.remainder(2), Functions.remainder(3)); Stream.range(0, 10) .filter(predicate) .forEach(consumer); assertEquals("06", consumer.toString()); } @Test public void testFilterWithXorPredicate() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Predicate<Integer> predicate = Predicate.Util.xor(Functions.remainder(2), Functions.remainder(3)); Stream.range(0, 10) .filter(predicate) .forEach(consumer); assertEquals("23489", consumer.toString()); } @Test public void testMapIntToSqrtString() { Function<Number, String> intToSqrtString = new Function<Number, String>() { @Override public String apply(Number t) { return String.format("[%d]", (int) Math.sqrt(t.intValue())); } }; List<String> expected = Arrays.asList("[2]", "[3]", "[4]", "[8]", "[25]"); Stream<String> stream = Stream.of(4, 9, 16, 64, 625) .map(intToSqrtString); assertThat(stream, elements(is(expected))); } @Test public void testMapStringToSquareInt() { final Function<String, Integer> stringToSquareInt = new Function<String, Integer>() { @Override public Integer apply(String t) { final String str = t.substring(1, t.length() - 1); final int value = Integer.parseInt(str); return value * value; } }; List<Integer> expected = Arrays.asList(4, 9, 16, 64, 625); Stream<Integer> stream = Stream.of("[2]", "[3]", "[4]", "[8]", "[25]") .map(stringToSquareInt); assertThat(stream, elements(is(expected))); } @Test public void testMapWithComposedFunction() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); final Function<Integer, Integer> mapPlus1 = new Function<Integer, Integer>() { @Override public Integer apply(Integer x) { return x + 1; } }; final Function<Integer, Integer> mapPlus2 = Function.Util.compose(mapPlus1, mapPlus1); Stream.range(-10, 0) .map(mapPlus2) .map(mapPlus2) .map(mapPlus2) .map(mapPlus2) .map(mapPlus2) .forEach(consumer); assertEquals("0123456789", consumer.toString()); } @Test public void testMapToInt() { final ToIntFunction<String> stringToSquareInt = new ToIntFunction<String>() { @Override public int applyAsInt(String t) { final String str = t.substring(1, t.length() - 1); final int value = Integer.parseInt(str); return value * value; } }; int[] expected = { 4, 9, 16, 64, 625 }; IntStream stream = Stream.of("[2]", "[3]", "[4]", "[8]", "[25]") .mapToInt(stringToSquareInt); assertThat(stream.toArray(), is(expected)); } @Test public void testMapToLong() { final ToLongFunction<String> stringToSquareLong = new ToLongFunction<String>() { @Override public long applyAsLong(String t) { final String str = t.substring(1, t.length() - 1); final long value = Long.parseLong(str); return value * value; } }; long[] expected = { 4, 9, 16, 64, 625 }; LongStream stream = Stream.of("[2]", "[3]", "[4]", "[8]", "[25]") .mapToLong(stringToSquareLong); assertThat(stream.toArray(), is(expected)); } @Test public void testMapToDouble() { final ToDoubleFunction<String> stringToDouble = new ToDoubleFunction<String>() { @Override public double applyAsDouble(String t) { return Double.parseDouble(t); } }; double[] expected = { 1.23, 4.56789, 10.1112 }; DoubleStream stream = Stream.of("1.23", "4.56789", "10.1112") .mapToDouble(stringToDouble); assertThat(stream.toArray(), is(expected)); } @Test public void testFlatMap() { final PrintConsumer<String> consumer = new PrintConsumer<String>(); Stream.rangeClosed(2, 4) .flatMap(new Function<Integer, Stream<String>>() { @Override public Stream<String> apply(final Integer i) { return Stream.rangeClosed(2, 4) .filter(Functions.remainder(2)) .map(new Function<Integer, String>() { @Override public String apply(Integer p) { return String.format("%d * %d = %d\n", i, p, (i*p)); } }); } }) .forEach(consumer); assertEquals( "2 * 2 = 4\n" + "2 * 4 = 8\n" + "3 * 2 = 6\n" + "3 * 4 = 12\n" + "4 * 2 = 8\n" + "4 * 4 = 16\n", consumer.toString()); } @Test public void testFlatMapToInt() { int[] actual = Stream.rangeClosed(2, 4) .flatMapToInt(new Function<Integer, IntStream>() { @Override public IntStream apply(Integer t) { return IntStream .iterate(t, IntUnaryOperator.Util.identity()) .limit(t); } }) .toArray(); int[] expected = { 2, 2, 3, 3, 3, 4, 4, 4, 4 }; assertThat(actual, is(expected)); } @Test public void testFlatMapToLong() { long[] actual = Stream.rangeClosed(2L, 4L) .flatMapToLong(new Function<Long, LongStream>() { @Override public LongStream apply(Long t) { return LongStream .iterate(t, LongUnaryOperator.Util.identity()) .limit(t); } }) .toArray(); long[] expected = { 2, 2, 3, 3, 3, 4, 4, 4, 4 }; assertThat(actual, is(expected)); } @Test @SuppressWarnings("unchecked") public void testFlatMapToDouble() { DoubleStream stream = Stream.of(2, 4) .flatMapToDouble(new Function<Integer, DoubleStream>() { @Override public DoubleStream apply(Integer t) { return DoubleStream.of(t / 10d, t / 20d); } }); assertThat(stream, DoubleStreamMatcher.elements(array( closeTo(0.2, 0.0001), closeTo(0.1, 0.0001), closeTo(0.4, 0.0001), closeTo(0.2, 0.0001) ))); } @Test public void testIndexed() { int[] expectedIndices = new int[] {0, 1, 2, 3}; int[] actualIndices = Stream.of("a", "b", "c", "d") .indexed() .mapToInt(Functions.<String>intPairIndex()) .toArray(); assertThat(actualIndices, is(expectedIndices)); } @Test public void testIndexedCustomStep() { int[] expectedIndices = new int[] {-10, -15, -20, -25}; int[] actualIndices = Stream.of("a", "b", "c", "d") .indexed(-10, -5) .mapToInt(Functions.<String>intPairIndex()) .toArray(); assertThat(actualIndices, is(expectedIndices)); } @Test public void testIndexedReverse() { List<String> expected = Arrays.asList("fifth", "fourth", "third", "second", "first"); Stream<String> stream = Stream.of("first", "second", "third", "fourth", "fifth") .indexed(0, -1) .sortBy(new Function<IntPair<String>, Integer>() { @Override public Integer apply(IntPair<String> t) { return t.getFirst(); } }) .map(new Function<IntPair<String>, String>() { @Override public String apply(IntPair<String> t) { return t.getSecond(); } }); assertThat(stream, elements(is(expected))); } @Test public void testDistinct() { List<Integer> expected = Arrays.asList(-1, 1, 2, 3, 5); Stream<Integer> stream = Stream.of(1, 1, 2, 3, 5, 3, 2, 1, 1, -1) .distinct() .sorted(); assertThat(stream, elements(is(expected))); } @Test public void testDistinctEmpty() { Stream<Integer> stream = Stream.<Integer>empty().distinct(); assertThat(stream, isEmpty()); } @Test public void testDistinctPreservesOrder() { List<Integer> expected = Arrays.asList(1, 2, 3, 5, -1); Stream<Integer> stream = Stream.of(1, 1, 2, 3, 5, 3, 2, 1, 1, -1) .distinct(); assertThat(stream, elements(is(expected))); } @Test public void testDistinctLazy() { List<Integer> expected = Arrays.asList(1, 2, 3, 5, -1); List<Integer> input = new ArrayList<Integer>(10); input.addAll(Arrays.asList(1, 1, 2, 3, 5)); Stream<Integer> stream = Stream.of(input).distinct(); input.addAll(Arrays.asList(3, 2, 1, 1, -1)); assertThat(stream, elements(is(expected))); } @Test public void testSorted() { List<Integer> expected = Arrays.asList(-7, 0, 3, 6, 9, 19); Stream<Integer> stream = Stream.of(6, 3, 9, 0, -7, 19).sorted(); assertThat(stream, elements(is(expected))); } @Test public void testSortedLazy() { List<Integer> expected = Arrays.asList(-7, 0, 3, 6, 9, 19); List<Integer> input = new ArrayList<Integer>(6); input.addAll(Arrays.asList(6, 3, 9)); Stream<Integer> stream = Stream.of(input).sorted(); input.addAll(Arrays.asList(0, -7, 19)); assertThat(stream, elements(is(expected))); } @Test public void testSortedWithComparator() { List<Integer> expected = Arrays.asList(19, 9, -7, 6, 3, 0); Stream<Integer> stream = Stream.of(6, 3, 9, 0, -7, 19) .sorted(Functions.descendingAbsoluteOrder()); assertThat(stream, elements(is(expected))); } @Test public void testSortByStringLength() { List<String> expected = Arrays.asList("a", "is", "This", "test"); Stream<String> stream = Stream.of("This", "is", "a", "test") .sortBy(new Function<String, Integer>() { @Override public Integer apply(String value) { return value.length(); } }); assertThat(stream, elements(is(expected))); } @Test public void testSortByStudentName() { final List<Student> students = Arrays.asList( Students.STEVE_CS_4, Students.MARIA_ECONOMICS_1, Students.VICTORIA_CS_3, Students.JOHN_CS_2 ); final List<Student> expected = Arrays.asList( Students.JOHN_CS_2, Students.MARIA_ECONOMICS_1, Students.STEVE_CS_4, Students.VICTORIA_CS_3 ); Stream<Student> stream = Stream.of(students) .sortBy(new Function<Student, String>() { @Override public String apply(Student student) { return student.getName(); } }); assertThat(stream, elements(is(expected))); } @Test public void testSortByStudentCourseDescending() { final List<Student> students = Arrays.asList( Students.STEVE_CS_4, Students.MARIA_ECONOMICS_1, Students.VICTORIA_CS_3, Students.JOHN_CS_2 ); final List<Student> expected = Arrays.asList( Students.STEVE_CS_4, Students.VICTORIA_CS_3, Students.JOHN_CS_2, Students.MARIA_ECONOMICS_1 ); Stream<Student> byCourseDesc = Stream.of(students) .sortBy(new Function<Student, Integer>() { @Override public Integer apply(Student student) { return -student.getCourse(); } }); assertThat(byCourseDesc, elements(is(expected))); } @Test public void testGroupBy() { final PrintConsumer<List<Integer>> pc1 = new PrintConsumer<List<Integer>>(); final PrintConsumer<List<Integer>> pc2 = new PrintConsumer<List<Integer>>(); final Integer partitionItem = 1; Stream.of(1, 2, 3, 1, 2, 3, 1, 2, 3) .groupBy(Functions.equalityPartitionItem(partitionItem)) .forEach(new Consumer<Map.Entry<Boolean, List<Integer>>>() { @Override public void accept(Map.Entry<Boolean, List<Integer>> entry) { (entry.getKey() ? pc1 : pc2) .accept(entry.getValue()); } }); assertEquals("[1, 1, 1]", pc1.toString()); assertEquals("[2, 3, 2, 3, 2, 3]", pc2.toString()); } @Test public void testChunkBy() { final PrintConsumer<List<Integer>> consumer = new PrintConsumer<List<Integer>>(); Stream.of(1, 1, 2, 2, 2, 3, 1) .chunkBy(UnaryOperator.Util.<Integer>identity()) .forEach(consumer); assertEquals("[1, 1][2, 2, 2][3][1]", consumer.toString()); } @Test public void testSample() { final PrintConsumer<Integer> pc1 = new PrintConsumer<Integer>(); Stream.of(1, 2, 3, 1, 2, 3, 1, 2, 3).sample(3).forEach(pc1); assertEquals("111", pc1.toString()); } @Test public void testSampleWithStep1() { final PrintConsumer<Integer> pc1 = new PrintConsumer<Integer>(); Stream.of(1, 2, 3, 1, 2, 3, 1, 2, 3).sample(1).forEach(pc1); assertEquals("123123123", pc1.toString()); } @Test(expected = IllegalArgumentException.class, timeout=1000) public void testSampleWithNegativeStep() { Stream.of(1, 2, 3, 1, 2, 3, 1, 2, 3).sample(-1).count(); } @Test public void testSlidingWindow() { long count = Stream.<Integer>empty().slidingWindow(5, 6).count(); assertEquals(0, count); final PrintConsumer<List<Integer>> pc1 = new PrintConsumer<List<Integer>>(); Stream.of(1, 1, 1, 2, 2, 2, 3, 3, 3).slidingWindow(3, 3).forEach(pc1); assertEquals("[1, 1, 1][2, 2, 2][3, 3, 3]", pc1.toString()); final PrintConsumer<List<Integer>> pc2 = new PrintConsumer<List<Integer>>(); Stream.of(1, 2, 3, 1, 2, 3, 1, 2, 3).slidingWindow(2, 3).forEach(pc2); assertEquals("[1, 2][1, 2][1, 2]", pc2.toString()); final PrintConsumer<List<Integer>> pc3 = new PrintConsumer<List<Integer>>(); Stream.of(1, 2, 3, 4, 5, 6).slidingWindow(3, 1).forEach(pc3); assertEquals("[1, 2, 3][2, 3, 4][3, 4, 5][4, 5, 6]", pc3.toString()); final PrintConsumer<List<Integer>> pc4 = new PrintConsumer<List<Integer>>(); Stream.of(1, 2, 3, 4, 5, 6).slidingWindow(3).forEach(pc4); assertEquals("[1, 2, 3][2, 3, 4][3, 4, 5][4, 5, 6]", pc4.toString()); final PrintConsumer<List<Integer>> pc5 = new PrintConsumer<List<Integer>>(); Stream.of(1, 2).slidingWindow(3, 1).forEach(pc5); assertEquals("[1, 2]", pc5.toString()); } @Test(expected = IllegalArgumentException.class) public void testSlidingWindowWithNegativeWindowSize() { Stream.of(1, 2, 3, 4).slidingWindow(-1, 1).count(); } @Test(expected = IllegalArgumentException.class, timeout=1000) public void testSlidingWindowWithNegativeStepSize() { Stream.of(1, 2, 3, 4).slidingWindow(5, -1).count(); } @Test public void testPeek() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); long count = Stream.range(0, 5) .peek(consumer) .count(); assertEquals(5, count); assertEquals("01234", consumer.toString()); } @Test public void testTakeWhile() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); long count = Stream.of(2, 4, 6, 7, 8, 10, 11) .takeWhile(Functions.remainder(2)) .peek(consumer) .count(); assertEquals(3, count); assertEquals("246", consumer.toString()); } @Test public void testTakeWhileNonFirstMatch() { assertThat( Stream.of(2, 4, 6, 7, 8, 10, 11) .takeWhile(Functions.remainder(3)), isEmpty()); } @Test public void testTakeWhileAllMatch() { long count = Stream.of(2, 4, 6, 7, 8, 10, 11) .takeWhile(Functions.remainder(1)) .count(); assertEquals(7, count); } @Test public void testDropWhile() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); long count = Stream.of(2, 4, 6, 7, 8, 10, 11) .dropWhile(Functions.remainder(2)) .peek(consumer) .count(); assertEquals(4, count); assertEquals("781011", consumer.toString()); } @Test public void testDropWhileNonFirstMatch() { long count = Stream.of(2, 4, 6, 7, 8, 10, 11) .dropWhile(Functions.remainder(3)) .count(); assertEquals(7, count); } @Test public void testDropWhileAllMatch() { assertThat( Stream.of(2, 4, 6, 7, 8, 10, 11) .dropWhile(Functions.remainder(1)), isEmpty()); } @Test public void testLimit() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Stream.range(0, 10) .limit(2) .forEach(consumer); assertEquals("01", consumer.toString()); } @Test(expected = IllegalArgumentException.class) public void testLimitNegative() { Stream.range(0, 10).limit(-2).count(); } @Test public void testLimitZero() { final Stream<Integer> stream = Stream.range(0, 10).limit(0); assertThat(stream, isEmpty()); } @Test public void testLimitMoreThanCount() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); long count = Stream.range(0, 5) .limit(15) .peek(consumer) .count(); assertEquals(5, count); assertEquals("01234", consumer.toString()); } @Test public void testSkip() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Stream.range(0, 10) .skip(7) .forEach(consumer); assertEquals("789", consumer.toString()); } @Test(expected = IllegalArgumentException.class) public void testSkipNegative() { Stream.range(0, 10).skip(-2).count(); } @Test public void testSkipZero() { long count = Stream.range(0, 2).skip(0).count(); assertEquals(2, count); } @Test public void testSkipMoreThanCount() { assertThat( Stream.range(0, 10).skip(15), isEmpty()); } @Test public void testSkipLazy() { final List<Integer> data = new ArrayList<Integer>(10); data.add(0); final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Stream<Integer> stream = Stream.of(data).skip(3); data.addAll(Arrays.asList(1, 2, 3, 4, 5)); stream = stream.peek(consumer); assertEquals(3, stream.count()); assertEquals("345", consumer.toString()); } @Test public void testSkipAndLimit() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Stream.range(0, 10) .skip(2) // 23456789 .limit(5) // 23456 .forEach(consumer); assertEquals("23456", consumer.toString()); } @Test public void testLimitAndSkip() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Stream.range(0, 10) .limit(5) // 01234 .skip(2) // 234 .forEach(consumer); assertEquals("234", consumer.toString()); } @Test public void testSkipAndLimitMoreThanCount() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Stream.range(0, 10) .skip(8) .limit(15) .forEach(consumer); assertEquals("89", consumer.toString()); } @Test public void testSkipMoreThanCountAndLimit() { long count = Stream.range(0, 10) .skip(15) .limit(8) .count(); assertEquals(0, count); } @Test public void testSkipAndLimitTwice() { final PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Stream.range(0, 10) .skip(2) // 23456789 .limit(5) // 23456 .skip(2) // 456 .limit(2) .forEach(consumer); assertEquals("45", consumer.toString()); } @Test public void testReduceSumFromZero() { int result = Stream.range(0, 10) .reduce(0, Functions.addition()); assertEquals(45, result); } @Test public void testReduceSumFromMinus45() { int result = Stream.range(0, 10) .reduce(-45, Functions.addition()); assertEquals(0, result); } @Test public void testReduceWithAnotherType() { int result = Stream.of("a", "bb", "ccc", "dddd") .reduce(0, new BiFunction<Integer, String, Integer>() { @Override public Integer apply(Integer length, String s) { return length + s.length(); } }); assertEquals(10, result); } @Test public void testReduceOptional() { Optional<Integer> result = Stream.range(0, 10) .reduce(Functions.addition()); assertThat(result, isPresent()); assertNotNull(result.get()); assertEquals(45, (int) result.get()); } @Test public void testReduceOptionalOnEmptyStream() { Optional<Integer> result = Stream.<Integer>empty() .reduce(Functions.addition()); assertThat(result, OptionalMatcher.isEmpty()); assertEquals(119, (int) result.orElse(119)); } @Test public void testCollectWithCollector() { String text = Stream.range(0, 10) .map(Functions.<Integer>convertToString()) .collect(Functions.joiningCollector()); assertEquals("0123456789", text); } @Test public void testCollectWithSupplierAndAccumulator() { String text = Stream.of("a", "b", "c", "def", "", "g") .collect(Functions.stringBuilderSupplier(), Functions.joiningAccumulator()) .toString(); assertEquals("abcdefg", text); } @Test public void testCollect123() { String string123 = Stream.of("1", "2", "3") .collect(new Supplier<StringBuilder>() { @Override public StringBuilder get() { return new StringBuilder(); } }, new BiConsumer<StringBuilder, String>() { @Override public void accept(StringBuilder value1, String value2) { value1.append(value2); } }) .toString(); assertEquals("123", string123); } @Test public void testMin() { Optional<Integer> min = Stream.of(6, 3, 9, 0, -7, 19) .min(Functions.naturalOrder()); assertThat(min, isPresent()); assertNotNull(min.get()); assertEquals(-7, (int) min.get()); } @Test public void testMinDescendingOrder() { Optional<Integer> min = Stream.of(6, 3, 9, 0, -7, 19) .min(Functions.descendingAbsoluteOrder()); assertThat(min, isPresent()); assertNotNull(min.get()); assertEquals(19, (int) min.get()); } @Test public void testMinEmpty() { Optional<Integer> min = Stream.<Integer>empty() .min(Functions.naturalOrder()); assertThat(min, OptionalMatcher.isEmpty()); } @Test public void testMax() { Optional<Integer> max = Stream.of(6, 3, 9, 0, -7, 19) .max(Functions.naturalOrder()); assertThat(max, isPresent()); assertNotNull(max.get()); assertEquals(19, (int) max.get()); } @Test public void testMaxDescendingOrder() { Optional<Integer> max = Stream.of(6, 3, 9, 0, -7, 19) .max(Functions.descendingAbsoluteOrder()); assertThat(max, isPresent()); assertNotNull(max.get()); assertEquals(0, (int) max.get()); } @Test public void testMaxEmpty() { Optional<Integer> max = Stream.<Integer>empty() .max(Functions.naturalOrder()); assertThat(max, OptionalMatcher.isEmpty()); } @Test public void testCount() { long count = Stream.range(10000000000L, 10000002000L).count(); assertEquals(2000, count); } @Test public void testCountMinValue() { long count = Stream.range(Integer.MIN_VALUE, Integer.MIN_VALUE + 100).count(); assertEquals(100, count); } @Test public void testCountMaxValue() { long count = Stream.range(Long.MAX_VALUE - 100, Long.MAX_VALUE).count(); assertEquals(100, count); } @Test public void testAnyMatchWithTrueResult() { boolean match = Stream.range(0, 10) .anyMatch(Functions.remainder(2)); assertTrue(match); } @Test public void testAnyMatchWithFalseResult() { boolean match = Stream.of(2, 3, 5, 8, 13) .allMatch(Functions.remainder(10)); assertFalse(match); } @Test public void testAllMatchWithFalseResult() { boolean match = Stream.range(0, 10) .allMatch(Functions.remainder(2)); assertFalse(match); } @Test public void testAllMatchWithTrueResult() { boolean match = Stream.of(2, 4, 6, 8, 10) .anyMatch(Functions.remainder(2)); assertTrue(match); } @Test public void testNoneMatchWithFalseResult() { boolean match = Stream.range(0, 10) .noneMatch(Functions.remainder(2)); assertFalse(match); } @Test public void testNoneMatchWithTrueResult() { boolean match = Stream.of(2, 3, 5, 8, 13) .noneMatch(Functions.remainder(10)); assertTrue(match); } @Test public void testFindFirst() { Optional<Integer> result = Stream.range(0, 10) .findFirst(); assertThat(result, isPresent()); assertNotNull(result.get()); assertEquals(0, (int) result.get()); } @Test public void testFindFirstOnEmptyStream() { assertThat(Stream.empty().findFirst(), OptionalMatcher.isEmpty()); } @Test public void testFindFirstAfterFiltering() { Optional<Integer> result = Stream.range(1, 1000) .filter(Functions.remainder(6)) .findFirst(); assertThat(result, isPresent()); assertNotNull(result.get()); assertEquals(6, (int) result.get()); } @Test(expected = NoSuchElementException.class) public void testSingleOnEmptyStream() { Stream.empty().single(); } @Test public void testSingleOnOneElementStream() { Integer result = Stream.of(42).single(); assertThat(result, is(42)); } @Test(expected = IllegalStateException.class) public void testSingleOnMoreElementsStream() { Stream.rangeClosed(1, 2).single(); } @Test(expected = NoSuchElementException.class) public void testSingleAfterFilteringToEmptyStream() { Stream.range(1, 5) .filter(Functions.remainder(6)) .single(); } @Test public void testSingleAfterFilteringToOneElementStream() { Integer result = Stream.range(1, 10) .filter(Functions.remainder(6)) .single(); assertThat(result, is(6)); } @Test(expected = IllegalStateException.class) public void testSingleAfterFilteringToMoreElementStream() { Stream.range(1, 100) .filter(Functions.remainder(6)) .single(); } @Test public void testFindSingleOnEmptyStream() { assertThat(Stream.empty().findSingle(), OptionalMatcher.isEmpty()); } @Test public void testFindSingleOnOneElementStream() { Optional<Integer> result = Stream.of(42).findSingle(); assertThat(result, hasValue(42)); } @Test(expected = IllegalStateException.class) public void testFindSingleOnMoreElementsStream() { Stream.rangeClosed(1, 2).findSingle(); } @Test public void testFindSingleAfterFilteringToEmptyStream() { Optional<Integer> result = Stream.range(1, 5) .filter(Functions.remainder(6)) .findSingle(); assertThat(result, OptionalMatcher.isEmpty()); } @Test public void testFindSingleAfterFilteringToOneElementStream() { Optional<Integer> result = Stream.range(1, 10) .filter(Functions.remainder(6)) .findSingle(); assertThat(result, hasValue(6)); } @Test(expected = IllegalStateException.class) public void testFindSingleAfterFilteringToMoreElementStream() { Stream.range(1, 100) .filter(Functions.remainder(6)) .findSingle(); } @Test public void testToArray() { Object[] objects = Stream.range(0, 200) .filter(Functions.remainder(4)) .toArray(); assertEquals(50, objects.length); assertNotNull(objects[10]); assertThat(objects[0], instanceOf(Integer.class)); } @Test public void testToArrayWithGenerator() { Integer[] numbers = Stream.range(1, 1000) .filter(Functions.remainder(2)) .toArray(Functions.arrayGenerator(Integer[].class)); assertTrue(numbers.length > 0); assertNotNull(numbers[100]); } @Test public void testToList() { assertThat(Stream.range(0, 5).toList(), contains(0, 1, 2, 3, 4)); } @Test(expected = NullPointerException.class) public void testCustomNull() { Stream.empty().custom(null); } @Test public void testCustomIntermediateOperator_Reverse() { PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Stream.range(0, 10) .custom(new CustomOperators.Reverse<Integer>()) .forEach(consumer); assertEquals("9876543210", consumer.toString()); } @Test public void testCustomIntermediateOperator_SkipAndLimit() { PrintConsumer<Integer> pc1 = new PrintConsumer<Integer>(); Stream.range(0, 10) .custom(new CustomOperators.SkipAndLimit<Integer>(5, 2)) .forEach(pc1); assertEquals("56", pc1.toString()); } @Test public void testCustomIntermediateOperator_FlatMapAndCast() { List<Character> expected = Arrays.asList('a', 'b', 'c', 'd', 'e', 'f'); List<List> lists = new ArrayList<List>(); for (char ch = 'a'; ch <= 'f'; ch++) { lists.add( new ArrayList<Character>(Arrays.asList(ch)) ); } Stream<Character> chars = Stream.of(lists) .custom(new CustomOperators.FlatMap<List, Object>(new Function<List, Stream<Object>>() { @SuppressWarnings("unchecked") @Override public Stream<Object> apply(List value) { return Stream.of(value); } })) .custom(new CustomOperators.Cast<Object, Character>(Character.class)); assertThat(chars, elements(is(expected))); } @Test public void testCustomTerminalOperator_Sum() { int sum = Stream.of(1, 2, 3, 4, 5) .custom(new CustomOperators.Sum()); assertEquals(15, sum); } @Test public void testNewArrayCompat() { String[] strings = new String[] {"abc", "def", "fff"}; String[] copy = Compat.newArrayCompat(strings, 5); assertEquals(5, copy.length); assertEquals("abc", copy[0]); assertEquals(null, copy[3]); String[] empty = new String[0]; String[] emptyCopy = Compat.newArrayCompat(empty, 3); assertEquals(3, emptyCopy.length); emptyCopy = Compat.newArrayCompat(empty, 0); assertEquals(0, emptyCopy.length); } @Test public void testCustomTerminalOperator_ForEach() { PrintConsumer<Integer> consumer = new PrintConsumer<Integer>(); Stream.range(0, 10) .custom(new CustomOperators.ForEach<Integer>(consumer)); assertEquals("0123456789", consumer.toString()); } private static class PrintConsumer<T> implements Consumer<T> { private final StringBuilder out = new StringBuilder(); @Override public void accept(T value) { out.append(value); } @Override public String toString() { return out.toString(); } } }
package it.unibz.inf.ontop.iq.node.impl; import com.google.common.collect.ImmutableSet; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.AssistedInject; import it.unibz.inf.ontop.injection.IntermediateQueryFactory; import it.unibz.inf.ontop.iq.IQTree; import it.unibz.inf.ontop.iq.IntermediateQuery; import it.unibz.inf.ontop.iq.LeafIQTree; import it.unibz.inf.ontop.iq.exception.InvalidIntermediateQueryException; import it.unibz.inf.ontop.iq.exception.QueryNodeTransformationException; import it.unibz.inf.ontop.iq.impl.IQTreeTools; import it.unibz.inf.ontop.iq.node.*; import it.unibz.inf.ontop.iq.transform.IQTransformer; import it.unibz.inf.ontop.iq.transform.node.HeterogeneousQueryNodeTransformer; import it.unibz.inf.ontop.iq.transform.node.HomogeneousQueryNodeTransformer; import it.unibz.inf.ontop.model.term.Variable; import it.unibz.inf.ontop.model.term.VariableOrGroundTerm; import it.unibz.inf.ontop.substitution.ImmutableSubstitution; public class NativeNodeImpl extends LeafIQTreeImpl implements NativeNode { private static final String NATIVE_STRING = "NATIVE "; private final ImmutableSet<Variable> variables; private final String nativeQueryString; private final VariableNullability variableNullability; @AssistedInject private NativeNodeImpl(@Assisted ImmutableSet<Variable> variables, @Assisted String nativeQueryString, @Assisted VariableNullability variableNullability, IQTreeTools iqTreeTools, IntermediateQueryFactory iqFactory) { super(iqTreeTools, iqFactory); this.variables = variables; this.nativeQueryString = nativeQueryString; this.variableNullability = variableNullability; } @Override public String getNativeQueryString() { return nativeQueryString; } @Override public void acceptVisitor(QueryNodeVisitor visitor) { throw new UnsupportedOperationException("Should NativeNode support visitors?"); } @Override public LeafIQTree acceptNodeTransformer(HomogeneousQueryNodeTransformer transformer) throws QueryNodeTransformationException { throw new UnsupportedOperationException("NativeNode does not support transformer (too late)"); } @Override public NodeTransformationProposal acceptNodeTransformer(HeterogeneousQueryNodeTransformer transformer) { throw new UnsupportedOperationException("NativeNode does not support transformer (too late)"); } @Override public ImmutableSet<Variable> getLocalVariables() { return variables; } @Override public boolean isVariableNullable(IntermediateQuery query, Variable variable) { return variableNullability.isPossiblyNullable(variable); } @Override public boolean isSyntacticallyEquivalentTo(QueryNode node) { return isEquivalentTo(node); } @Override public ImmutableSet<Variable> getLocallyRequiredVariables() { return ImmutableSet.of(); } @Override public ImmutableSet<Variable> getRequiredVariables(IntermediateQuery query) { return ImmutableSet.of(); } @Override public ImmutableSet<Variable> getLocallyDefinedVariables() { return variables; } @Override public boolean isEquivalentTo(QueryNode queryNode) { return (queryNode instanceof NativeNode) && ((NativeNode) queryNode).getVariables().equals(variables) && ((NativeNode) queryNode).getNativeQueryString().equals(nativeQueryString); } @Override public ImmutableSet<Variable> getVariables() { return variables; } @Override public IQTree acceptTransformer(IQTransformer transformer) { throw new UnsupportedOperationException("NativeNode does not support transformer (too late)"); } @Override public IQTree applyDescendingSubstitutionWithoutOptimizing(ImmutableSubstitution<? extends VariableOrGroundTerm> descendingSubstitution) { throw new UnsupportedOperationException("NativeNode does not support descending substitutions (too late)"); } @Override public ImmutableSet<Variable> getKnownVariables() { return variables; } @Override public boolean isDeclaredAsEmpty() { return false; } @Override public VariableNullability getVariableNullability() { return variableNullability; } @Override public void validate() throws InvalidIntermediateQueryException { } @Override public String toString() { return NATIVE_STRING + variables + "\n" + nativeQueryString; } }
package de.cubeisland.engine.modularity.core; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeMap; import javax.inject.Inject; import javax.inject.Provider; import de.cubeisland.engine.modularity.core.graph.DependencyGraph; import de.cubeisland.engine.modularity.core.graph.DependencyInformation; import de.cubeisland.engine.modularity.core.graph.Node; import de.cubeisland.engine.modularity.core.graph.meta.ModuleMetadata; import de.cubeisland.engine.modularity.core.graph.meta.ServiceDefinitionMetadata; import de.cubeisland.engine.modularity.core.graph.meta.ServiceImplementationMetadata; import de.cubeisland.engine.modularity.core.graph.meta.ServiceProviderMetadata; import de.cubeisland.engine.modularity.core.graph.meta.ValueProviderMetadata; import de.cubeisland.engine.modularity.core.service.InstancedServiceContainer; import de.cubeisland.engine.modularity.core.service.ProvidedServiceContainer; import de.cubeisland.engine.modularity.core.service.ProxyServiceContainer; import de.cubeisland.engine.modularity.core.service.ServiceContainer; import de.cubeisland.engine.modularity.core.service.ServiceManager; public class BasicModularity implements Modularity { private InformationLoader loader; private final DependencyGraph graph = new DependencyGraph(); private final Map<ClassLoader, Set<DependencyInformation>> infosByClassLoader = new HashMap<ClassLoader, Set<DependencyInformation>>(); private final Map<String, ModuleMetadata> modules = new HashMap<String, ModuleMetadata>(); private final Map<String, TreeMap<Integer, DependencyInformation>> services = new HashMap<String, TreeMap<Integer, DependencyInformation>>(); private final Map<String, ValueProviderMetadata> valueProviders = new HashMap<String, ValueProviderMetadata>(); private final Map<String, Instance> instances = new HashMap<String, Instance>(); // Modules and ServiceContainers private final Map<String, ValueProvider<?>> providers = new HashMap<String, ValueProvider<?>>(); private final ServiceManager serviceManager = new ServiceManager(); private final Field MODULE_META_FIELD; private final Field MODULE_MODULARITY_FIELD; public BasicModularity(InformationLoader loader) { this.loader = loader; try { MODULE_META_FIELD = Module.class.getDeclaredField("metadata"); MODULE_META_FIELD.setAccessible(true); MODULE_MODULARITY_FIELD = Module.class.getDeclaredField("modularity"); MODULE_MODULARITY_FIELD.setAccessible(true); } catch (NoSuchFieldException e) { throw new IllegalStateException(); } this.registerProvider(URL.class, new SourceURLProvider()); } @Override public Set<Node> load(File source) { Set<DependencyInformation> loaded = getLoader().loadInformation(source); Set<Node> nodes = new HashSet<Node>(); if (loaded.isEmpty()) { System.out.println("No DependencyInformation could be extracted from target source!"); // TODO } for (DependencyInformation info : loaded) { if (!(info instanceof ServiceImplementationMetadata)) { nodes.add(graph.addNode(info)); } String className = info.getClassName(); if (info instanceof ModuleMetadata) { modules.put(className, (ModuleMetadata)info); } else if (info instanceof ValueProviderMetadata) { valueProviders.put(((ValueProviderMetadata)info).getValueName(), (ValueProviderMetadata)info); } else { if (info instanceof ServiceProviderMetadata) { className = ((ServiceProviderMetadata)info).getServiceName(); } TreeMap<Integer, DependencyInformation> services = this.services.get(className); if (services == null) { services = new TreeMap<Integer, DependencyInformation>(); this.services.put(className, services); } String version = info.getVersion(); if ("unknown".equals(version)) { version = "0"; } try { services.put(Integer.valueOf(version), info); } catch (NumberFormatException e) { services.put(0, info); } } Set<DependencyInformation> set = infosByClassLoader.get(info.getClassLoader()); if (set == null) { set = new HashSet<DependencyInformation>(); infosByClassLoader.put(info.getClassLoader(), set); } set.add(info); } return nodes; } @Override public Object start(Node node) { if (node == null) { return null; } DependencyInformation info = node.getInformation(); if (info == null || info instanceof ServiceImplementationMetadata) // Not found OR Implementation { return null; } Object instance = this.start(info); Object result = instance; if (instance instanceof ServiceContainer) { if (instance instanceof ProxyServiceContainer) { if (!((ProxyServiceContainer)instance).hasImplementations()) { startServiceImplementation((ProxyServiceContainer)instance); } } result = ((ServiceContainer)instance).getImplementation(); } return result; } private Object start(DependencyInformation info) { depth++; Object result = getInstance(info); if (result == null) { show("Starting", info); Map<String, Object> instances = collectDependencies(info); result = newInstance(info, instances); startServiceImplementations(instances); enableInstance(info, result); show("done.\n", null); } else { show("- get", info); } depth return result; } private void enableInstance(DependencyInformation info, Object instance) { show("enable", info); if (instance instanceof InstancedServiceContainer) { instance = ((InstancedServiceContainer)instance).getImplementation(); } if (instance instanceof ProvidedServiceContainer) { instance = ((ProvidedServiceContainer)instance).getProvider(); } String enableMethod = info.getEnableMethod(); if (enableMethod != null) { try { Method method = instance.getClass().getMethod(enableMethod); method.invoke(instance); // TODO allow Parameters (add to dependencies) } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } catch (InvocationTargetException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } } private Object getInstance(DependencyInformation info) { String identifier = info.getClassName(); if (info instanceof ServiceImplementationMetadata) { identifier = ((ServiceImplementationMetadata)info).getServiceName(); } try { if (info instanceof ServiceDefinitionMetadata) { ServiceContainer<?> service = serviceManager.getService(Class.forName(info.getClassName(), true, info.getClassLoader())); if (service != null) { return service; } } if (info instanceof ServiceProviderMetadata) { ServiceContainer<?> service = serviceManager.getService(Class.forName(((ServiceProviderMetadata)info).getServiceName(), true, info.getClassLoader())); if (service != null) { return service; } } } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } return instances.get(identifier); } private void startServiceImplementations(Map<String, Object> instances) { show("Search for impls <", null); for (Object instance : instances.values()) { if (instance instanceof ProxyServiceContainer && !((ProxyServiceContainer)instance).hasImplementations()) { startServiceImplementation((ProxyServiceContainer)instance); } } show(">", null); } private void startServiceImplementation(ProxyServiceContainer container) { for (TreeMap<Integer, DependencyInformation> map : services.values()) { for (DependencyInformation impl : map.values()) { if (impl instanceof ServiceImplementationMetadata && ((ServiceImplementationMetadata)impl).getServiceName().equals(container.getInterface().getName())) { Map<String, Object> deps = collectDependencies(impl); Object instance = newInstance(impl, deps); startServiceImplementations(deps); enableInstance(impl, instance); } } } } private Map<String, Object> collectDependencies(DependencyInformation info) { show("Collect dependencies of", info); Map<String, Object> result = new HashMap<String, Object>(); collectDependencies(info, info.requiredDependencies(), result, true); collectDependencies(info, info.optionalDependencies(), result, false); return result; } private void collectDependencies(DependencyInformation info, Set<String> deps, Map<String, Object> collected, boolean required) { for (String dep : deps) { ValueProvider<?> provider = providers.get(dep); if (provider != null) { collected.put(dep, provider.get(info, this)); continue; } try { ServiceContainer<?> service = serviceManager.getService(Class.forName(dep, true, info.getClassLoader())); if (service!=null) { collected.put(dep, service.getImplementation()); continue; } } catch (ClassNotFoundException ignored) {} catch (NullPointerException e) { System.out.println(e); } DependencyInformation dependency = getDependencyInformation(dep); if (dependency == null) { if (required) { throw new MissingDependencyException(info, dep); } System.out.println("Missing optional dependency to: " + dep); continue; } if (dependency instanceof ValueProviderMetadata) { collected.put(dep, start(dependency)); } else { String className = dependency.getClassName(); if (dependency instanceof ServiceProviderMetadata) { className = ((ServiceProviderMetadata)dependency).getServiceName(); } collected.put(className, start(dependency)); } } } private DependencyInformation getDependencyInformation(String dependencyString) { ModuleMetadata module = modules.get(dependencyString); if (module != null) { return module; } ValueProviderMetadata value = valueProviders.get(dependencyString); if (value != null) { return value; } int versionAt = dependencyString.indexOf(':'); Integer version = null; if (versionAt != -1) { version = Integer.parseInt(dependencyString.substring(versionAt + 1, dependencyString.length())); dependencyString = dependencyString.substring(0, versionAt); } TreeMap<Integer, DependencyInformation> services = this.services.get(dependencyString); if (services != null) { if (version == null) { return services.lastEntry().getValue(); } else { return services.get(version); } } return null; } private Object newInstance(DependencyInformation info, Map<String, Object> deps) { try { show("Start", info); Class<?> instanceClass = Class.forName(info.getClassName(), true, info.getClassLoader()); Object instance; if (info instanceof ServiceDefinitionMetadata) { serviceManager.registerService(instanceClass, info); instance = serviceManager.getService(instanceClass); } else // Module, ServiceImpl, ServiceProvider, ValueProvider { Constructor<?> constructor = getConstructor(info, deps, instanceClass); final Object created = constructor.newInstance(getConstructorParams(deps, constructor)); injectDependencies(deps, created, info); if (info instanceof ServiceImplementationMetadata) { Class serviceClass = Class.forName(((ServiceImplementationMetadata)info).getServiceName(), true, info.getClassLoader()); serviceManager.registerService(serviceClass, created); return created; } if (info instanceof ServiceProviderMetadata) { serviceManager.registerService((ServiceProviderMetadata)info, created); } instance = created; } if (instance == null) { throw new IllegalStateException(); } if (instance instanceof Instance) { String name = info.getClassName(); if (info instanceof ServiceProviderMetadata) { name = ((ServiceProviderMetadata)info).getServiceName(); } this.instances.put(name, (Instance)instance); } else if (instance instanceof ValueProvider) { this.providers.put(((ValueProviderMetadata)info).getValueName(), (ValueProvider<?>)instance); } return instance; } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } catch (InvocationTargetException e) { throw new IllegalStateException(e); } catch (InstantiationException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } private void injectDependencies(Map<String, Object> deps, Object instance, DependencyInformation info) throws IllegalAccessException { if (instance instanceof Module) { MODULE_META_FIELD.set(instance, info); MODULE_MODULARITY_FIELD.set(instance, this); } for (Field field : instance.getClass().getDeclaredFields()) { if (field.isAnnotationPresent(Inject.class)) { Class<?> type = field.getType(); boolean maybe = Maybe.class.equals(type); if (maybe) { type = (Class)((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0]; } Object toSet = deps.get(type.getName()); if (!maybe && toSet == null) { throw new IllegalStateException(); } if (toSet instanceof ServiceContainer) { toSet = ((ServiceContainer)toSet).getImplementation(); } if (toSet instanceof Provider) { toSet = ((Provider)toSet).get(); } if (toSet instanceof ValueProvider) { toSet = ((ValueProvider)toSet).get(info, this); } if (maybe) { toSet = new SettableMaybe(toSet); // TODO save to be able to provide/remove module later } field.setAccessible(true); field.set(instance, toSet); } } } private Object[] getConstructorParams(Map<String, Object> deps, Constructor<?> instanceConstructor) { Object[] parameters; Class<?>[] parameterTypes = instanceConstructor.getParameterTypes(); parameters = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { final Class<?> type = parameterTypes[i]; Object instance = deps.get(type.getName()); if (instance instanceof ServiceContainer) { parameters[i] = ((ServiceContainer)instance).getImplementation(); } else if (instance instanceof Provider) { parameters[i] = ((Provider)instance).get(); } else { parameters[i] = instance; } } return parameters; } private Constructor<?> getConstructor(DependencyInformation info, Map<String, Object> deps, Class<?> instanceClass) { Constructor<?> instanceConstructor = null; for (Constructor<?> constructor : instanceClass.getConstructors()) { boolean ok = true; for (Class<?> dep : constructor.getParameterTypes()) { ok = ok && deps.containsKey(dep.getName()); // TODO what if it was optional? } if (ok) { instanceConstructor = constructor; break; } } if (instanceConstructor == null) { throw new IllegalStateException(info.getClassName() + " has no usable Constructor");// TODO error } instanceConstructor.setAccessible(true); return instanceConstructor; } private int depth = -1; @Override public Class<?> getClazz(String name, Set<String> dependencies) { if (name == null) { return null; } Set<String> checked = new HashSet<String>(); Class clazz = getClazz(name, checked, dependencies); if (clazz == null) { clazz = getClazz(name, checked, modules.keySet()); } return clazz; } @Override public DependencyGraph getGraph() { return this.graph; } @Override public ServiceManager getServiceManager() { return this.serviceManager; } private Class<?> getClazz(String name, Set<String> checked, Set<String> strings) { for (String dep : strings) { if (checked.contains(dep)) { continue; } checked.add(dep); try { DependencyInformation info = getDependencyInformation(dep); if (info != null) { return info.getClassLoader().findClass(name, false); } } catch (ClassNotFoundException ignored) { } } return null; } @Override public Set<ServiceContainer<?>> getServices() { return serviceManager.getServices(); } @Override public Set<Module> getModules() { return Collections.emptySet(); // TODO } @Override @SuppressWarnings("unchecked") public <T> T start(Class<T> type) { ServiceContainer<T> service = serviceManager.getService(type); if (service instanceof InstancedServiceContainer) { return service.getImplementation(); } return (T)start(graph.getNode(type.getName())); } @Override public void startAll() { startRecursive(getGraph().getRoot()); } @Override public Set<Node> unload(Node node) { if (node.getInformation() == null) { return Collections.emptySet(); } Object instance = getInstance(node.getInformation()); if (instance == null) { System.out.println(node.getInformation().getClassName() + " is not loaded"); return Collections.emptySet(); } if (node.getInformation() instanceof ServiceImplementationMetadata) { Node serviceNode = graph.getNode(((ServiceImplementationMetadata)node.getInformation()).getServiceName()); Object serviceInstance = getInstance(serviceNode.getInformation()); if (!(serviceInstance instanceof ProxyServiceContainer)) { throw new IllegalStateException("Service was not in a Container"); } if (((ProxyServiceContainer)serviceInstance).getImplementations().size() > 1) { stop(node, instance); return Collections.singleton(node); } // else unload predecessors too } Set<Node> unloaded = new HashSet<Node>(); for (Node pre : node.getPredecessors()) { unloaded.addAll(unload(pre)); } stop(node, instance); unloaded.add(node); return unloaded; } @SuppressWarnings("unchecked") private void stop(Node node, Object instance) { String disableMethod = node.getInformation().getDisableMethod(); if (disableMethod != null) { try { Method method = instance.getClass().getMethod(disableMethod); method.setAccessible(true); method.invoke(instance); } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } catch (InvocationTargetException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } if (instance instanceof Module) { instances.values().remove(instance); } else if (instance instanceof ProxyServiceContainer) { if (node instanceof ServiceDefinitionMetadata) { // TODO stop all implementations for (Object impl : ((ProxyServiceContainer)instance).getImplementations()) { ((ProxyServiceContainer)instance).removeImplementation(impl); } instances.values().remove(instance); } else { Object found = null; for (Object impl : ((ProxyServiceContainer)instance).getImplementations()) { if (node.getInformation().getClassName().equals(impl.getClass().getName())) { found = impl; break; } } if (found == null) { throw new IllegalStateException("Tried to remove missing Implementation: " + node.getInformation().getClassName()); } ProxyServiceContainer service = ((ProxyServiceContainer)instance).removeImplementation(found); if (!service.hasImplementations()) { instances.values().remove(service); } } } } @Override public void reload(Node node) { Set<Node> unloaded = unload(node); for (Node reload : unloaded) { start(reload); } } private void startRecursive(Node node) { if (node.getInformation() != null) { start(node); } for (Node suc : node.getSuccessors()) { startRecursive(suc); } } @Override public <T> void registerProvider(Class<T> clazz, ValueProvider<T> provider) { this.providers.put(clazz.getName(), provider); graph.provided(clazz); } @Override @SuppressWarnings("unchecked") public <T> ValueProvider<T> getProvider(Class<T> clazz) { ValueProvider<T> provider = (ValueProvider<T>)providers.get(clazz.getName()); if (provider != null) { return provider; } ValueProviderMetadata meta = valueProviders.get(clazz.getName()); if (meta != null) { return (ValueProvider<T>)start(meta); } return null; } private void show(String show, DependencyInformation clazz) { if (1 == 1) { return; } for (int i1 = 0; i1 < depth; i1++) { System.out.print("\t"); } String name = ""; if (clazz != null) { name = clazz.getClassName(); name = name.substring(name.lastIndexOf(".") + 1); name += ":" + clazz.getVersion(); } if (clazz != null) { Object instance = getInstance(clazz); if (instance != null) { if (instance instanceof ProxyServiceContainer && !((ProxyServiceContainer)instance).hasImplementations()) { name = "[" + name + "]"; } } else { name = "[" + name + "]"; } } System.out.println(show + " " + name); } @Override public InformationLoader getLoader() { return loader; } @Override public Set<Instance> getNodes() { return new HashSet<Instance>(instances.values()); } }
package ru.job4j.tracker; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; .java.ulil.Date.*; /** * Class TrackerTest. * @author Yury Chuksin (chuksin.yury@gmail.com) * @since 19.02.2017 */ public class TrackerTest { /** * tracker create new empty object Tracker. */ private Tracker tracker = new Tracker(); /** * date new empty object Date. */ Date date = new Date(); /** * itemsR control array for test. */ private Item[] itemsR = new Item[new Item("name1", "descipt1", date.getTime()), new Item("name2", "descipt2", date.getTime())]; /** * itemT1 create new test object Item. */ private final Item itemT1 = new Item("name1", "descipt1", date.getTime()); /** * itemT2 create new test object Item. */ private final Item itemT2 = new Item("name2", "descipt2", date.getTime()); /** * itemT3 create new test object Item. */ private final Item itemT3 = new Item("changeName", "changeDescript", date.getTime()); /** * whenDoAddItemthenGetAddingItemToArray compare two array. */ @Test public void whenDoAddItemthenGetAddingItemToArray() { this.tracker.addItem(this.itemT1); this.tracker.addItem(this.itemT2); assertThat(this.itemsR, is(this.tracker.getListOfItems())); } /** * whenDoFindByNameThenGetItemByName compare two array with finding one by name. */ @Test public void whenDoFindByNameThenGetItemByName() { this.tracker.addItem(this.itemT1); this.tracker.addItem(this.itemT2); assartThat(this.itemT2, is(this.tracker.findByName("name2"))); } /** * whenFindByIdThenGetItemById compare two array with finding one by id. */ @Test public void whenFindByIdThenGetItemById() { this.tracker.addItem(this.itemT1); this.tracker.addItem(this.itemT2); assertThat(this.itemT1, is(this.tracker.findById("1"))); } /** * whenDoRedactItemThenGetEditItem method must update Item. */ @Test public void whenDoRedactItemThenGetEditItem() { this.tracker.addItem(this.itemT1); this.tracker.addItem(this.itemT2); this.itemT3.setComment("new comment"); this.itemT3.setId("2"); assertThat(this.itemT3, is(this.tracker.redactItem(new Item("changeName", "changeDescript", this.date.getTime(), "new comment", "2")))); } /** * whenDoDeleteItemThenGetEraseOneItem method must delete Item. */ @Test public void whenDoDeleteItemThenGetEraseOneItem() { this.tracker.addItem(this.itemT1); this.tracker.addItem(this.itemT2); Item itemNull = this.tracker.deleteItem("1"); assertThat(null, is(itemNull)); } /** * whenDoGetListOfItemsThenGetArrayList method must get all items. */ @Test public void whenDoGetListOfItemsThenGetArrayList() { this.tracker.addItem(this.itemT1); this.tracker.addItem(this.itemT2); assertThat(this.itemsR, is(this.tracker.getListOfItems())); } }
package org.mskcc.cbio.portal.scripts; import org.mskcc.cbio.portal.dao.*; import org.mskcc.cbio.portal.model.*; import org.mskcc.cbio.portal.util.*; import org.apache.commons.lang.StringUtils; import org.apache.commons.math.stat.descriptive.DescriptiveStatistics; import java.io.*; import java.util.*; import java.util.regex.*; /** * Import protein array data into database * @author jj */ public class ImportProteinArrayData { private ProgressMonitor pMonitor; private int cancerStudyId; private String cancerStudyStableId; private File arrayData; public ImportProteinArrayData(File arrayData, int cancerStudyId, String cancerStudyStableId, ProgressMonitor pMonitor) { this.arrayData = arrayData; this.cancerStudyId = cancerStudyId; this.cancerStudyStableId = cancerStudyStableId; this.pMonitor = pMonitor; } /** * Import RPPA data. Profiles and a case list will also be added here. * @throws IOException * @throws DaoException */ public void importData() throws IOException, DaoException { MySQLbulkLoader.bulkLoadOff(); // import array data DaoProteinArrayData daoPAD = DaoProteinArrayData.getInstance(); FileReader reader = new FileReader(arrayData); BufferedReader buf = new BufferedReader(reader); String line = buf.readLine(); String[] sampleIds = line.split("\t"); Sample[] samples = new Sample[sampleIds.length-1]; for (int i=1; i<sampleIds.length; i++) { samples[i-1] = DaoSample.getSampleByCancerStudyAndSampleId(cancerStudyId, StableIdUtil.getSampleId(sampleIds[i])); } ArrayList<Integer> internalSampleIds = new ArrayList<Integer>(); while ((line=buf.readLine()) != null) { if (pMonitor != null) { pMonitor.incrementCurValue(); ConsoleUtil.showProgress(pMonitor); } String[] strs = line.split("\t"); String arrayInfo = strs[0]; String arrayId = importArrayInfo(arrayInfo); double[] zscores = convertToZscores(strs); for (int i=0; i<zscores.length; i++) { if (samples[i]==null) { continue; } int sampleId = samples[i].getInternalId(); ProteinArrayData pad = new ProteinArrayData(cancerStudyId, arrayId, sampleId, zscores[i]); daoPAD.addProteinArrayData(pad); internalSampleIds.add(sampleId); } } // import profile addRPPAProfile(internalSampleIds); } private double[] convertToZscores(String[] strs) { double[] data = new double[strs.length-1]; for (int i=1; i<strs.length; i++) { // ignore the first column data[i-1] = Double.parseDouble(strs[i]); } DescriptiveStatistics ds = new DescriptiveStatistics(data); double mean = ds.getMean(); double std = ds.getStandardDeviation(); for (int i=0; i<data.length; i++) { data[i] = (data[i]-mean)/std; } return data; } private String importArrayInfo(String info) throws DaoException { DaoProteinArrayInfo daoPAI = DaoProteinArrayInfo.getInstance(); DaoProteinArrayTarget daoPAT = DaoProteinArrayTarget.getInstance(); DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); String[] parts = info.split("\\|"); String[] genes = parts[0].split(" "); fixSymbols(genes); String arrayId = parts[1]; Pattern p = Pattern.compile("(p[STY][0-9]+)"); Matcher m = p.matcher(arrayId); String type, residue; if (m.find()) { type = "phosphorylation"; residue = m.group(1); importPhosphoGene(genes, residue, arrayId); } else { type = "protein_level"; p = Pattern.compile("(cleaved[A-Z][0-9]+)"); m = p.matcher(arrayId); residue = m.find() ? m.group(1) : null; importRPPAProteinAlias(genes); } if (daoPAI.getProteinArrayInfo(arrayId)==null) { ProteinArrayInfo pai = new ProteinArrayInfo(arrayId, type, StringUtils.join(genes, "/"), residue, null); daoPAI.addProteinArrayInfo(pai); for (String symbol : genes) { CanonicalGene gene = daoGene.getNonAmbiguousGene(symbol); if (gene==null) { System.err.println(symbol+" not exist"); continue; } long entrez = gene.getEntrezGeneId(); daoPAT.addProteinArrayTarget(arrayId, entrez); } } if (!daoPAI.proteinArrayCancerStudyAdded(arrayId, cancerStudyId)) { daoPAI.addProteinArrayCancerStudy(arrayId, Collections.singleton(cancerStudyId)); } return arrayId; } private void fixSymbols(String[] genes) { int n = genes.length; for (int i=0; i<n; i++) { if (genes[i].equalsIgnoreCase("CDC2")) { genes[i] = "CDK1"; } } } private void importPhosphoGene(String[] genes, String residue, String arrayId) throws DaoException { DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); String phosphoSymbol = StringUtils.join(genes, "/")+"_"+residue; Set<String> aliases = new HashSet<String>(); aliases.add(arrayId); aliases.add("rppa-phospho"); aliases.add("phosphoprotein"); for (String gene : genes) { aliases.add("phospho"+gene); } CanonicalGene phosphoGene = new CanonicalGene(phosphoSymbol, aliases); phosphoGene.setType(CanonicalGene.PHOSPHOPROTEIN_TYPE); daoGene.addGene(phosphoGene); } private void importRPPAProteinAlias(String[] genes) throws DaoException { DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); for (String gene : genes) { CanonicalGene existingGene = daoGene.getGene(gene); if (existingGene!=null) { Set<String> aliases = new HashSet<String>(); aliases.add("rppa-protein"); existingGene.setAliases(aliases); daoGene.addGene(existingGene); } } } private void addRPPAProfile(ArrayList<Integer> sampleIds) throws DaoException { // add profile String idProfProt = cancerStudyStableId+"_RPPA_protein_level"; if (DaoGeneticProfile.getGeneticProfileByStableId(idProfProt)==null) { GeneticProfile gpPro = new GeneticProfile(idProfProt, cancerStudyId, GeneticAlterationType.PROTEIN_ARRAY_PROTEIN_LEVEL, "Z-SCORE", "protein/phosphoprotein level (RPPA)", "Protein or phosphoprotein level (Z-scores) measured by reverse phase protein array (RPPA)", true); DaoGeneticProfile.addGeneticProfile(gpPro); DaoGeneticProfileSamples.addGeneticProfileSamples( DaoGeneticProfile.getGeneticProfileByStableId(idProfProt).getGeneticProfileId(), sampleIds); } } public static void main(String[] args) throws Exception { // args = new String[] {"/Users/jgao/projects/cbio-portal-data/studies/cellline/douglevine_ccl/data_rppa.txt","cellline_douglevine_ccl"}; if (args.length < 2) { System.out.println("command line usage: importRPPAData.pl <RPPA_data.txt> <Cancer study identifier>"); return; } int cancerStudyId = DaoCancerStudy.getCancerStudyByStableId(args[1]).getInternalId(); ProgressMonitor pMonitor = new ProgressMonitor(); pMonitor.setConsoleMode(true); File file = new File(args[0]); System.out.println("Reading data from: " + file.getAbsolutePath()); int numLines = FileUtil.getNumLines(file); System.out.println(" --> total number of lines: " + numLines); pMonitor.setMaxValue(numLines); ImportProteinArrayData parser = new ImportProteinArrayData(file, cancerStudyId, args[1], pMonitor); parser.importData(); ConsoleUtil.showWarnings(pMonitor); System.err.println("Done."); } /** * add extra antibodies of normalized phosphoprotein data * @param args * @throws Exception */ public static void main_normalize_phospho(String[] args) throws Exception { DaoProteinArrayData daoPAD = DaoProteinArrayData.getInstance(); DaoProteinArrayInfo daoPAI = DaoProteinArrayInfo.getInstance(); DaoProteinArrayTarget daoPAT = DaoProteinArrayTarget.getInstance(); DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); DaoPatientList daoPatientList = new DaoPatientList(); ArrayList<CancerStudy> studies = DaoCancerStudy.getAllCancerStudies(); for (CancerStudy study : studies) { int studyId = study.getInternalId(); PatientList patientlist = daoPatientList.getPatientListByStableId(study.getCancerStudyStableId()+"_RPPA"); if (patientlist==null) continue; List<Integer> sampleIds = InternalIdUtil.getInternalSampleIds(studyId, patientlist.getPatientList()); ArrayList<ProteinArrayInfo> phosphoArrays = daoPAI.getProteinArrayInfoForType( studyId, Collections.singleton("phosphorylation")); ArrayList<ProteinArrayInfo> proteinArrays = daoPAI.getProteinArrayInfoForType( studyId, Collections.singleton("protein_level")); for (ProteinArrayInfo phosphoArray : phosphoArrays) { for (ProteinArrayInfo proteinArray : proteinArrays) { if (proteinArray.getGene().equals(phosphoArray.getGene())) { String id = phosphoArray.getId()+"-"+proteinArray.getId(); if (id.matches(".+-.+-.+")) continue; System.out.println(study.getCancerStudyStableId()+" "+id+" " +phosphoArray.getGene()+" "+phosphoArray.getResidue()); ProteinArrayInfo pai = new ProteinArrayInfo(id,"phosphorylation", phosphoArray.getGene(),phosphoArray.getResidue(),null); daoPAI.addProteinArrayInfo(pai); for (String symbol : phosphoArray.getGene().split("/")) { CanonicalGene gene = daoGene.getNonAmbiguousGene(symbol); if (gene==null) { System.err.println(symbol+" not exist"); continue; } long entrez = gene.getEntrezGeneId(); try { daoPAT.addProteinArrayTarget(id, entrez); } catch (Exception e) { e.printStackTrace(); } } daoPAI.addProteinArrayCancerStudy(id, Collections.singleton(studyId)); ArrayList<ProteinArrayData> phosphoData = daoPAD.getProteinArrayData( studyId, Collections.singleton(phosphoArray.getId()), sampleIds); ArrayList<ProteinArrayData> proteinData = daoPAD.getProteinArrayData( studyId, Collections.singleton(proteinArray.getId()), sampleIds); HashMap<Integer,ProteinArrayData> mapProteinData = new HashMap<Integer,ProteinArrayData>(); for (ProteinArrayData pad : proteinData) { mapProteinData.put(pad.getSampleId(), pad); } for (ProteinArrayData pad : phosphoData) { Integer sampleId = pad.getSampleId(); ProteinArrayData proteinPAD = mapProteinData.get(sampleId); if (proteinPAD==null) { System.err.println("no data: "+proteinPAD.getArrayId()+" "+sampleId); continue; } double abud = pad.getAbundance() - proteinPAD.getAbundance(); // minus ProteinArrayData norm = new ProteinArrayData(studyId, id, sampleId, abud); daoPAD.addProteinArrayData(norm); } //break; } } } } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.netbeans.cubeon.ui.query; import java.awt.Component; import java.awt.Dialog; import java.awt.event.ActionEvent; import java.text.MessageFormat; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.AbstractAction; import javax.swing.JComponent; import org.netbeans.cubeon.tasks.core.api.CubeonContext; import org.netbeans.cubeon.tasks.core.api.TaskRepositoryHandler; import org.netbeans.cubeon.tasks.spi.repository.TaskRepository; import org.netbeans.cubeon.tasks.spi.query.TaskQuery; import org.netbeans.cubeon.tasks.spi.query.TaskQuerySupportProvider; import org.openide.DialogDisplayer; import org.openide.WizardDescriptor; import org.openide.util.HelpCtx; import org.openide.util.Lookup; public final class NewQueryWizardAction extends AbstractAction { private WizardDescriptor.Panel<WizardObject>[] panels; private TaskRepository taskRepository; public NewQueryWizardAction(String name) { init(name); } private void init(String name) { putValue(NAME, name); } public void preferredRepository(TaskRepository repository) { this.taskRepository = repository; } /** * Initialize panels representing individual wizard's steps and sets * various properties for them influencing wizard appearance. */ private WizardDescriptor.Panel[] getPanels() { if (panels == null) { //lookup CubeonContext CubeonContext cubeonContext = Lookup.getDefault().lookup(CubeonContext.class); assert cubeonContext != null : "CubeonContext can't be null"; //lookup TaskRepositoryHandler TaskRepositoryHandler repositoryHandler = cubeonContext.getLookup().lookup(TaskRepositoryHandler.class); List<TaskRepository> repositorys = repositoryHandler.getTaskRepositorys(); Collections.sort(repositorys, new Comparator<TaskRepository>() { public int compare(TaskRepository o1, TaskRepository o2) { return o1.getName().compareTo(o2.getName()); } }); if (taskRepository != null || repositorys.size() == 1) { if (taskRepository == null) { taskRepository = repositorys.get(0); } panels = new WizardDescriptor.Panel[]{new TaskQueryAttributesWizard(taskRepository)}; } else { panels = new WizardDescriptor.Panel[]{ new ChooseRepositoryWizard(repositorys), new TaskQueryAttributesWizard() }; } String[] steps = new String[panels.length]; for (int i = 0; i < panels.length; i++) { Component c = panels[i].getComponent(); // Default step name to component name of panel. Mainly useful // for getting the name of the target chooser to appear in the // list of steps. steps[i] = c.getName(); if (c instanceof JComponent) { // assume Swing components JComponent jc = (JComponent) c; // Sets step number of a component jc.putClientProperty("WizardPanel_contentSelectedIndex", new Integer(i)); // Sets steps names for a panel jc.putClientProperty("WizardPanel_contentData", steps); // Turn on subtitle creation on each step jc.putClientProperty("WizardPanel_autoWizardStyle", Boolean.FALSE); // Show steps on the left side with the image on the background jc.putClientProperty("WizardPanel_contentDisplayed", Boolean.FALSE); // Turn on numbering of all steps jc.putClientProperty("WizardPanel_contentNumbered", Boolean.FALSE); } } } return panels; } public HelpCtx getHelpCtx() { return HelpCtx.DEFAULT_HELP; } public void actionPerformed(ActionEvent e) { final WizardObject wizardObject = new WizardObject(); WizardDescriptor wizardDescriptor = new WizardDescriptor(getPanels(), wizardObject); // {0} will be replaced by WizardDesriptor.Panel.getComponent().getName() wizardDescriptor.setTitleFormat(new MessageFormat("{0}")); Dialog dialog = DialogDisplayer.getDefault().createDialog(wizardDescriptor); dialog.setVisible(true); dialog.toFront(); if (wizardDescriptor.getValue() == WizardDescriptor.FINISH_OPTION) { TaskQuery query = wizardObject.getQuery(); assert query != null; TaskRepository repository = wizardObject.getRepository(); assert repository != null; TaskQuerySupportProvider tqsp = repository.getLookup().lookup(TaskQuerySupportProvider.class); tqsp.addTaskQuery(query); //open query results view ResultsTopComponent component = ResultsTopComponent.findInstance(); component.open(); component.requestActive(); component.showResults(query); query.synchronize(); } } static class WizardObject { private TaskQuery query; private TaskRepository repository; public WizardObject() { } public WizardObject(TaskQuery query, TaskRepository repository) { this.query = query; this.repository = repository; } public TaskRepository getRepository() { return repository; } public void setRepository(TaskRepository repository) { this.repository = repository; } public TaskQuery getQuery() { return query; } public void setQuery(TaskQuery query) { this.query = query; } } }
package io.spine.server.storage.datastore; import com.google.cloud.datastore.Datastore; import com.google.cloud.datastore.DatastoreOptions; import com.google.common.testing.EqualsTester; import com.google.common.testing.NullPointerTester; import io.spine.testing.server.storage.datastore.TestDatastores; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static com.google.common.truth.Truth.assertThat; import static io.spine.testing.DisplayNames.NOT_ACCEPT_NULLS; import static io.spine.testing.server.storage.datastore.TestDatastores.local; @DisplayName("`ProjectId` should") class ProjectIdTest { @Test @DisplayName(NOT_ACCEPT_NULLS) void testNulls() { new NullPointerTester() .setDefault(Datastore.class, TestDatastores.local()) .testStaticMethods(ProjectId.class, NullPointerTester.Visibility.PACKAGE); } @Test @DisplayName("support equality") void testEquals() { ProjectId a1 = ProjectId.of("a"); ProjectId a2 = ProjectId.of(datastore("a")); ProjectId b1 = ProjectId.of("b"); ProjectId b2 = ProjectId.of(datastore("b")); new EqualsTester() .addEqualityGroup(a1, a2) .addEqualityGroup(b1, b2) .testEquals(); } @Test @DisplayName("support `toString()`") void testToString() { String value = "my-fancy-project-id"; ProjectId projectId = ProjectId.of(value); String idAsString = projectId.toString(); assertThat(idAsString).contains(value); } private static Datastore datastore(String projectId) { DatastoreOptions options = local().getOptions() .toBuilder() .setProjectId(projectId) .build(); Datastore datastore = options.getService(); return datastore; } }
package org.hisp.dhis.scheduling; import static org.hisp.dhis.scheduling.JobStatus.DISABLED; import static org.hisp.dhis.scheduling.JobStatus.SCHEDULED; import static org.hisp.dhis.schema.annotation.Property.Value.FALSE; import java.util.Date; import javax.annotation.Nonnull; import org.hisp.dhis.common.BaseIdentifiableObject; import org.hisp.dhis.common.DxfNamespaces; import org.hisp.dhis.common.SecondaryMetadataObject; import org.hisp.dhis.scheduling.parameters.AnalyticsJobParameters; import org.hisp.dhis.scheduling.parameters.ContinuousAnalyticsJobParameters; import org.hisp.dhis.scheduling.parameters.EventProgramsDataSynchronizationJobParameters; import org.hisp.dhis.scheduling.parameters.MetadataSyncJobParameters; import org.hisp.dhis.scheduling.parameters.MonitoringJobParameters; import org.hisp.dhis.scheduling.parameters.PredictorJobParameters; import org.hisp.dhis.scheduling.parameters.PushAnalysisJobParameters; import org.hisp.dhis.scheduling.parameters.SmsJobParameters; import org.hisp.dhis.scheduling.parameters.TrackerProgramsDataSynchronizationJobParameters; import org.hisp.dhis.scheduling.parameters.jackson.JobConfigurationSanitizer; import org.hisp.dhis.schema.annotation.Property; import org.springframework.scheduling.support.CronTrigger; import org.springframework.scheduling.support.SimpleTriggerContext; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeId; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; @JacksonXmlRootElement( localName = "jobConfiguration", namespace = DxfNamespaces.DXF_2_0 ) @JsonDeserialize( converter = JobConfigurationSanitizer.class ) public class JobConfiguration extends BaseIdentifiableObject implements SecondaryMetadataObject { // Externally configurable properties /** * The type of job. */ private JobType jobType; /** * The cron expression used for scheduling the job. Relevant for scheduling * type {@link SchedulingType#CRON}. */ private String cronExpression; /** * The delay in seconds between the completion of one job execution and the * start of the next. Relevant for scheduling type {@link SchedulingType#FIXED_DELAY}. */ private Integer delay; /** * Parameters of the job. Jobs can use their own implementation of the {@link JobParameters} class. */ private JobParameters jobParameters; /** * Indicates whether this job is currently enabled or disabled. */ private boolean enabled = true; // Internally managed properties private JobStatus jobStatus; private Date nextExecutionTime; private JobStatus lastExecutedStatus = JobStatus.NOT_STARTED; private Date lastExecuted; private String lastRuntimeExecution; private boolean inMemoryJob = false; private String userUid; private boolean leaderOnlyJob = false; public JobConfiguration() { } /** * Constructor. * * @param name the job name. * @param jobType the {@link JobType}. * @param userUid the user UID. * @param inMemoryJob whether this is an in-memory job. */ public JobConfiguration( String name, JobType jobType, String userUid, boolean inMemoryJob ) { this.name = name; this.jobType = jobType; this.userUid = userUid; this.inMemoryJob = inMemoryJob; init(); } /** * Constructor which implies enabled true and in-memory job false. * * @param name the job name. * @param jobType the {@link JobType}. * @param cronExpression the cron expression. * @param jobParameters the job parameters. */ public JobConfiguration( String name, JobType jobType, String cronExpression, JobParameters jobParameters ) { this( name, jobType, cronExpression, jobParameters, true, false ); } /** * Constructor. * * @param name the job name. * @param jobType the {@link JobType}. * @param cronExpression the cron expression. * @param jobParameters the job parameters. * @param enabled whether this job is enabled. * @param inMemoryJob whether this is an in-memory job. */ public JobConfiguration( String name, JobType jobType, String cronExpression, JobParameters jobParameters, boolean enabled, boolean inMemoryJob ) { this.name = name; this.cronExpression = cronExpression; this.jobType = jobType; this.jobParameters = jobParameters; this.enabled = enabled; this.inMemoryJob = inMemoryJob; setJobStatus( enabled ? SCHEDULED : DISABLED ); init(); } // Logic private void init() { if ( inMemoryJob ) { setAutoFields(); } } /** * Checks if this job has changes compared to the specified job configuration that are only * allowed for configurable jobs. * * @param other the job configuration that should be checked. * @return <code>true</code> if this job configuration has changes in fields that are only * allowed for configurable jobs, <code>false</code> otherwise. */ public boolean hasNonConfigurableJobChanges( @Nonnull JobConfiguration other ) { if ( this.jobType != other.getJobType() ) { return true; } if ( this.jobStatus != other.getJobStatus() ) { return true; } if ( this.jobParameters != other.getJobParameters() ) { return true; } return this.enabled != other.isEnabled(); } @JacksonXmlProperty @JsonProperty( access = JsonProperty.Access.READ_ONLY ) public boolean isConfigurable() { return jobType.isConfigurable(); } @JacksonXmlProperty @JsonProperty( access = JsonProperty.Access.READ_ONLY ) public SchedulingType getSchedulingType() { return jobType.getSchedulingType(); } public boolean hasCronExpression() { return cronExpression != null && !cronExpression.isEmpty(); } @Override public String toString() { return "JobConfiguration{" + "uid='" + uid + '\'' + ", name='" + name + '\'' + ", jobType=" + jobType + ", cronExpression='" + cronExpression + '\'' + ", delay='" + delay + '\'' + ", jobParameters=" + jobParameters + ", enabled=" + enabled + ", inMemoryJob=" + inMemoryJob + ", lastRuntimeExecution='" + lastRuntimeExecution + '\'' + ", userUid='" + userUid + '\'' + ", leaderOnlyJob=" + leaderOnlyJob + ", jobStatus=" + jobStatus + ", nextExecutionTime=" + nextExecutionTime + ", lastExecutedStatus=" + lastExecutedStatus + ", lastExecuted=" + lastExecuted + '}'; } // Get and set methods @JacksonXmlProperty @JsonProperty @JsonTypeId public JobType getJobType() { return jobType; } public void setJobType( JobType jobType ) { this.jobType = jobType; } @JacksonXmlProperty @JsonProperty public String getCronExpression() { return cronExpression; } public void setCronExpression( String cronExpression ) { this.cronExpression = cronExpression; } @JacksonXmlProperty @JsonProperty public Integer getDelay() { return delay; } public void setDelay( Integer delay ) { this.delay = delay; } /** * The sub type names refer to the {@link JobType} enumeration. */ @JacksonXmlProperty @JsonProperty @Property( required = FALSE ) @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "jobType" ) @JsonSubTypes( value = { @JsonSubTypes.Type( value = AnalyticsJobParameters.class, name = "ANALYTICS_TABLE" ), @JsonSubTypes.Type( value = ContinuousAnalyticsJobParameters.class, name = "CONTINUOUS_ANALYTICS_TABLE" ), @JsonSubTypes.Type( value = MonitoringJobParameters.class, name = "MONITORING" ), @JsonSubTypes.Type( value = PredictorJobParameters.class, name = "PREDICTOR" ), @JsonSubTypes.Type( value = PushAnalysisJobParameters.class, name = "PUSH_ANALYSIS" ), @JsonSubTypes.Type( value = SmsJobParameters.class, name = "SMS_SEND" ), @JsonSubTypes.Type( value = MetadataSyncJobParameters.class, name = "META_DATA_SYNC" ), @JsonSubTypes.Type( value = EventProgramsDataSynchronizationJobParameters.class, name = "EVENT_PROGRAMS_DATA_SYNC" ), @JsonSubTypes.Type( value = TrackerProgramsDataSynchronizationJobParameters.class, name = "TRACKER_PROGRAMS_DATA_SYNC" ), } ) public JobParameters getJobParameters() { return jobParameters; } public void setJobParameters( JobParameters jobParameters ) { this.jobParameters = jobParameters; } @JacksonXmlProperty @JsonProperty public boolean isEnabled() { return enabled; } public void setEnabled( boolean enabled ) { this.enabled = enabled; } @JacksonXmlProperty @JsonProperty( access = JsonProperty.Access.READ_ONLY ) public JobStatus getJobStatus() { return jobStatus; } public void setJobStatus( JobStatus jobStatus ) { this.jobStatus = jobStatus; } @JacksonXmlProperty @JsonProperty( access = JsonProperty.Access.READ_ONLY ) public Date getNextExecutionTime() { return nextExecutionTime; } /** * Only set next execution time if the job is not continuous. */ public void setNextExecutionTime( Date nextExecutionTime ) { if ( cronExpression == null || cronExpression.equals( "" ) || cronExpression.equals( "* * * * * ?" ) ) { return; } if ( nextExecutionTime != null ) { this.nextExecutionTime = nextExecutionTime; } else { this.nextExecutionTime = new CronTrigger( cronExpression ).nextExecutionTime( new SimpleTriggerContext() ); } } @JacksonXmlProperty @JsonProperty( access = JsonProperty.Access.READ_ONLY ) public Date getLastExecuted() { return lastExecuted; } public void setLastExecuted( Date lastExecuted ) { this.lastExecuted = lastExecuted; } @JacksonXmlProperty @JsonProperty( access = JsonProperty.Access.READ_ONLY ) public JobStatus getLastExecutedStatus() { return lastExecutedStatus; } public void setLastExecutedStatus( JobStatus lastExecutedStatus ) { this.lastExecutedStatus = lastExecutedStatus; } @JacksonXmlProperty @JsonProperty( access = JsonProperty.Access.READ_ONLY ) public String getLastRuntimeExecution() { return lastRuntimeExecution; } public void setLastRuntimeExecution( String lastRuntimeExecution ) { this.lastRuntimeExecution = lastRuntimeExecution; } @JacksonXmlProperty @JsonProperty public boolean isLeaderOnlyJob() { return leaderOnlyJob; } public void setLeaderOnlyJob( boolean leaderOnlyJob ) { this.leaderOnlyJob = leaderOnlyJob; } public boolean isInMemoryJob() { return inMemoryJob; } public void setInMemoryJob( boolean inMemoryJob ) { this.inMemoryJob = inMemoryJob; } @JacksonXmlProperty @JsonProperty( access = JsonProperty.Access.READ_ONLY ) public String getUserUid() { return userUid; } public void setUserUid( String userUid ) { this.userUid = userUid; } }
package okapi; import okapi.MainVerticle; import io.vertx.core.DeploymentOptions; import io.vertx.core.Vertx; import io.vertx.core.http.HttpClient; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(VertxUnitRunner.class) public class TenantTest { Vertx vertx; String doc1, doc2; String location; Async async; private HttpClient httpClient; private static String LS = System.lineSeparator(); public TenantTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp(TestContext context) { vertx = Vertx.vertx(); DeploymentOptions opt = new DeploymentOptions(); vertx.deployVerticle(MainVerticle.class.getName(), opt, context.asyncAssertSuccess()); this.httpClient = vertx.createHttpClient(); } @After public void tearDown(TestContext context) { vertx.close(context.asyncAssertSuccess()); } private int port = Integer.parseInt(System.getProperty("port", "9130")); @Test public void test1(TestContext context) { this.async = context.async(); healthCheck(context); } public void healthCheck(TestContext context) { httpClient.get(port, "localhost", "/_/health", response -> { context.assertEquals(200, response.statusCode()); response.handler(body -> { }); response.endHandler(x -> { listNone(context); }); }).end(); } public void listNone(TestContext context) { httpClient.get(port, "localhost", "/_/tenants", response -> { context.assertEquals(200, response.statusCode()); response.handler(body -> { context.assertEquals("[ ]", body.toString()); }); response.endHandler(x -> { post(context); }); }).end(); } public void post(TestContext context) { doc1 = "{"+LS + " \"name\" : \"roskilde\","+LS + " \"description\" : \"Roskilde bibliotek\""+LS + "}"; doc2 = "{"+LS + " \"id\" : \"roskilde\","+LS + " \"name\" : \"roskilde\","+LS + " \"description\" : \"Roskilde bibliotek\""+LS + "}"; httpClient.post(port, "localhost", "/_/tenants", response -> { context.assertEquals(201, response.statusCode()); response.endHandler(x -> { location = response.getHeader("Location"); getNone(context); }); }).end(doc1); } public void getNone(TestContext context) { httpClient.get(port, "localhost", location + "_none", response -> { context.assertEquals(404, response.statusCode()); response.endHandler(x -> { listOne(context); }); }).end(); } public void listOne(TestContext context) { httpClient.get(port, "localhost", "/_/tenants", response -> { context.assertEquals(200, response.statusCode()); response.handler(body -> { context.assertEquals("[ \"roskilde\" ]", body.toString()); }); response.endHandler(x -> { getIt(context); }); }).end(); } public void getIt(TestContext context) { httpClient.get(port, "localhost", location, response -> { context.assertEquals(200, response.statusCode()); response.handler(body -> { context.assertEquals(doc2, body.toString()); }); response.endHandler(x -> { deleteIt(context); }); }).end(); } public void deleteIt(TestContext context) { httpClient.delete(port, "localhost", location, response -> { context.assertEquals(204, response.statusCode()); response.endHandler(x -> { post2(context); }); }).end(); } public void post2(TestContext context) { doc1 = "{"+LS + " \"name\" : \"roskilde\","+LS + " \"id\" : \"roskildedk\","+LS + " \"description\" : \"Roskilde bibliotek\""+LS + "}"; httpClient.post(port, "localhost", "/_/tenants", response -> { context.assertEquals(201, response.statusCode()); response.endHandler(x -> { location = response.getHeader("Location"); listOne2(context); }); }).end(doc1); } public void listOne2(TestContext context) { httpClient.get(port, "localhost", "/_/tenants", response -> { context.assertEquals(200, response.statusCode()); response.handler(body -> { context.assertEquals("[ \"roskildedk\" ]", body.toString()); }); response.endHandler(x -> { done(context); }); }).end(); } public void done(TestContext context){ async.complete(); } }
package hudson.cli; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.codec.binary.Base64; /** * Creates a capacity-unlimited bi-directional {@link InputStream}/{@link OutputStream} pair over * HTTP, which is a request/response protocol. * * @author Kohsuke Kawaguchi */ public class FullDuplexHttpStream { private final URL target; /** * Authorization header value needed to get through the HTTP layer. */ private final String authorization; private final OutputStream output; private final InputStream input; public InputStream getInputStream() { return input; } public OutputStream getOutputStream() { return output; } @Deprecated public FullDuplexHttpStream(URL target) throws IOException { this(target,basicAuth(target.getUserInfo())); } private static String basicAuth(String userInfo) { if (userInfo != null) return "Basic "+new String(Base64.encodeBase64(userInfo.getBytes())); return null; } /** * @param target * The endpoint that we are making requests to. * @param authorization * The value of the authorization header, if non-null. */ public FullDuplexHttpStream(URL target, String authorization) throws IOException { this.target = target; this.authorization = authorization; CrumbData crumbData = new CrumbData(); UUID uuid = UUID.randomUUID(); // so that the server can correlate those two connections // server->client HttpURLConnection con = (HttpURLConnection) target.openConnection(); con.setDoOutput(true); // request POST to avoid caching con.setRequestMethod("POST"); con.addRequestProperty("Session", uuid.toString()); con.addRequestProperty("Side","download"); if (authorization != null) { con.addRequestProperty("Authorization", authorization); } if(crumbData.isValid) { con.addRequestProperty(crumbData.crumbName, crumbData.crumb); } con.getOutputStream().close(); input = con.getInputStream(); // make sure we hit the right URL if(con.getHeaderField("Hudson-Duplex")==null) throw new IOException(target+" doesn't look like Jenkins"); // client->server uses chunked encoded POST for unlimited capacity. con = (HttpURLConnection) target.openConnection(); con.setDoOutput(true); // request POST con.setRequestMethod("POST"); con.setChunkedStreamingMode(0); con.setRequestProperty("Content-type","application/octet-stream"); con.addRequestProperty("Session", uuid.toString()); con.addRequestProperty("Side","upload"); if (authorization != null) { con.addRequestProperty ("Authorization", authorization); } if(crumbData.isValid) { con.addRequestProperty(crumbData.crumbName, crumbData.crumb); } output = con.getOutputStream(); } static final int BLOCK_SIZE = 1024; static final Logger LOGGER = Logger.getLogger(FullDuplexHttpStream.class.getName()); private final class CrumbData { String crumbName; String crumb; boolean isValid; private CrumbData() { this.crumbName = ""; this.crumb = ""; this.isValid = false; getData(); } private void getData() { try { String base = createCrumbUrlBase(); String[] pair = readData(base + "?xpath=concat(//crumbRequestField,\":\",//crumb)").split(":", 2); crumbName = pair[0]; crumb = pair[1]; isValid = true; LOGGER.fine("Crumb data: "+crumbName+"="+crumb); } catch (IOException e) { // presumably this Hudson doesn't use crumb LOGGER.log(Level.FINE,"Failed to get crumb data",e); } } private String createCrumbUrlBase() { String url = target.toExternalForm(); return new StringBuilder(url.substring(0, url.lastIndexOf("/cli"))).append("/crumbIssuer/api/xml/").toString(); } private String readData(String dest) throws IOException { HttpURLConnection con = (HttpURLConnection) new URL(dest).openConnection(); if (authorization != null) { con.addRequestProperty("Authorization", authorization); } try (BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()))) { String line = reader.readLine(); String nextLine = reader.readLine(); if (nextLine != null) { System.err.println("Warning: received junk from " + dest); System.err.println(line); System.err.println(nextLine); while ((nextLine = reader.readLine()) != null) { System.err.println(nextLine); } } return line; } finally { con.disconnect(); } } } }
package consulo.dotnet.debugger; import java.util.Collection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import com.intellij.execution.ExecutionResult; import com.intellij.execution.configurations.RunProfile; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.ui.ExecutionConsole; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.Computable; import com.intellij.xdebugger.XDebugProcess; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XDebuggerManager; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.breakpoints.XBreakpoint; import com.intellij.xdebugger.breakpoints.XLineBreakpoint; import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider; import consulo.dotnet.debugger.breakpoint.DotNetExceptionBreakpointType; import consulo.dotnet.debugger.breakpoint.DotNetLineBreakpointType; import consulo.dotnet.debugger.breakpoint.DotNetMethodBreakpointType; import consulo.dotnet.debugger.breakpoint.properties.DotNetExceptionBreakpointProperties; import consulo.dotnet.debugger.breakpoint.properties.DotNetLineBreakpointProperties; import consulo.dotnet.debugger.breakpoint.properties.DotNetMethodBreakpointProperties; import consulo.dotnet.debugger.proxy.DotNetVirtualMachineProxy; /** * @author VISTALL * @since 16.04.2016 */ public abstract class DotNetDebugProcessBase extends XDebugProcess { public static final String RUN_TO_CURSOR = "runToCursor"; private ExecutionResult myResult; private final RunProfile myRunProfile; protected final XDebuggerManager myDebuggerManager; public DotNetDebugProcessBase(@NotNull XDebugSession session, @NotNull RunProfile runProfile) { super(session); myRunProfile = runProfile; myDebuggerManager = XDebuggerManager.getInstance(session.getProject()); } @NotNull public DotNetDebugContext createDebugContext(@NotNull DotNetVirtualMachineProxy proxy, @Nullable XBreakpoint<?> breakpoint) { return new DotNetDebugContext(getSession().getProject(), proxy, myRunProfile, getSession(), breakpoint); } public abstract void start(); public void setExecutionResult(ExecutionResult executionResult) { myResult = executionResult; } @Override public boolean checkCanInitBreakpoints() { return false; } @Nullable @Override protected ProcessHandler doGetProcessHandler() { return myResult.getProcessHandler(); } @NotNull @Override public ExecutionConsole createConsole() { return myResult.getExecutionConsole(); } @NotNull @Override public XDebuggerEditorsProvider getEditorsProvider() { return new DotNetEditorsProvider(getSession()); } @Override public void startStepOver() { } @Override public void startStepInto() { } @Override public void startStepOut() { } @Override public void resume() { } @Override public void runToPosition(@NotNull XSourcePosition position) { } @Override public abstract void stop(); @NotNull public Collection<? extends XLineBreakpoint<?>> getLineBreakpoints() { return ApplicationManager.getApplication().runReadAction((Computable<Collection<? extends XLineBreakpoint<DotNetLineBreakpointProperties>>>) () -> myDebuggerManager.getBreakpointManager() .getBreakpoints(DotNetLineBreakpointType.getInstance())); } @NotNull public Collection<? extends XLineBreakpoint<DotNetMethodBreakpointProperties>> getMethodBreakpoints() { return ApplicationManager.getApplication().runReadAction((Computable<Collection<? extends XLineBreakpoint<DotNetMethodBreakpointProperties>>>) () -> myDebuggerManager.getBreakpointManager() .getBreakpoints(DotNetMethodBreakpointType.getInstance())); } @NotNull public Collection<? extends XBreakpoint<DotNetExceptionBreakpointProperties>> getExceptionBreakpoints() { return ApplicationManager.getApplication().runReadAction((Computable<Collection<? extends XBreakpoint<DotNetExceptionBreakpointProperties>>>) () -> myDebuggerManager.getBreakpointManager() .getBreakpoints(DotNetExceptionBreakpointType.getInstance())); } public void normalizeBreakpoints() { for(XLineBreakpoint<?> lineBreakpoint : getLineBreakpoints()) { myDebuggerManager.getBreakpointManager().updateBreakpointPresentation(lineBreakpoint, null, null); } } }
package de.clemensloos.elan.sender; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import de.clemensloos.elan.sender.database.DatabaseHandler; import de.clemensloos.elan.sender.database.Song; public class ImportListActivity extends Activity { List<Song> songList; Button okay; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); songList = null; setContentView(R.layout.import_list); okay = ((Button)findViewById(R.id.but_okay_import)); okay.setEnabled(false); Intent intent = getIntent(); String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action)) { Uri uri = intent.getData(); try{ FileInputStream file = new FileInputStream(new File(uri.getPath())); Iterator<Row> rowIterator; HSSFWorkbook workbook = new HSSFWorkbook(file); HSSFSheet sheet = workbook.getSheetAt(0); rowIterator = sheet.iterator(); LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); TableLayout table = (TableLayout) findViewById(R.id.song_table); songList = new ArrayList<>(); TableRow rowView = (TableRow)inflater.inflate(R.layout.import_table_row, null); ((TextView)rowView.findViewById(R.id.number)).setText(" ((TextView)rowView.findViewById(R.id.title)).setText("Title"); ((TextView)rowView.findViewById(R.id.interpret)).setText("Artist"); table.addView(rowView); while (rowIterator.hasNext()) { Row row = rowIterator.next(); if (row.getCell(0) == null || row.getCell(0).getCellType() != Cell.CELL_TYPE_NUMERIC) { continue; } int nr = (int)Math.rint(row.getCell(0).getNumericCellValue()); String title = ""; if (row.getCell(1) != null && row.getCell(1).getCellType() == Cell.CELL_TYPE_STRING) { title = row.getCell(1).getStringCellValue(); } String artist = ""; if (row.getCell(2) != null && row.getCell(2).getCellType() == Cell.CELL_TYPE_STRING) { artist = row.getCell(2).getStringCellValue(); } songList.add(new Song(nr, title, artist)); rowView = (TableRow)inflater.inflate(R.layout.import_table_row, null); ((TextView)rowView.findViewById(R.id.number)).setText("" + nr); ((TextView)rowView.findViewById(R.id.title)).setText(title); ((TextView)rowView.findViewById(R.id.interpret)).setText(artist); table.addView(rowView); okay.setEnabled(true); } //table.addView(rowView); } catch(IOException e) { finish(); } ((Button)findViewById(R.id.but_cancel_import)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); okay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (songList != null && songList.size() > 0) { DatabaseHandler dbh = new DatabaseHandler(ImportListActivity.this); dbh.clearSongs(); dbh.addSongs(songList); } finish(); } }); } } }
package de.lmu.ifi.dbs.elki.algorithm.outlier.intrinsic; import de.lmu.ifi.dbs.elki.algorithm.AbstractDistanceBasedAlgorithm; import de.lmu.ifi.dbs.elki.algorithm.outlier.OutlierAlgorithm; import de.lmu.ifi.dbs.elki.data.type.TypeInformation; import de.lmu.ifi.dbs.elki.data.type.TypeUtil; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.database.datastore.DataStoreFactory; import de.lmu.ifi.dbs.elki.database.datastore.DataStoreUtil; import de.lmu.ifi.dbs.elki.database.datastore.DoubleDataStore; import de.lmu.ifi.dbs.elki.database.datastore.WritableDoubleDataStore; import de.lmu.ifi.dbs.elki.database.ids.DBIDIter; import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil; import de.lmu.ifi.dbs.elki.database.ids.DBIDs; import de.lmu.ifi.dbs.elki.database.ids.DoubleDBIDListIter; import de.lmu.ifi.dbs.elki.database.ids.KNNList; import de.lmu.ifi.dbs.elki.database.query.knn.KNNQuery; import de.lmu.ifi.dbs.elki.database.relation.DoubleRelation; import de.lmu.ifi.dbs.elki.database.relation.MaterializedDoubleRelation; import de.lmu.ifi.dbs.elki.database.relation.Relation; import de.lmu.ifi.dbs.elki.distance.distancefunction.DistanceFunction; import de.lmu.ifi.dbs.elki.logging.Logging; import de.lmu.ifi.dbs.elki.logging.progress.FiniteProgress; import de.lmu.ifi.dbs.elki.logging.progress.StepProgress; import de.lmu.ifi.dbs.elki.math.DoubleMinMax; import de.lmu.ifi.dbs.elki.math.statistics.intrinsicdimensionality.HillEstimator; import de.lmu.ifi.dbs.elki.math.statistics.intrinsicdimensionality.IntrinsicDimensionalityEstimator; import de.lmu.ifi.dbs.elki.result.outlier.OutlierResult; import de.lmu.ifi.dbs.elki.result.outlier.OutlierScoreMeta; import de.lmu.ifi.dbs.elki.result.outlier.QuotientOutlierScoreMeta; import de.lmu.ifi.dbs.elki.utilities.DatabaseUtil; import de.lmu.ifi.dbs.elki.utilities.documentation.Reference; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.CommonConstraints; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.GreaterEqualConstraint; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.ObjectParameter; @Reference(authors = "Jonathan von Brünken, Michael E. Houle, Arthur Zimek", title = "Intrinsic Dimensional Outlier Detection in High-Dimensional Data", booktitle = "NII Technical Report (NII-2015-003E)", url = "http: public class IDOS<O> extends AbstractDistanceBasedAlgorithm<O, OutlierResult> implements OutlierAlgorithm { /** * The logger for this class. */ private static final Logging LOG = Logging.getLogger(IDOS.class); /** * kNN for the context set (ID computation). */ protected int k_c; /** * kNN for the reference set. */ protected int k_r; /** * Estimator for intrinsic dimensionality. */ protected IntrinsicDimensionalityEstimator estimator; /** * Constructor. * * @param distanceFunction the distance function to use * @param estimator Estimator for intrinsic dimensionality * @param kc the context set size for the ID computation * @param kr the neighborhood size to use in score computation */ public IDOS(DistanceFunction<? super O> distanceFunction, IntrinsicDimensionalityEstimator estimator, int kc, int kr) { super(distanceFunction); this.estimator = estimator; this.k_c = kc; this.k_r = kr; } /** * Run the algorithm * * @param database Database * @param relation Data relation * @return Outlier result */ public OutlierResult run(Database database, Relation<O> relation) { StepProgress stepprog = LOG.isVerbose() ? new StepProgress("IDOS", 3) : null; if(stepprog != null) { stepprog.beginStep(1, "Precomputing neighborhoods", LOG); } KNNQuery<O> knnQ = DatabaseUtil.precomputedKNNQuery(database, relation, getDistanceFunction(), Math.max(k_c, k_r) + 1); DBIDs ids = relation.getDBIDs(); if(stepprog != null) { stepprog.beginStep(2, "Computing intrinsic dimensionalities", LOG); } DoubleDataStore intDims = computeIDs(ids, knnQ); if(stepprog != null) { stepprog.beginStep(3, "Computing IDOS scores", LOG); } DoubleMinMax idosminmax = new DoubleMinMax(); DoubleDataStore ldms = computeIDOS(ids, knnQ, intDims, idosminmax); if(stepprog != null) { stepprog.setCompleted(LOG); } DoubleRelation scoreResult = new MaterializedDoubleRelation("Intrinsic Dimensionality Outlier Score", "idos", ldms, ids); OutlierScoreMeta scoreMeta = new QuotientOutlierScoreMeta(idosminmax.getMin(), idosminmax.getMax(), 0.0, Double.POSITIVE_INFINITY, 1.0); return new OutlierResult(scoreMeta, scoreResult); } /** * Computes all IDs * * @param ids the DBIDs to process * @param knnQ the KNN query * @return The computed intrinsic dimensionalities. */ protected DoubleDataStore computeIDs(DBIDs ids, KNNQuery<O> knnQ) { WritableDoubleDataStore intDims = DataStoreUtil.makeDoubleStorage(ids, DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP); FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Intrinsic dimensionality", ids.size(), LOG) : null; double[] dists = new double[k_c]; for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { KNNList nn = knnQ.getKNNForDBID(iter, k_c + 1); int pos = 0; for(DoubleDBIDListIter neighbor = nn.iter(); neighbor.valid(); neighbor.advance()) { final double ndist = neighbor.doubleValue(); if(ndist > 0.) { // Estimators don't expect zero values. dists[pos++] = ndist; } if(pos >= k_c) { // Always stop after at most k_c elements. break; } } intDims.putDouble(iter, estimator.estimate(dists, pos)); LOG.incrementProcessed(prog); } LOG.ensureCompleted(prog); return intDims; } /** * Computes all IDOS scores. * * @param ids the DBIDs to process * @param knnQ the KNN query * @param intDims Precomputed intrinsic dimensionalities * @param idosminmax Output of minimum and maximum, for metadata * @return ID scores */ protected DoubleDataStore computeIDOS(DBIDs ids, KNNQuery<O> knnQ, DoubleDataStore intDims, DoubleMinMax idosminmax) { WritableDoubleDataStore ldms = DataStoreUtil.makeDoubleStorage(ids, DataStoreFactory.HINT_STATIC); FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("ID Outlier Scores for objects", ids.size(), LOG) : null; for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnQ.getKNNForDBID(iter, k_r); double sum = 0.; int cnt = 0; for(DoubleDBIDListIter neighbor = neighbors.iter(); neighbor.valid(); neighbor.advance()) { if(DBIDUtil.equal(iter, neighbor)) { continue; } final double id = intDims.doubleValue(neighbor); sum += id > 0 ? 1.0 / id : 0.; if(++cnt == k_r) { // Always stop after at most k_r elements. break; } } final double id_q = intDims.doubleValue(iter); final double idos = id_q > 0 ? id_q * sum / cnt : 0.; ldms.putDouble(iter, idos); idosminmax.put(idos); LOG.incrementProcessed(prog); } LOG.ensureCompleted(prog); return ldms; } @Override public TypeInformation[] getInputTypeRestriction() { return TypeUtil.array(getDistanceFunction().getInputTypeRestriction()); } @Override protected Logging getLogger() { return LOG; } public static class Parameterizer<O> extends AbstractDistanceBasedAlgorithm.Parameterizer<O> { /** * The class used for estimating the intrinsic dimensionality. */ public static final OptionID ESTIMATOR_ID = new OptionID("idos.estimator", "Estimator of intrinsic dimensionality."); /** * Parameter to specify the neighborhood size to use for the averaging. */ public static final OptionID KR_ID = new OptionID("idos.kr", "Reference set size."); /** * Parameter to specify the number of nearest neighbors of an object to be * used for the GED computation. */ public static final OptionID KC_ID = new OptionID("idos.kc", "Context set size (ID estimation)."); /** * Estimator for intrinsic dimensionality. */ protected IntrinsicDimensionalityEstimator estimator; /** * kNN for the context set (ID computation). */ protected int k_c = 20; /** * kNN for the reference set. */ protected int k_r = 20; @Override protected void makeOptions(Parameterization config) { super.makeOptions(config); ObjectParameter<IntrinsicDimensionalityEstimator> estP = new ObjectParameter<>(ESTIMATOR_ID, IntrinsicDimensionalityEstimator.class, HillEstimator.class); if(config.grab(estP)) { estimator = estP.instantiateClass(config); } IntParameter pKc = new IntParameter(KC_ID) .addConstraint(new GreaterEqualConstraint(5)); if(config.grab(pKc)) { k_c = pKc.getValue(); } IntParameter pKr = new IntParameter(KR_ID) .addConstraint(CommonConstraints.GREATER_THAN_ONE_INT); if(config.grab(pKr)) { k_r = pKr.getValue(); } } @Override protected IDOS<O> makeInstance() { return new IDOS<>(distanceFunction, estimator, k_c, k_r); } } }
package hr.unidu.oop.p09; public class VisestrukeDretve implements Runnable{ // Posao koji se obavlja u dretvi stavlja se u metodu run public void run(){ try { // Dretva pauzira 2 sekunde Thread.sleep(2000); } catch (InterruptedException ex) { ex.printStackTrace(); } Thread.yield(); for (int i = 0; i<10; i++){ String naziv = Thread.currentThread().getName(); System.out.println("Dretva " + naziv + " radi."); } } public static void main(String[] args){ VisestrukeDretve obj = new VisestrukeDretve(); Thread t1 = new Thread(obj, "PRVA"); Thread t2 = new Thread(obj); t2.setName("DRUGA"); Thread t3 = new Thread(obj); t3.setName("TREĆA"); t1.setPriority(Thread.MIN_PRIORITY); t2.setPriority(5); t3.setPriority(Thread.MAX_PRIORITY); t1.start(); t2.start(); t3.start(); } }
/* @java.file.header */ package org.gridgain.examples; import org.gridgain.client.router.*; import org.gridgain.examples.misc.client.router.*; import org.gridgain.grid.*; import org.gridgain.grid.util.typedef.*; import org.gridgain.grid.util.typedef.internal.*; import org.gridgain.testframework.junits.common.*; import org.jetbrains.annotations.*; import org.springframework.beans.*; import org.springframework.beans.factory.*; import org.springframework.beans.factory.xml.*; import org.springframework.context.*; import org.springframework.context.support.*; import org.springframework.core.io.*; import java.net.*; import java.util.*; /** * GridRouterExample self test. */ public class GridRouterExamplesSelfTest extends GridAbstractExamplesTest { /** * @throws Exception If failed. */ @Override protected void beforeTest() throws Exception { // Start up a grid node. startGrid(getTestGridName(0), "examples/config/example-cache.xml"); // Start up a router. startRouter("config/router/default-router.xml"); } /** * @throws Exception If failed. */ @Override protected void afterTest() throws Exception { GridRouterFactory.stopAllRouters(); super.afterTest(); } /** * @throws Exception If failed. */ public void testGridRouterExample() throws Exception { RouterExample.main(EMPTY_ARGS); } /** * Starts router. * * @param cfgPath Path to router config. * @throws GridException Thrown in case of any errors. */ protected static void startRouter(String cfgPath) throws GridException { URL cfgUrl = U.resolveGridGainUrl(cfgPath); if (cfgUrl == null) throw new GridException("Spring XML file not found (is GRIDGAIN_HOME set?): " + cfgPath); ApplicationContext ctx = loadCfg(cfgUrl); if (ctx == null) throw new GridException("Application context can not be null"); GridTcpRouterConfiguration tcpCfg = getBean(ctx, GridTcpRouterConfiguration.class); if (tcpCfg == null) throw new GridException("GridTcpRouterConfiguration is not found"); tcpCfg.setHost("127.0.0.1"); GridRouterFactory.startTcpRouter(tcpCfg); } /** * Reads spring context from the given location. * @param springCfgUrl Context descriptor loxcation. * @return Spring context. * @throws GridException If context can't be loaded. */ private static ApplicationContext loadCfg(URL springCfgUrl) throws GridException { GenericApplicationContext springCtx; try { springCtx = new GenericApplicationContext(); new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(springCfgUrl)); springCtx.refresh(); } catch (BeansException e) { throw new GridException("Failed to instantiate Spring XML application context [springUrl=" + springCfgUrl + ", err=" + e.getMessage() + ']', e); } return springCtx; } /** * Get bean configuration. * * @param ctx Spring context. * @param beanCls Bean class. * @return Spring bean. */ @Nullable public static <T> T getBean(ListableBeanFactory ctx, Class<T> beanCls) { Map.Entry<String, T> entry = F.firstEntry(ctx.getBeansOfType(beanCls)); return entry == null ? null : entry.getValue(); } }
package com.foundationdb.server.store; import com.foundationdb.KeyValue; import com.foundationdb.Range; import com.foundationdb.Transaction; import com.foundationdb.async.Function; import com.foundationdb.ais.model.Column; import com.foundationdb.ais.model.Group; import com.foundationdb.ais.model.HasStorage; import com.foundationdb.ais.model.Index; import com.foundationdb.ais.model.Sequence; import com.foundationdb.ais.model.StorageDescription; import com.foundationdb.ais.model.Table; import com.foundationdb.ais.model.TableIndex; import com.foundationdb.ais.model.TableName; import com.foundationdb.ais.model.AbstractVisitor; import com.foundationdb.ais.model.GroupsContainsLobsVisitor; import com.foundationdb.ais.util.TableChange.ChangeType; import com.foundationdb.ais.util.TableChangeValidator.ChangeLevel; import com.foundationdb.async.AsyncIterator; import com.foundationdb.directory.DirectorySubspace; import com.foundationdb.directory.PathUtil; import com.foundationdb.qp.row.IndexRow; import com.foundationdb.qp.row.Row; import com.foundationdb.qp.row.WriteIndexRow; import com.foundationdb.qp.row.OverlayingRow; import com.foundationdb.qp.rowtype.Schema; import com.foundationdb.qp.rowtype.RowType; import com.foundationdb.qp.storeadapter.FDBAdapter; import com.foundationdb.qp.storeadapter.indexrow.FDBIndexRow; import com.foundationdb.qp.storeadapter.indexrow.SpatialColumnHandler; import com.foundationdb.qp.util.SchemaCache; import com.foundationdb.server.error.DuplicateKeyException; import com.foundationdb.server.error.FDBNotCommittedException; import com.foundationdb.server.error.LobException; import com.foundationdb.server.service.Service; import com.foundationdb.server.service.ServiceManager; import com.foundationdb.server.service.blob.BlobRef; import com.foundationdb.server.service.blob.LobService; import com.foundationdb.server.service.config.ConfigurationService; import com.foundationdb.server.service.listener.ListenerService; import com.foundationdb.server.service.metrics.LongMetric; import com.foundationdb.server.service.metrics.MetricsService; import com.foundationdb.server.service.session.Session; import com.foundationdb.server.service.transaction.TransactionService; import com.foundationdb.server.store.FDBTransactionService.TransactionState; import com.foundationdb.server.store.TableChanges.Change; import com.foundationdb.server.store.TableChanges.ChangeSet; import com.foundationdb.server.store.format.FDBStorageDescription; import com.foundationdb.server.types.aksql.aktypes.AkBlob; import com.foundationdb.server.types.aksql.aktypes.AkGUID; import com.foundationdb.server.types.service.TypesRegistryService; import com.foundationdb.server.util.ReadWriteMap; import com.foundationdb.tuple.Tuple2; import com.foundationdb.tuple.Tuple; import com.google.inject.Inject; import com.persistit.Key; import com.persistit.Persistit; import com.persistit.Value; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import static com.foundationdb.server.store.FDBStoreDataHelper.*; public class FDBStore extends AbstractStore<FDBStore,FDBStoreData,FDBStorageDescription> implements Service { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final Session.MapKey<Object, SequenceCache> SEQ_UPDATES_KEY = Session.MapKey.mapNamed("SEQ_UPDATE"); private final FDBHolder holder; private final ConfigurationService configService; private final FDBSchemaManager schemaManager; private final FDBTransactionService txnService; private final MetricsService metricsService; private final ReadWriteMap<Object, SequenceCache> sequenceCache; private LobService lobService; private static final String ROWS_FETCHED_METRIC = "SQLLayerRowsFetched"; private static final String ROWS_STORED_METRIC = "SQLLayerRowsStored"; private static final String ROWS_CLEARED_METRIC = "SQLLayerRowsCleared"; private static final String CONFIG_SEQUENCE_CACHE_SIZE = "fdbsql.fdb.sequence_cache_size"; private LongMetric rowsFetchedMetric, rowsStoredMetric, rowsClearedMetric; private DirectorySubspace rootDir; private int sequenceCacheSize; @Inject public FDBStore(FDBHolder holder, ConfigurationService configService, SchemaManager schemaManager, TransactionService txnService, ListenerService listenerService, TypesRegistryService typesRegistryService, ServiceManager serviceManager, MetricsService metricsService) { super(txnService, schemaManager, listenerService, typesRegistryService, serviceManager); this.holder = holder; this.configService = configService; if(schemaManager instanceof FDBSchemaManager) { this.schemaManager = (FDBSchemaManager)schemaManager; } else { throw new IllegalStateException("Only usable with FDBSchemaManager, found: " + txnService); } if(txnService instanceof FDBTransactionService) { this.txnService = (FDBTransactionService)txnService; } else { throw new IllegalStateException("Only usable with FDBTransactionService, found: " + txnService); } this.metricsService = metricsService; this.sequenceCache = ReadWriteMap.wrapFair(new HashMap<Object, SequenceCache>()); } @Override public long nextSequenceValue(Session session, Sequence sequence) { Map<Object, SequenceCache> sessionMap = session.get(SEQ_UPDATES_KEY); SequenceCache cache = null; if(sessionMap != null) { cache = sessionMap.get(SequenceCache.cacheKey(sequence)); } if(cache == null) { cache = sequenceCache.getOrCreateAndPut(SequenceCache.cacheKey(sequence), SEQUENCE_CACHE_VALUE_CREATOR); long readTimestamp = txnService.getTransactionStartTimestamp(session); if(readTimestamp < cache.getTimestamp()) { cache = null; } } long rawValue = (cache != null) ? cache.nextCacheValue() : -1; if(rawValue < 0) { rawValue = updateSequenceCache(session, sequence); } return sequence.realValueForRawNumber(rawValue); } @Override public long curSequenceValue(Session session, Sequence sequence) { long rawValue = 0; SequenceCache cache = sequenceCache.get(sequence.getStorageUniqueKey()); if(cache == null) { cache = session.get(SEQ_UPDATES_KEY, sequence.getStorageUniqueKey()); } if (cache != null) { rawValue = cache.getCurrentValue(); } else { // TODO: Allow FDBStorageDescription to intervene? TransactionState txn = txnService.getTransaction(session); byte[] byteValue = txn.getValue(prefixBytes(sequence)); if(byteValue != null) { Tuple2 tuple = Tuple2.fromBytes(byteValue); rawValue = tuple.getLong(0); } } return sequence.realValueForRawNumber(rawValue); } public void setRollbackPending(Session session) { if(txnService.isTransactionActive(session)) { txnService.setRollbackPending(session); } } // Service @Override public void start() { rowsFetchedMetric = metricsService.addLongMetric(ROWS_FETCHED_METRIC); rowsStoredMetric = metricsService.addLongMetric(ROWS_STORED_METRIC); rowsClearedMetric = metricsService.addLongMetric(ROWS_CLEARED_METRIC); rootDir = holder.getRootDirectory(); boolean withConcurrentDML = Boolean.parseBoolean(configService.getProperty(FEATURE_DDL_WITH_DML_PROP)); this.sequenceCacheSize = Integer.parseInt(configService.getProperty(CONFIG_SEQUENCE_CACHE_SIZE)); this.constraintHandler = new FDBConstraintHandler(this, configService, typesRegistryService, serviceManager, txnService); this.onlineHelper = new OnlineHelper(txnService, schemaManager, this, typesRegistryService, constraintHandler, withConcurrentDML); listenerService.registerRowListener(onlineHelper); } @Override public void stop() { } @Override public void crash() { } // Store @Override public FDBStoreData createStoreData(Session session, FDBStorageDescription storageDescription) { return new FDBStoreData(session, storageDescription, createKey()); } @Override protected void releaseStoreData(Session session, FDBStoreData storeData) { // None } @Override FDBStorageDescription getStorageDescription(FDBStoreData storeData) { return storeData.storageDescription; } @Override protected Key getKey(Session session, FDBStoreData storeData) { return storeData.persistitKey; } @Override protected void store(Session session, FDBStoreData storeData) { packKey(storeData); storeData.storageDescription.store(this, session, storeData); rowsStoredMetric.increment(); } @Override protected boolean fetch(Session session, FDBStoreData storeData) { packKey(storeData); boolean result = storeData.storageDescription.fetch(this, session, storeData); rowsFetchedMetric.increment(); return result; } @Override protected void clear(Session session, FDBStoreData storeData) { packKey(storeData); storeData.storageDescription.clear(this, session, storeData); rowsClearedMetric.increment(); } @Override void resetForWrite(FDBStoreData storeData, Index index, WriteIndexRow indexRowBuffer) { if(storeData.persistitValue == null) { storeData.persistitValue = new Value((Persistit) null); } indexRowBuffer.resetForWrite(index, storeData.persistitKey, storeData.persistitValue); } @Override protected Iterator<Void> createDescendantIterator(Session session, final FDBStoreData storeData) { groupDescendantsIterator(session, storeData); return new Iterator<Void>() { @Override public boolean hasNext() { return storeData.iterator.hasNext(); } @Override public Void next() { storeData.iterator.next(); unpackKey(storeData); return null; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override protected IndexRow readIndexRow(Session session, Index parentPKIndex, FDBStoreData storeData, Row childRow) { Key parentPkKey = storeData.persistitKey; PersistitKeyAppender keyAppender = PersistitKeyAppender.create(parentPkKey, parentPKIndex.getIndexName()); for (Column column : childRow.rowType().table().getParentJoin().getChildColumns()) { keyAppender.append(childRow.value(column.getPosition()), column); } // Only called when child row does not contain full HKey. // Key contents are the logical parent of the actual index entry (if it exists). byte[] packed = packedTuple(parentPKIndex, parentPkKey); byte[] end = packedTuple(parentPKIndex, parentPkKey, Key.AFTER); TransactionState txn = txnService.getTransaction(session); List<KeyValue> pkValue = txn.getRangeAsValueList(packed, end); FDBIndexRow indexRow = null; if (!pkValue.isEmpty()) { assert pkValue.size() == 1 : parentPKIndex; KeyValue kv = pkValue.get(0); assert kv.getValue().length == 0 : parentPKIndex + ", " + kv; indexRow = new FDBIndexRow(this); FDBStoreDataHelper.unpackTuple(parentPKIndex, parentPkKey, kv.getKey()); indexRow.resetForRead(parentPKIndex, parentPkKey, null); } return indexRow; } @Override public void writeIndexRow(Session session, TableIndex index, Row row, Key hKey, WriteIndexRow indexRow, SpatialColumnHandler spatialColumnHandler, long zValue, boolean doLock) { TransactionState txn = txnService.getTransaction(session); Key indexKey = createKey(); constructIndexRow(session, indexKey, row, index, hKey, indexRow, spatialColumnHandler, zValue, true); checkUniqueness(session, txn, index, row, indexKey); byte[] packedKey = packedTuple(index, indexKey); txn.setBytes(packedKey, EMPTY_BYTE_ARRAY); } @Override public void deleteIndexRow(Session session, TableIndex index, Row row, Key hKey, WriteIndexRow indexRow, SpatialColumnHandler spatialColumnHandler, long zValue, boolean doLock) { TransactionState txn = txnService.getTransaction(session); Key indexKey = createKey(); constructIndexRow(session, indexKey, row, index, hKey, indexRow, spatialColumnHandler, zValue, false); byte[] packed = packedTuple(index, indexKey); txn.clearKey(packed); } @Override protected void lock (Session session, FDBStoreData storeData, Row row) { // None } @Override protected void lock(Session session, Row row) { // None } @Override protected void trackTableWrite(Session session, Table table) { // None } @Override public void truncateTree(Session session, HasStorage object) { TransactionState txn = txnService.getTransaction(session); txn.clearRange(Range.startsWith(prefixBytes(object))); } @Override public void deleteIndexes(Session session, Collection<? extends Index> indexes) { for(Index index : indexes) { removeIfExists(session, rootDir, FDBNameGenerator.dataPath(index)); } } @Override public void dropGroup(final Session session, Group group) { deleteLobs(session, group); group.getRoot().visit(new AbstractVisitor() { @Override public void visit(Table table) { removeTrees(session, table); } }); } @Override public void removeTrees(Session session, Table table) { // Table and indexes (and group and group indexes if root table) removeIfExists(session, rootDir, FDBNameGenerator.dataPath(table.getName())); // Sequence if(table.getIdentityColumn() != null) { deleteSequences(session, Collections.singleton(table.getIdentityColumn().getIdentityGenerator())); } } @Override public void removeTrees(Session session, com.foundationdb.ais.model.Schema schema) { removeIfExists(session, rootDir, FDBNameGenerator.dataPathSchemaTable(schema.getName())); removeIfExists(session, rootDir, FDBNameGenerator.dataPathSchemaSequence(schema.getName())); } @Override public void removeTree(Session session, HasStorage object) { deleteLobs(session, object); truncateTree(session, object); } private void deleteLobs(Session session, HasStorage object) { if (object instanceof com.foundationdb.ais.model.Group) { Group group = (Group)object; GroupsContainsLobsVisitor visitor = new GroupsContainsLobsVisitor(); group.visit(visitor); if (visitor.containsLob()) { deleteLobsChecked(session, group); } } } private void deleteLobsChecked(Session session, Group group) { FDBStoreData storeData = createStoreData(session, group); groupIterator(session, storeData); while (storeData.next()) { Row row = expandGroupData(session, storeData, SchemaCache.globalSchema(group.getAIS())); deleteLobs(row); } } @Override public void dropAllLobs(Session session) { getLobService().clearAllLobs(); } @Override public void truncateIndexes(Session session, Collection<? extends Index> indexes) { for(Index index : indexes) { truncateTree(session, index); } } @Override public void deleteSequences(Session session, Collection<? extends Sequence> sequences) { for (Sequence sequence : sequences) { session.remove(SEQ_UPDATES_KEY, SequenceCache.cacheKey(sequence)); sequenceCache.remove(sequence.getStorageUniqueKey()); removeIfExists(session, rootDir, FDBNameGenerator.dataPath(sequence)); } } @Override public FDBAdapter createAdapter(Session session) { return new FDBAdapter(this, session, txnService, configService); } @Override public boolean treeExists(Session session, StorageDescription storageDescription) { TransactionState txn = txnService.getTransaction(session); return txn.getRangeExists(Range.startsWith(prefixBytes((FDBStorageDescription) storageDescription)), 1); } @Override public void discardOnlineChange(Session session, Collection<ChangeSet> changeSets) { for(ChangeSet cs : changeSets) { TableName newName = new TableName(cs.getNewSchema(), cs.getNewName()); removeIfExists(session, rootDir, FDBNameGenerator.onlinePath(newName)); for(Change c : cs.getIdentityChangeList()) { switch(ChangeType.valueOf(c.getChangeType())) { case ADD: removeIfExists(session, rootDir, FDBNameGenerator.onlinePathSequence(newName.getSchemaName(), c.getNewName())); break; case DROP: // None break; default: throw new IllegalStateException(c.getChangeType()); } } } } @Override public void finishOnlineChange(Session session, Collection<ChangeSet> changeSets) { TransactionState txnState = txnService.getTransaction(session); Transaction txn = txnState.getTransaction(); for(ChangeSet cs : changeSets) { TableName oldName = new TableName(cs.getOldSchema(), cs.getOldName()); TableName newName = new TableName(cs.getNewSchema(), cs.getNewName()); for(Change c : cs.getIdentityChangeList()) { List<String> seqOldDataPath = FDBNameGenerator.dataPathSequence(oldName.getSchemaName(), c.getOldName()); List<String> seqNewDataPath = FDBNameGenerator.dataPathSequence(newName.getSchemaName(), c.getNewName()); List<String> seqOnlinePath = FDBNameGenerator.onlinePathSequence(newName.getSchemaName(), c.getNewName()); switch(ChangeType.valueOf(c.getChangeType())) { case ADD: try { rootDir.removeIfExists(txn, seqOldDataPath).get(); // Due to schema currently being create on demand rootDir.createOrOpen(txn, PathUtil.popBack(seqNewDataPath)).get(); rootDir.move(txn, seqOnlinePath, seqNewDataPath).get(); } catch (RuntimeException e) { throw FDBAdapter.wrapFDBException(session, e); } break; case DROP: try { rootDir.removeIfExists(txn, seqOldDataPath).get(); } catch (RuntimeException e) { throw FDBAdapter.wrapFDBException(session, e); } break; default: throw new IllegalStateException(cs.getChangeLevel()); } } List<String> dataPath = FDBNameGenerator.dataPath(oldName); List<String> onlinePath = FDBNameGenerator.onlinePath(newName); // - move renamed directories if(!oldName.equals(newName)) { schemaManager.renamingTable(session, oldName, newName); dataPath = FDBNameGenerator.dataPath(newName); } if (!directoryExists(txnState, rootDir, onlinePath)) { continue; } switch(ChangeLevel.valueOf(cs.getChangeLevel())) { case NONE: // None break; case METADATA: case METADATA_CONSTRAINT: case INDEX: case INDEX_CONSTRAINT: // - Move everything from dataOnline/foo/ to data/foo/ // - remove dataOnline/foo/ try { for(String subPath : rootDir.list(txn, onlinePath).get()) { List<String> subDataPath = PathUtil.extend(dataPath, subPath); List<String> subOnlinePath = PathUtil.extend(onlinePath, subPath); rootDir.removeIfExists(txn, subDataPath).get(); rootDir.move(txn, subOnlinePath, subDataPath).get(); } rootDir.remove(txn, onlinePath).get(); } catch (RuntimeException e) { throw FDBAdapter.wrapFDBException(session, e); } break; case TABLE: case GROUP: // - move unaffected from data/foo/ to dataOnline/foo/ // - remove data/foo // - move dataOnline/foo to data/foo/ try { if (rootDir.exists(txn, dataPath).get()) { executeLobOnlineDelete(session, oldName.getSchemaName(), oldName.getTableName()); for(String subPath : rootDir.list(txn, dataPath).get()) { List<String> subDataPath = PathUtil.extend(dataPath, subPath); List<String> subOnlinePath = PathUtil.extend(onlinePath, subPath); if(!rootDir.exists(txn, subOnlinePath).get()) { rootDir.move(txn, subDataPath, subOnlinePath).get(); } } rootDir.remove(txn, dataPath).get(); } rootDir.move(txn, onlinePath, dataPath).get(); } catch (RuntimeException e) { throw FDBAdapter.wrapFDBException(session, e); } break; default: throw new IllegalStateException(cs.getChangeLevel()); } } } @Override public void traverse(Session session, Group group, TreeRecordVisitor visitor) { visitor.initialize(session, this); FDBStoreData storeData = createStoreData(session, group); groupIterator(session, storeData); while (storeData.next()) { Row row = expandGroupData(session, storeData, SchemaCache.globalSchema(group.getAIS())); visitor.visit(storeData.persistitKey, row); } } public Row expandGroupData(Session session, FDBStoreData storeData, Schema schema) { unpackKey(storeData); return expandRow(session, storeData, schema); } @Override public <V extends IndexVisitor<Key, Value>> V traverse(Session session, Index index, V visitor, long scanTimeLimit, long sleepTime) { FDBStoreData storeData = createStoreData(session, index); storeData.persistitValue = new Value((Persistit)null); TransactionState txn = txnService.getTransaction(session); FDBScanTransactionOptions transactionOptions; if (scanTimeLimit > 0) { transactionOptions = new FDBScanTransactionOptions(true, -1, scanTimeLimit, sleepTime); } else { transactionOptions = FDBScanTransactionOptions.SNAPSHOT; } indexIterator(session, storeData, false, false, false, transactionOptions); while(storeData.next()) { // Key unpackKey(storeData); // Value unpackValue(storeData); // Visit visitor.visit(storeData.persistitKey, storeData.persistitValue); } return visitor; } @Override public String getName() { return "FoundationDB APIv" + holder.getAPIVersion(); } @Override public Collection<String> getStorageDescriptionNames() { final List<List<String>> dataDirs = Arrays.asList( Arrays.asList(FDBNameGenerator.DATA_PATH_NAME, FDBNameGenerator.TABLE_PATH_NAME), Arrays.asList(FDBNameGenerator.DATA_PATH_NAME, FDBNameGenerator.SEQUENCE_PATH_NAME), Arrays.asList(FDBNameGenerator.ONLINE_PATH_NAME, FDBNameGenerator.TABLE_PATH_NAME), Arrays.asList(FDBNameGenerator.ONLINE_PATH_NAME, FDBNameGenerator.SEQUENCE_PATH_NAME) ); return txnService.runTransaction(new Function<Transaction, Collection<String>>() { @Override public Collection<String> apply(Transaction txn) { Set<String> pathSet = new TreeSet<>(); for(List<String> dataPath : dataDirs) { if(rootDir.exists(txn, dataPath).get()) { for(String schemaName : rootDir.list(txn, dataPath).get()) { List<String> schemaPath = PathUtil.extend(dataPath, schemaName); for(String o : rootDir.list(txn, schemaPath).get()) { pathSet.add(PathUtil.extend(schemaPath, o).toString()); } } } } return pathSet; } }); } @Override public Class<? extends Exception> getOnlineDMLFailureException() { return FDBNotCommittedException.class; } @Override protected Row storeLobs(Row row) { RowType rowType = row.rowType(); OverlayingRow resRow = new OverlayingRow(row); Boolean changedRow = false; for ( int i = 0; i < rowType.nFields(); i++ ) { if (rowType.typeAt(i).equalsExcludingNullable(AkBlob.INSTANCE.instance(true))) { int tableId = rowType.table().getTableId(); BlobRef blobRef = (BlobRef)row.value(i).getObject(); String allowedLobFormat = configService.getProperty("fdbsql.blob.allowed_storage_format"); if (blobRef == null) { continue; } if (blobRef.isLongLob()) { if (allowedLobFormat.equalsIgnoreCase("SHORT_LOB")) { throw new LobException("Long lob storage format not allowed"); } } else if (blobRef.isShortLob()) { if (allowedLobFormat.equalsIgnoreCase("LONG_LOB")) { throw new LobException("Short lob storage format not allowed"); } if (allowedLobFormat.equalsIgnoreCase("SHORT_LOB") && (blobRef.getBytes().length >= AkBlob.LOB_SWITCH_SIZE)) { throw new LobException("Lob too large to store as SHORT_LOB"); } if (blobRef.getBytes().length >= AkBlob.LOB_SWITCH_SIZE) { UUID id = UUID.randomUUID(); getLobService().createNewLob(id.toString()); getLobService().writeBlob(id.toString(), 0, blobRef.getBytes()); BlobRef newBlob = new BlobRef(id); resRow.overlay(i, newBlob); changedRow = true; } } if (blobRef.isLongLob()) { getLobService().linkTableBlob(blobRef.getId().toString(), tableId); } } } return changedRow ? resRow : row; } @Override protected void deleteLobs(Row row) { RowType rowType = row.rowType(); for( int i = 0; i < rowType.nFields(); i++ ) { if (rowType.typeAt(i).equalsExcludingNullable(AkBlob.INSTANCE.instance(true))) { BlobRef blobRef = (BlobRef)row.value(i).getObject(); if (blobRef == null) { continue; } if (blobRef.isLongLob()) { getLobService().deleteLob(blobRef.getId().toString()); } } } } private LobService getLobService() { if (lobService == null) lobService = serviceManager.getServiceByClass(LobService.class); return lobService; } @Override protected void registerLobForOnlineDelete(Session session, String schemaName, String tableRootName, UUID lobId) { List<String> path = FDBNameGenerator.onlineLobPath(schemaName, tableRootName); TransactionState tr = txnService.getTransaction(session); DirectorySubspace dir = rootDir.createOrOpen(tr.getTransaction(), path).get(); byte[] key = dir.pack(AkGUID.uuidToBytes(lobId)); tr.setBytes(key, EMPTY_BYTE_ARRAY); } @Override protected void executeLobOnlineDelete(Session session, String schemaName, String tableName) { List<String> onlineLobPath = FDBNameGenerator.onlineLobPath(schemaName, tableName); TransactionState tr = txnService.getTransaction(session); if (rootDir.exists(tr.getTransaction(), onlineLobPath).get()) { DirectorySubspace dir = rootDir.createOrOpen(tr.getTransaction(), onlineLobPath).get(); AsyncIterator<KeyValue> it = tr.getRangeIterator(dir.range(), Integer.MAX_VALUE).iterator(); while(it.hasNext()) { KeyValue kv = it.next(); Tuple t = dir.unpack(kv.getKey()); getLobService().deleteLob(AkGUID.bytesToUUID(t.getBytes(0), 0).toString()); } rootDir.removeIfExists(tr.getTransaction(), onlineLobPath).get(); } } // KeyCreator @Override public Key createKey() { return new Key(null, 2047); } // Storage iterators public TransactionState getTransaction(Session session, FDBStoreData storeData) { return txnService.getTransaction(session); } public enum GroupIteratorBoundary { START, END, KEY, NEXT_KEY, FIRST_DESCENDANT, LAST_DESCENDANT } /** Iterate over the whole group. */ public void groupIterator(Session session, FDBStoreData storeData) { groupIterator(session, storeData, GroupIteratorBoundary.START, GroupIteratorBoundary.END, Transaction.ROW_LIMIT_UNLIMITED, FDBScanTransactionOptions.NORMAL); } /** Iterate over just <code>storeData.persistitKey</code>, if present. */ public void groupKeyIterator(Session session, FDBStoreData storeData, FDBScanTransactionOptions transactionOptions) { // NOTE: Caller checks whether key returned matches. groupIterator(session, storeData, GroupIteratorBoundary.KEY, GroupIteratorBoundary.NEXT_KEY, 1, transactionOptions); } /** Iterate over <code>storeData.persistitKey</code>'s descendants. */ public void groupDescendantsIterator(Session session, FDBStoreData storeData) { groupIterator(session, storeData, GroupIteratorBoundary.FIRST_DESCENDANT, GroupIteratorBoundary.LAST_DESCENDANT, Transaction.ROW_LIMIT_UNLIMITED, FDBScanTransactionOptions.NORMAL); } /** Iterate over <code>storeData.persistitKey</code>'s descendants. */ public void groupKeyAndDescendantsIterator(Session session, FDBStoreData storeData, FDBScanTransactionOptions transactionOptions) { groupIterator(session, storeData, GroupIteratorBoundary.KEY, GroupIteratorBoundary.LAST_DESCENDANT, Transaction.ROW_LIMIT_UNLIMITED, transactionOptions); } public void groupIterator(Session session, FDBStoreData storeData, FDBScanTransactionOptions transactionOptions) { groupIterator(session, storeData, GroupIteratorBoundary.START, GroupIteratorBoundary.END, Transaction.ROW_LIMIT_UNLIMITED, transactionOptions); } public void groupIterator(Session session, FDBStoreData storeData, GroupIteratorBoundary left, GroupIteratorBoundary right, int limit, FDBScanTransactionOptions transactionOptions) { storeData.storageDescription.groupIterator(this, session, storeData, left, right, limit, transactionOptions); } /** Iterate over the whole index. */ public void indexIterator(Session session, FDBStoreData storeData, FDBScanTransactionOptions transactionOptions) { indexIterator(session, storeData, false, false, false, transactionOptions); } public void indexIterator(Session session, FDBStoreData storeData, boolean key, boolean inclusive, boolean reverse, FDBScanTransactionOptions transactionOptions) { storeData.storageDescription.indexIterator(this, session, storeData, key, inclusive, reverse, transactionOptions); } // Internal private void constructIndexRow(Session session, Key indexKey, Row row, Index index, Key hKey, WriteIndexRow indexRow, SpatialColumnHandler spatialColumnHandler, long zValue, boolean forInsert) { indexKey.clear(); indexRow.resetForWrite(index, indexKey); indexRow.initialize(row, hKey, spatialColumnHandler, zValue); indexRow.close(session, forInsert); } private void checkUniqueness(Session session, TransactionState txn, Index index, Row row, Key key) { if(index.isUnique() && !hasNullIndexSegments(row, index)) { int realSize = key.getEncodedSize(); key.setDepth(index.getKeyColumns().size()); try { checkKeyDoesNotExistInIndex(session, txn, row, index, key); } finally { key.setEncodedSize(realSize); } } } private void checkKeyDoesNotExistInIndex(Session session, TransactionState txn, Row row, Index index, Key key) { assert index.isUnique() : index; FDBPendingIndexChecks.PendingCheck<?> check = FDBPendingIndexChecks.keyDoesNotExistInIndexCheck(session, txn, index, key); if (txn.getForceImmediateForeignKeyCheck() || txn.getIndexChecks(false) == null) { check.blockUntilReady(txn); if (!check.check(session, txn, index)) { // Using RowData, can give better error than check.throwException(). String msg = formatIndexRowString(session, row, index); throw new DuplicateKeyException(index.getIndexName(), msg); } } else { txn.getIndexChecks(false).add(session, txn, index, check); } } private void removeIfExists(Session session, DirectorySubspace dir, List<String> dirs) { try { Transaction txn = txnService.getTransaction(session).getTransaction(); dir.removeIfExists(txn, dirs).get(); } catch (RuntimeException e) { throw FDBAdapter.wrapFDBException(session, e); } } private boolean directoryExists (TransactionState txn, DirectorySubspace dir, List<String> dirs) { try { return dir.exists(txn.getTransaction(), dirs).get(); } catch (RuntimeException e) { throw FDBAdapter.wrapFDBException(txn.session, e); } } private long updateSequenceCache(Session session, Sequence s) { Transaction tr = txnService.getTransaction(session).getTransaction(); byte[] prefixBytes = prefixBytes(s); byte[] byteValue = tr.get(prefixBytes).get(); final long rawValue; if(byteValue != null) { Tuple2 tuple = Tuple2.fromBytes(byteValue); rawValue = tuple.getLong(0); } else { rawValue = 1; } tr.set(prefixBytes, Tuple2.from(rawValue + sequenceCacheSize).pack()); Map<Object, SequenceCache> sessionMap = session.get(SEQ_UPDATES_KEY); if(sessionMap == null) { txnService.addCallback(session, TransactionService.CallbackType.COMMIT, SEQUENCE_UPDATES_PUT_CALLBACK); txnService.addCallback(session, TransactionService.CallbackType.END, SEQUENCE_UPDATES_CLEAR_CALLBACK); } SequenceCache newCache = SequenceCache.newLocal(rawValue, sequenceCacheSize); session.put(SEQ_UPDATES_KEY, SequenceCache.cacheKey(s), newCache); return rawValue; } private static final ReadWriteMap.ValueCreator<Object, SequenceCache> SEQUENCE_CACHE_VALUE_CREATOR = new ReadWriteMap.ValueCreator<Object, SequenceCache>() { public SequenceCache createValueForKey (Object key) { return SequenceCache.newEmpty(); } }; private static final TransactionService.Callback SEQUENCE_UPDATES_CLEAR_CALLBACK = new TransactionService.Callback() { @Override public void run(Session session, long timestamp) { session.remove(SEQ_UPDATES_KEY); } }; private final TransactionService.Callback SEQUENCE_UPDATES_PUT_CALLBACK = new TransactionService.Callback() { @Override public void run(Session session, long timestamp) { Map<Object, SequenceCache> map = session.get(SEQ_UPDATES_KEY); for(Entry<Object, SequenceCache> entry : map.entrySet()) { SequenceCache global = SequenceCache.newGlobal(timestamp, entry.getValue()); sequenceCache.put(entry.getKey(), global); } } }; }
package org.opennms.nrtg.web.internal; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.opennms.netmgt.model.PrefabGraph; /** * @author Markus@OpenNMS.org */ public class NrtHelper { public static final List<String> RRD_KEYWORDS = Arrays.asList( " "DEF", "CDEF", "LINE", "GPRINT"); public String cleanUpRrdGraphStringForWebUi(final PrefabGraph prefabGraph, final Map<String,String> externalPropertyAttributes, final Map<String,String> stringPropertyAttributes) { String graphString = prefabGraph.getCommand(); //Overwrite height and width by cinematic ration 1x2.40 graphString = "--height=400 " + graphString; graphString = "--width=960 " + graphString; if (!graphString.contains("--slope-mode")) { graphString = "--slope-mode " + graphString; } if (!graphString.contains("--watermark")) { graphString = "--watermark=\"NRTG Alpha 1.0\" " + graphString; } // Escaping colons in rrd-strings rrd in javascript in java... graphString = graphString.replace("\\:", "\\\\\\\\:"); graphString = graphString.replace("\\n", "\\\\\\\\n"); // Escaping quotes in javascript in java graphString = graphString.replace("\"", "\\\\\""); for (final String key : externalPropertyAttributes.keySet()) { graphString = graphString.replace("{" + key + "}", externalPropertyAttributes.get(key)); } for (final String key : stringPropertyAttributes.keySet()) { graphString = graphString.replace("{" + key + "}", stringPropertyAttributes.get(key)); } return graphString; } public String generateJsMappingObject(String rrdCommand, final Map<String, String> rrdGraphAttributesToMetricIds) { final StringBuilder stringBuilder = new StringBuilder(); final String command = rrdCommand; final Pattern pattern = Pattern.compile("DEF:.*?=(\\{.*?\\}):(.*?):"); final Matcher matcher = pattern.matcher(command); final Map<String, String> rrdFileMapping = new HashMap<String, String>(); while (matcher.find()) { rrdFileMapping.put(matcher.group(2), matcher.group(1)); } for (final Map.Entry<String,String> entry : rrdGraphAttributesToMetricIds.entrySet()) { final String row = String.format("'%s': '%s:%s', %n", entry.getValue(), rrdFileMapping.get(entry.getKey()), entry.getKey()); stringBuilder.append(row); } return stringBuilder.toString().substring(0,stringBuilder.toString().length() - ", \n".length()); } }
package fr.inria.diverse.trace.api; import java.util.List; import java.util.Map; import org.eclipse.emf.ecore.EObject; public interface ITraceManager { void save(); void addState(); boolean addStateIfChanged(); void addEvent(String eventName, Map<String, Object> params); void retroAddEvent(String eventName, Map<String, Object> params); void endEvent(String eventName, Object returnValue); void initTrace(); EObject getTraceRoot(); int getTraceSize(); void goTo(int index); void goTo(EObject stateOrValue); EObject getExecutionState(int index); String getDescriptionOfExecutionState(int index); boolean isMacro(String string); String currentMacro(); int getNumberOfValueTraces(); List<List<? extends EObject>> getAllValueTraces(); String getDescriptionOfValue(EObject value); }
package net.silentchaos512.gems.api.tool; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import net.minecraft.item.ItemStack; import net.minecraft.util.math.MathHelper; import net.silentchaos512.gems.SilentGems; import net.silentchaos512.gems.api.ITool; import net.silentchaos512.gems.api.lib.ArmorPartPosition; import net.silentchaos512.gems.api.lib.EnumMaterialGrade; import net.silentchaos512.gems.api.lib.ToolPartPosition; import net.silentchaos512.gems.api.stats.CommonItemStats; import net.silentchaos512.gems.api.stats.ItemStat; import net.silentchaos512.gems.api.stats.ItemStatModifier; import net.silentchaos512.gems.api.stats.ItemStatModifier.Operation; import net.silentchaos512.gems.api.tool.part.ToolPart; import net.silentchaos512.gems.config.GemsConfig; import net.silentchaos512.gems.util.ArmorHelper; import net.silentchaos512.gems.util.ToolHelper; public final class ToolStats { public static final String ID_VARIETY_BONUS = "variety_bonus"; private final ToolPart[] parts; private final EnumMaterialGrade[] grades; public final ItemStack tool; public float durability = 0f; public float harvestSpeed = 0f; public float meleeDamage = 0f; public float magicDamage = 0f; public float meleeSpeed = 0f; public float chargeSpeed = 0f; public float enchantability = 0f; public float protection = 0f; public int harvestLevel = 0; public ToolStats(ItemStack tool) { this.tool = tool; this.parts = new ToolPart[0]; this.grades = new EnumMaterialGrade[0]; } public ToolStats(ItemStack tool, ToolPart[] parts, EnumMaterialGrade[] grades) { this.tool = tool; this.parts = parts; this.grades = grades; } public ToolStats calculate() { if (parts.length == 0) return this; Map<ItemStat, List<ItemStatModifier>> mods = new HashMap<>(); for (ItemStat stat : ItemStat.ALL_STATS) { mods.put(stat, new ArrayList<>()); } Set<ToolPart> uniqueParts = Sets.newConcurrentHashSet(); // Head (main) parts for (int i = 0; i < parts.length; ++i) { ToolPart part = parts[i]; EnumMaterialGrade grade = grades[i]; for (ItemStat stat : ItemStat.ALL_STATS) { ItemStatModifier statModifier = part.getStatModifier(stat, grade); if (statModifier != null) { mods.get(stat).add(statModifier); } } // float multi = (100 + grade.bonusPercent) / 100f; // durability += part.getDurability() * multi; // harvestSpeed += part.getHarvestSpeed() * multi; // meleeDamage += part.getMeleeDamage() * multi; // magicDamage += part.getMagicDamage() * multi; // meleeSpeed += part.getMeleeSpeed() * multi; // enchantability += part.getEnchantability() * multi; // chargeSpeed += part.getChargeSpeed() * multi; // protection += part.getProtection() * multi; // harvestLevel = Math.max(harvestLevel, part.getHarvestLevel()); uniqueParts.add(part); } // Variety bonus int variety = MathHelper.clamp(uniqueParts.size(), 1, GemsConfig.VARIETY_CAP); float bonus = 1.0f + GemsConfig.VARIETY_BONUS * (variety - 1); mods.get(CommonItemStats.DURABILITY) .add(new ItemStatModifier(ID_VARIETY_BONUS, bonus, Operation.MULTIPLY)); mods.get(CommonItemStats.HARVEST_SPEED) .add(new ItemStatModifier(ID_VARIETY_BONUS, bonus, Operation.MULTIPLY)); mods.get(CommonItemStats.MELEE_DAMAGE) .add(new ItemStatModifier(ID_VARIETY_BONUS, bonus, Operation.MULTIPLY)); mods.get(CommonItemStats.MAGIC_DAMAGE) .add(new ItemStatModifier(ID_VARIETY_BONUS, bonus, Operation.MULTIPLY)); mods.get(CommonItemStats.ATTACK_SPEED) .add(new ItemStatModifier(ID_VARIETY_BONUS, bonus, Operation.MULTIPLY)); mods.get(CommonItemStats.CHARGE_SPEED) .add(new ItemStatModifier(ID_VARIETY_BONUS, bonus, Operation.MULTIPLY)); mods.get(CommonItemStats.ENCHANTABILITY) .add(new ItemStatModifier(ID_VARIETY_BONUS, bonus, Operation.MULTIPLY)); mods.get(CommonItemStats.ARMOR) .add(new ItemStatModifier(ID_VARIETY_BONUS, bonus, Operation.MULTIPLY)); mods.get(CommonItemStats.MAGIC_ARMOR) .add(new ItemStatModifier(ID_VARIETY_BONUS, bonus, Operation.MULTIPLY)); // Tool class multipliers if (tool.getItem() instanceof ITool) { ITool itool = (ITool) tool.getItem(); durability *= itool.getDurabilityMultiplier(); harvestSpeed *= itool.getHarvestSpeedMultiplier(); } // Rod, tip, grip, frame ToolPart partRod = ToolHelper.getConstructionRod(tool); ToolPart partTip = ToolHelper.getConstructionTip(tool); ToolPart partGrip = ToolHelper.getPart(tool, ToolPartPosition.ROD_GRIP); ToolPart partFrame = ArmorHelper.getPart(tool, ArmorPartPosition.FRAME); for (ToolPart part : Lists.newArrayList(partRod, partTip, partGrip, partFrame)) { if (part != null) { for (ItemStat stat : ItemStat.ALL_STATS) { ItemStatModifier statModifier = part.getStatModifier(stat, EnumMaterialGrade.NONE); if (statModifier != null) { mods.get(stat).add(statModifier); } } } } durability = calcStat(CommonItemStats.DURABILITY, mods); harvestSpeed = calcStat(CommonItemStats.HARVEST_SPEED, mods); meleeDamage = calcStat(CommonItemStats.MELEE_DAMAGE, mods); magicDamage = calcStat(CommonItemStats.MAGIC_DAMAGE, mods); meleeSpeed = calcStat(CommonItemStats.ATTACK_SPEED, mods); chargeSpeed = calcStat(CommonItemStats.CHARGE_SPEED, mods); enchantability = calcStat(CommonItemStats.ENCHANTABILITY, mods); protection = calcStat(CommonItemStats.ARMOR, mods); harvestLevel = (int) calcStat(CommonItemStats.HARVEST_LEVEL, mods); return this; } public float calcStat(ItemStat stat, Map<ItemStat, List<ItemStatModifier>> mods) { // if (stat == CommonItemStats.CHARGE_SPEED) { // String str = ""; // for (ItemStatModifier mod : mods.get(stat)) { // str += "{" + mod.getId() + " " + mod.getOperation() + " " + mod.getAmount() + "}, "; // SilentGems.logHelper.debug(str); return stat.compute(0f, mods.get(stat)); } }
package com.exedio.cope.console; import java.io.File; import java.util.ArrayList; import java.util.Date; import com.exedio.cope.ConnectProperties; import com.exedio.cope.Feature; import com.exedio.cope.Model; import com.exedio.cope.SetValue; import com.exedio.cope.Type; import com.exedio.cope.pattern.MediaPath; import com.exedio.cope.util.CacheInfo; import com.exedio.cope.util.ConnectToken; import com.exedio.cope.util.ConnectionPoolInfo; final class HistoryThread extends Thread { static final Model HISTORY_MODEL = new Model( HistoryModel.TYPE, HistoryItemCache.TYPE, HistoryMedia.TYPE); private static final String NAME = "COPE History"; private final String name; private final Model watchedModel; private final String propertyFile; private final Object lock = new Object(); private final String topic; private final MediaPath[] medias; private volatile boolean proceed = true; HistoryThread(final Model model, final String propertyFile) { super(NAME); this.name = NAME + ' ' + '(' + Integer.toString(System.identityHashCode(this), 36) + ')'; setName(name); this.watchedModel = model; this.propertyFile = propertyFile; this.topic = name + ' '; assert model!=null; assert propertyFile!=null; final ArrayList<MediaPath> medias = new ArrayList<MediaPath>(); for(final Type<?> type : watchedModel.getTypes()) for(final Feature feature : type.getDeclaredFeatures()) if(feature instanceof MediaPath) medias.add((MediaPath)feature); this.medias = medias.toArray(new MediaPath[medias.size()]); } @Override public void run() { System.out.println(topic + "run() started"); try { sleepByWait(2000l); if(!proceed) return; System.out.println(topic + "run() connecting"); ConnectToken connectToken = null; final long connecting = System.currentTimeMillis(); try { connectToken = ConnectToken.issue(HISTORY_MODEL, new ConnectProperties(new File(propertyFile)), name); System.out.println(topic + "run() connected (" + (System.currentTimeMillis() - connecting) + "ms)"); try { HISTORY_MODEL.startTransaction("check"); HISTORY_MODEL.checkDatabase(); HISTORY_MODEL.commit(); } finally { HISTORY_MODEL.rollbackIfNotCommitted(); } for(int running = 0; proceed; running++) { System.out.println(topic + "run() LOG " + running); log(running); sleepByWait(60000l); } } finally { if(connectToken!=null) { System.out.println(topic + "run() disconnecting"); final long disconnecting = System.currentTimeMillis(); connectToken.returnIt(); System.out.println(topic + "run() disconnected (" + (System.currentTimeMillis() - disconnecting) + "ms)"); } else System.out.println(topic + "run() not connected"); } } catch(Exception e) { e.printStackTrace(); } } private void log(final int running) { // prepare final int thread = System.identityHashCode(this); final int MEDIAS_STAT_LENGTH = 7; final int[][] mediaValues = new int[medias.length][]; for(int i = 0; i<mediaValues.length; i++) mediaValues[i] = new int[MEDIAS_STAT_LENGTH]; // gather data final Date date = new Date(); final ConnectionPoolInfo connectionPoolInfo = watchedModel.getConnectionPoolInfo(); final long nextTransactionId = watchedModel.getNextTransactionId(); final CacheInfo[] itemCacheInfos = watchedModel.getItemCacheInfo(); final long[] queryCacheInfo = watchedModel.getQueryCacheInfo(); final int mediasNoSuchPath = MediaPath.noSuchPath.get(); int mediaValuesIndex = 0; for(final MediaPath path : medias) { mediaValues[mediaValuesIndex][0] = path.exception.get(); mediaValues[mediaValuesIndex][1] = path.notAnItem.get(); mediaValues[mediaValuesIndex][2] = path.noSuchItem.get(); mediaValues[mediaValuesIndex][3] = path.isNull.get(); mediaValues[mediaValuesIndex][4] = path.notComputable.get(); mediaValues[mediaValuesIndex][5] = path.notModified.get(); mediaValues[mediaValuesIndex][6] = path.delivered.get(); mediaValuesIndex++; } // process data long itemCacheHits = 0; long itemCacheMisses = 0; int itemCacheNumberOfCleanups = 0; int itemCacheItemsCleanedUp = 0; final SetValue[][] itemCacheSetValues = new SetValue[itemCacheInfos.length][]; int itemCacheSetValuesIndex = 0; for(final CacheInfo ci : itemCacheInfos) { itemCacheHits += ci.getHits(); itemCacheMisses += ci.getMisses(); itemCacheNumberOfCleanups += ci.getNumberOfCleanups(); itemCacheItemsCleanedUp += ci.getItemsCleanedUp(); itemCacheSetValues[itemCacheSetValuesIndex] = new SetValue[]{ null, // will be HistoryItemCache.model HistoryItemCache.type.map(ci.getType().getID()), HistoryItemCache.date.map(date), HistoryItemCache.thread.map(thread), HistoryItemCache.running.map(running), HistoryItemCache.limit.map(ci.getLimit()), HistoryItemCache.level.map(ci.getLevel()), HistoryItemCache.hits.map(ci.getHits()), HistoryItemCache.misses.map(ci.getMisses()), HistoryItemCache.numberOfCleanups.map(ci.getNumberOfCleanups()), HistoryItemCache.itemsCleanedUp.map(ci.getItemsCleanedUp()), HistoryItemCache.lastCleanup.map(ci.getLastCleanup()), HistoryItemCache.ageAverageMillis.map(ci.getAgeAverageMillis()), HistoryItemCache.ageMinMillis.map(ci.getAgeMinMillis()), HistoryItemCache.ageMaxMillis.map(ci.getAgeMaxMillis()), }; itemCacheSetValuesIndex++; } final int[] mediaTotal = new int[MEDIAS_STAT_LENGTH]; final SetValue[][] mediaSetValues = new SetValue[medias.length][]; int mediaSetValuesIndex = 0; for(int[] mediaValue : mediaValues) { for(int i = 0; i<MEDIAS_STAT_LENGTH; i++) mediaTotal[i] += mediaValue[i]; mediaSetValues[mediaSetValuesIndex] = new SetValue[]{ null, // will be HistoryMedia.model HistoryMedia.media.map(medias[mediaSetValuesIndex].getID()), HistoryMedia.date.map(date), HistoryMedia.thread.map(thread), HistoryMedia.running.map(running), HistoryMedia.exception .map(mediaValue[0]), HistoryMedia.notAnItem .map(mediaValue[1]), HistoryMedia.noSuchItem .map(mediaValue[2]), HistoryMedia.isNull .map(mediaValue[3]), HistoryMedia.notComputable.map(mediaValue[4]), HistoryMedia.notModified .map(mediaValue[5]), HistoryMedia.delivered .map(mediaValue[6]), }; mediaSetValuesIndex++; } final SetValue[] setValues = new SetValue[]{ HistoryModel.date.map(date), HistoryModel.thread.map(thread), HistoryModel.running.map(running), HistoryModel.connectionPoolIdle.map(connectionPoolInfo.getIdleCounter()), HistoryModel.connectionPoolGet.map(connectionPoolInfo.getCounter().getGetCounter()), HistoryModel.connectionPoolPut.map(connectionPoolInfo.getCounter().getPutCounter()), HistoryModel.connectionPoolInvalidFromIdle.map(connectionPoolInfo.getInvalidFromIdle()), HistoryModel.connectionPoolInvalidIntoIdle.map(connectionPoolInfo.getInvalidIntoIdle()), HistoryModel.nextTransactionId.map(nextTransactionId), HistoryModel.itemCacheHits.map(itemCacheHits), HistoryModel.itemCacheMisses.map(itemCacheMisses), HistoryModel.itemCacheNumberOfCleanups.map(itemCacheNumberOfCleanups), HistoryModel.itemCacheItemsCleanedUp.map(itemCacheItemsCleanedUp), HistoryModel.queryCacheHits.map(queryCacheInfo[0]), HistoryModel.queryCacheMisses.map(queryCacheInfo[1]), HistoryModel.mediasNoSuchPath.map(mediasNoSuchPath), HistoryModel.mediasException .map(mediaTotal[0]), HistoryModel.mediasNotAnItem .map(mediaTotal[1]), HistoryModel.mediasNoSuchItem .map(mediaTotal[2]), HistoryModel.mediasIsNull .map(mediaTotal[3]), HistoryModel.mediasNotComputable.map(mediaTotal[4]), HistoryModel.mediasNotModified .map(mediaTotal[5]), HistoryModel.mediasDelivered .map(mediaTotal[6]) }; // save data try { HISTORY_MODEL.startTransaction(topic + running); final HistoryModel model = new HistoryModel(setValues); { final SetValue modelSetValue = HistoryItemCache.model.map(model); for(final SetValue[] itemCacheSetValue : itemCacheSetValues) { assert itemCacheSetValue[0]==null : itemCacheSetValue[0]; itemCacheSetValue[0] = modelSetValue; new HistoryItemCache(itemCacheSetValue); } } final SetValue modelSetValue = HistoryMedia.model.map(model); for(SetValue[] mediaSetValue : mediaSetValues) { assert mediaSetValue[0]==null : mediaSetValue[0]; mediaSetValue[0] = modelSetValue; new HistoryMedia(mediaSetValue); } HISTORY_MODEL.commit(); } finally { HISTORY_MODEL.rollbackIfNotCommitted(); } } private void sleepByWait(final long millis) { synchronized(lock) { //System.out.println(topic + "run() sleeping (" + millis + "ms)"); //final long sleeping = System.currentTimeMillis(); try { lock.wait(millis); } catch(InterruptedException e) { throw new RuntimeException(e); } //System.out.println(topic + "run() slept (" + (System.currentTimeMillis()-sleeping) + "ms)"); } } void stopAndJoin() { System.out.println(topic + "stopAndJoin() entering"); proceed = false; synchronized(lock) { System.out.println(topic + "stopAndJoin() notifying"); lock.notify(); } System.out.println(topic + "stopAndJoin() notified"); final long joining = System.currentTimeMillis(); try { join(); } catch(InterruptedException e) { throw new RuntimeException(e); } System.out.println(topic + "stopAndJoin() joined (" + (System.currentTimeMillis() - joining) + "ms)"); } @Override public String toString() { return name; } }
package com.exedio.copernica; import net.sourceforge.jwebunit.WebTestCase; public class WebTest extends WebTestCase { public WebTest(String name) { super(name); } String someNotNullString; String someNotNullInteger; String someBoolean; public void setUp() throws Exception { super.setUp(); getTestContext().setBaseUrl("http://localhost:8080/copernicatest/"); someNotNullString = "running100"; someNotNullInteger = "107"; someBoolean = "NULL"; } private void assertItemForm() { assertFormElementEquals("someNotNullString", someNotNullString); assertFormElementEquals("someNotNullInteger", someNotNullInteger); assertFormElementEquals("someBoolean", someBoolean); } public void testSearch() { beginAt("copernica.jsp"); assertTitleEquals("Copernica"); assertLinkPresentWithText("de"); clickLinkWithText("Attribute Item"); assertTitleEquals("Attribute Item"); assertTextPresent("Attribute Item"); assertLinkPresentWithText("50"); clickLinkWithText("50"); assertTitleEquals("Attribute Item"); assertLinkNotPresentWithText("50"); clickLinkWithText("[X]"); assertTitleEquals("AttributeItem.103"); assertItemForm(); setFormElement("someNotNullString", "running100changed"); someNotNullString = "running100changed"; submit("SAVE"); assertTitleEquals("AttributeItem.103"); assertItemForm(); setFormElement("someNotNullInteger", "1077"); someNotNullInteger = "1077"; submit("SAVE"); assertTitleEquals("AttributeItem.103"); assertItemForm(); setFormElement("someBoolean", "TRUE"); someBoolean = "TRUE"; submit("SAVE"); assertTitleEquals("AttributeItem.103"); assertItemForm(); setFormElement("someNotNullString", "running100"); someNotNullString = "running100"; setFormElement("someNotNullInteger", "107"); someNotNullInteger = "107"; setFormElement("someBoolean", "NULL"); someBoolean = "NULL"; submit("SAVE"); assertTitleEquals("AttributeItem.103"); assertItemForm(); } }
package com.censoredsoftware.Demigods.Enum; import java.util.ArrayList; import org.bukkit.ChatColor; import org.bukkit.inventory.ItemStack; import com.censoredsoftware.Demigods.API.ItemAPI; public enum Books { /** * _Alex's Secret Book */ ALEX_SECRET_BOOK(new Book(25.0, ItemAPI.createBook(ChatColor.GOLD + "_Alex's Secret Book", "_Alex", new ArrayList<String>() { { add("Whoa... you found my book! Please be careful with it. It can be pretty powerful!"); add("Shh!"); } }, null))), /** * The Book of Ages */ BOOK_OF_AGES(new Book(75.0, ItemAPI.createBook(ChatColor.MAGIC + "The Book of Ages", "Steve", new ArrayList<String>() { { add(ChatColor.MAGIC + "You cannot comprehend the power contained in this book."); } }, null))); private Book value; private Books(Book value) { this.value = value; } public Book getBook() { return this.value; } public static class Book { private Double chance; private ItemStack item; public Book(Double chance, ItemStack item) { this.chance = chance; this.item = item; } public ItemStack getItem() { return item; } public Double getChance() { return chance; } } }
package aptgraph.core; import info.debatty.java.graphs.SimilarityInterface; import java.io.Serializable; /** * * @author Thibault Debatty */ public class DomainSimilarity implements SimilarityInterface<Request>, Serializable { /** * Compute the similarity between requests Domains. * @param r1 * @param r2 * @return */ public final double similarity(final Request r1, final Request r2) { double counter = 0.0; String[] domain_r1 = r1.getDomain().split("[.]"); String[] domain_r2 = r2.getDomain().split("[.]"); if (domain_r1[domain_r1.length - 1] .equals(domain_r2[domain_r2.length - 1]) && domain_r1.length > 1 && domain_r2.length > 1) { for (int i = 1; i <= Math.min(domain_r1.length, domain_r2.length) - 1; i++) { if (domain_r1[domain_r1.length - i - 1] .equals(domain_r2[domain_r2.length - i - 1])) { counter++; } else { break; } } return counter / (Math.max(domain_r1.length, domain_r2.length) - 1); } else { if (r1.getDomain().equals(r2.getDomain())) { counter++; } return counter / (Math.max(domain_r1.length, domain_r2.length)); } } }
package brooklyn.entity.basic; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.concurrent.ExecutionException; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import brooklyn.config.BrooklynProperties; import brooklyn.config.ConfigKey; import brooklyn.config.ConfigKey.HasConfigKey; import brooklyn.entity.Application; import brooklyn.entity.Effector; import brooklyn.entity.Entity; import brooklyn.entity.Group; import brooklyn.entity.drivers.EntityDriver; import brooklyn.entity.drivers.downloads.DownloadResolver; import brooklyn.entity.effector.Effectors; import brooklyn.entity.trait.Startable; import brooklyn.entity.trait.StartableMethods; import brooklyn.event.AttributeSensor; import brooklyn.event.Sensor; import brooklyn.event.basic.DependentConfiguration; import brooklyn.location.Location; import brooklyn.location.LocationSpec; import brooklyn.management.ExecutionContext; import brooklyn.management.LocationManager; import brooklyn.management.ManagementContext; import brooklyn.management.Task; import brooklyn.management.TaskAdaptable; import brooklyn.management.TaskFactory; import brooklyn.management.internal.EffectorUtils; import brooklyn.management.internal.LocalManagementContext; import brooklyn.management.internal.ManagementContextInternal; import brooklyn.management.internal.NonDeploymentManagementContext; import brooklyn.policy.Policy; import brooklyn.policy.basic.AbstractPolicy; import brooklyn.util.ResourceUtils; import brooklyn.util.collections.MutableMap; import brooklyn.util.exceptions.Exceptions; import brooklyn.util.flags.FlagUtils; import brooklyn.util.task.DynamicTasks; import brooklyn.util.task.ParallelTask; import brooklyn.util.task.Tasks; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.reflect.TypeToken; /** * Convenience methods for working with entities. * <p> * Also see the various {@code *Methods} classes for traits, * such as {@link StartableMethods} for {@link Startable} implementations. */ public class Entities { private static final Logger log = LoggerFactory.getLogger(Entities.class); /** * Names that, if they appear anywhere in an attribute/config/field indicates that it * may be private, so should not be logged etc. */ private static final List<String> SECRET_NAMES = ImmutableList.of( "password", "passwd", "credential", "secret", "private", "access.cert", "access.key"); /** * Invokes an {@link Effector} on multiple entities, with the named arguments from the parameters {@link Map} * using the context of the provided {@link Entity}. * <p> * Intended for use only from the callingEntity. * <p> * Returns a {@link ParallelTask} containing the results from each tasks invocation. Calling * {@link java.util.concurrent.Future#get() get()} on this will block until all tasks are complete, * and will throw an exception if any task resulted in an error. * * @return {@link ParallelTask} containing results from each invocation */ public static <T> Task<List<T>> invokeEffectorList(EntityLocal callingEntity, Iterable<? extends Entity> entitiesToCall, final Effector<T> effector, final Map<String,?> parameters) { // formulation is complicated, but it is building up a list of tasks, without blocking on them initially, // but ensuring that when the parallel task is gotten it does block on all of them if (entitiesToCall == null){ entitiesToCall = ImmutableList.of(); } List<TaskAdaptable<T>> tasks = Lists.newArrayList(); for (final Entity entity : entitiesToCall) { tasks.add( Effectors.invocation(entity, effector, parameters) ); } ParallelTask<T> invoke = new ParallelTask<T>( MutableMap.of( "displayName", effector.getName()+" (parallel)", "description", "Invoking effector \""+effector.getName()+"\" on "+tasks.size()+(tasks.size() == 1 ? " entity" : " entities"), "tag", BrooklynTasks.tagForCallerEntity(callingEntity)), tasks); return DynamicTasks.queueIfPossible(invoke).orSubmitAsync(callingEntity).asTask(); } public static <T> Task<List<T>> invokeEffectorListWithMap(EntityLocal callingEntity, Iterable<? extends Entity> entitiesToCall, final Effector<T> effector, final Map<String,?> parameters) { return invokeEffectorList(callingEntity, entitiesToCall, effector, parameters); } @SuppressWarnings("unchecked") public static <T> Task<List<T>> invokeEffectorListWithArgs(EntityLocal callingEntity, Iterable<? extends Entity> entitiesToCall, final Effector<T> effector, Object ...args) { return invokeEffectorListWithMap(callingEntity, entitiesToCall, effector, // putting into a map, unnecessarily, as it ends up being the array again... EffectorUtils.prepareArgsForEffectorAsMapFromArray(effector, args)); } public static <T> Task<List<T>> invokeEffectorList(EntityLocal callingEntity, Iterable<? extends Entity> entitiesToCall, final Effector<T> effector) { return invokeEffectorList(callingEntity, entitiesToCall, effector, Collections.<String,Object>emptyMap()); } public static <T> Task<T> invokeEffector(EntityLocal callingEntity, Entity entityToCall, final Effector<T> effector, final Map<String,?> parameters) { Task<T> t = Effectors.invocation(entityToCall, effector, parameters).asTask(); // we pass to callingEntity for consistency above, but in exec-context it should be // re-dispatched to targetEntity ((EntityInternal)callingEntity).getManagementSupport().getExecutionContext().submit( MutableMap.of("tag", BrooklynTasks.tagForCallerEntity(callingEntity)), t); return t; } @SuppressWarnings("unchecked") public static <T> Task<T> invokeEffectorWithArgs(EntityLocal callingEntity, Entity entityToCall, final Effector<T> effector, Object ...args) { return invokeEffector(callingEntity, entityToCall, effector, EffectorUtils.prepareArgsForEffectorAsMapFromArray(effector, args)); } public static <T> Task<T> invokeEffector(EntityLocal callingEntity, Entity entityToCall, final Effector<T> effector) { return invokeEffector(callingEntity, entityToCall, effector, Collections.<String,Object>emptyMap()); } /** convenience - invokes in parallel if multiple, but otherwise invokes the item directly */ public static Task<?> invokeEffector(EntityLocal callingEntity, Iterable<? extends Entity> entitiesToCall, final Effector<?> effector, final Map<String,?> parameters) { if (Iterables.size(entitiesToCall)==1) return invokeEffector(callingEntity, entitiesToCall.iterator().next(), effector, parameters); else return invokeEffectorList(callingEntity, entitiesToCall, effector, parameters); } /** convenience - invokes in parallel if multiple, but otherwise invokes the item directly */ public static Task<?> invokeEffector(EntityLocal callingEntity, Iterable<? extends Entity> entitiesToCall, final Effector<?> effector) { return invokeEffector(callingEntity, entitiesToCall, effector, Collections.<String,Object>emptyMap()); } public static boolean isSecret(String name) { String lowerName = name.toLowerCase(); for (String secretName : SECRET_NAMES) { if (lowerName.contains(secretName)) return true; } return false; } public static boolean isTrivial(Object v) { return v==null || (v instanceof Map && ((Map<?,?>)v).isEmpty()) || (v instanceof Collection && ((Collection<?>)v).isEmpty()) || (v instanceof CharSequence&& ((CharSequence)v).length() == 0); } public static <K> Map<K,Object> sanitize(Map<K,?> input) { Map<K,Object> result = Maps.newLinkedHashMap(); for (Map.Entry<K,?> e: input.entrySet()) { if (isSecret(""+e.getKey())) result.put(e.getKey(), "xxxxxxxx"); else result.put(e.getKey(), e.getValue()); } return result; } public static void dumpInfo(Iterable<? extends Entity> entities) { for (Entity e : entities) { dumpInfo(e); } } public static void dumpInfo(Entity e) { try { dumpInfo(e, new PrintWriter(System.out), "", " "); } catch (IOException exc) { // system.out throwing an exception is odd, so don't have IOException on signature throw new RuntimeException(exc); } } public static void dumpInfo(Entity e, Writer out) throws IOException { dumpInfo(e, out, "", " "); } public static void dumpInfo(Entity e, String currentIndentation, String tab) throws IOException { dumpInfo(e, new PrintWriter(System.out), currentIndentation, tab); } public static void dumpInfo(Entity e, Writer out, String currentIndentation, String tab) throws IOException { out.append(currentIndentation+e.toString()+"\n"); out.append(currentIndentation+tab+tab+"locations = "+e.getLocations()+"\n"); for (ConfigKey<?> it : sortConfigKeys(e.getEntityType().getConfigKeys())) { Object v = ((EntityInternal)e).getConfigMap().getRawConfig(it); if (!isTrivial(v)) { out.append(currentIndentation+tab+tab+it.getName()); out.append(" = "); if (isSecret(it.getName())) out.append("xxxxxxxx"); else if ((v instanceof Task) && ((Task<?>)v).isDone()) { if (((Task<?>)v).isError()) { out.append("ERROR in "+v); } else { try { out.append(((Task<?>)v).get() + " (from "+v+")"); } catch (ExecutionException ee) { throw new IllegalStateException("task "+v+" done and !isError, but threw exception on get", ee); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return; } } } else out.append(""+v); out.append("\n"); } } for (Sensor<?> it : sortSensors(e.getEntityType().getSensors())) { if (it instanceof AttributeSensor) { Object v = e.getAttribute((AttributeSensor<?>)it); if (!isTrivial(v)) { out.append(currentIndentation+tab+tab+it.getName()); out.append(": "); if (isSecret(it.getName())) out.append("xxxxxxxx"); else out.append(""+v); out.append("\n"); } } } if (e instanceof Group) { StringBuilder members = new StringBuilder(); for (Entity it : ((Group)e).getMembers()) { members.append(it.getId()+", "); } out.append(currentIndentation+tab+tab+"Members: "+members.toString()+"\n"); } out.append(currentIndentation+tab+tab+"Policies:\n"); for (Policy policy : e.getPolicies()) { dumpInfo(policy, out, currentIndentation+tab+tab+tab, tab); } for (Entity it : e.getChildren()) { dumpInfo(it, out, currentIndentation+tab, tab); } out.flush(); } public static void dumpInfo(Location loc) { try { dumpInfo(loc, new PrintWriter(System.out), "", " "); } catch (IOException exc) { // system.out throwing an exception is odd, so don't have IOException on signature throw new RuntimeException(exc); } } public static void dumpInfo(Location loc, Writer out) throws IOException { dumpInfo(loc, out, "", " "); } public static void dumpInfo(Location loc, String currentIndentation, String tab) throws IOException { dumpInfo(loc, new PrintWriter(System.out), currentIndentation, tab); } @SuppressWarnings("rawtypes") public static void dumpInfo(Location loc, Writer out, String currentIndentation, String tab) throws IOException { out.append(currentIndentation+loc.toString()+"\n"); for (Object entryO : loc.getAllConfig(true).entrySet()) { Map.Entry entry = (Map.Entry)entryO; Object keyO = entry.getKey(); String key = keyO instanceof HasConfigKey ? ((HasConfigKey)keyO).getConfigKey().getName() : keyO instanceof ConfigKey ? ((ConfigKey)keyO).getName() : keyO == null ? null : keyO.toString(); Object val = entry.getValue(); if (!isTrivial(val)) { out.append(currentIndentation+tab+tab+key); out.append(" = "); if (isSecret(key)) out.append("xxxxxxxx"); else out.append(""+val); out.append("\n"); } } for (Map.Entry<String,?> entry : sortMap(FlagUtils.getFieldsWithFlags(loc)).entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); if (!isTrivial(val)) { out.append(currentIndentation+tab+tab+key); out.append(" = "); if (isSecret(key)) out.append("xxxxxxxx"); else out.append(""+val); out.append("\n"); } } for (Location it : loc.getChildren()) { dumpInfo(it, out, currentIndentation+tab, tab); } out.flush(); } public static void dumpInfo(Policy pol) { try { dumpInfo(pol, new PrintWriter(System.out), "", " "); } catch (IOException exc) { // system.out throwing an exception is odd, so don't have IOException on signature throw new RuntimeException(exc); } } public static void dumpInfo(Policy pol, Writer out) throws IOException { dumpInfo(pol, out, "", " "); } public static void dumpInfo(Policy pol, String currentIndentation, String tab) throws IOException { dumpInfo(pol, new PrintWriter(System.out), currentIndentation, tab); } public static void dumpInfo(Policy pol, Writer out, String currentIndentation, String tab) throws IOException { out.append(currentIndentation+pol.toString()+"\n"); for (ConfigKey<?> key : sortConfigKeys(pol.getPolicyType().getConfigKeys())) { Object val = ((AbstractPolicy)pol).getConfigMap().getRawConfig(key); if (!isTrivial(val)) { out.append(currentIndentation+tab+tab+key); out.append(" = "); if (isSecret(key.getName())) out.append("xxxxxxxx"); else out.append(""+val); out.append("\n"); } } out.flush(); } @SuppressWarnings({ "rawtypes", "unchecked" }) public static List<Sensor<?>> sortSensors(Set<Sensor<?>> sensors) { List result = new ArrayList(sensors); Collections.sort(result, new Comparator<Sensor>() { @Override public int compare(Sensor arg0, Sensor arg1) { return arg0.getName().compareTo(arg1.getName()); } }); return result; } @SuppressWarnings({ "rawtypes", "unchecked" }) public static List<ConfigKey<?>> sortConfigKeys(Set<ConfigKey<?>> configs) { List result = new ArrayList(configs); Collections.sort(result, new Comparator<ConfigKey>() { @Override public int compare(ConfigKey arg0, ConfigKey arg1) { return arg0.getName().compareTo(arg1.getName()); } }); return result; } public static <T> Map<String, T> sortMap(Map<String, T> map) { Map<String,T> result = Maps.newLinkedHashMap(); List<String> order = Lists.newArrayList(map.keySet()); Collections.sort(order, String.CASE_INSENSITIVE_ORDER); for (String key : order) { result.put(key, map.get(key)); } return result; } public static boolean isAncestor(Entity descendant, Entity potentialAncestor) { Entity ancestor = descendant.getParent(); while (ancestor != null) { if (ancestor.equals(potentialAncestor)) return true; ancestor = ancestor.getParent(); } return false; } /** note, it is usually preferred to use isAncestor() and swap the order, it is a cheaper method */ public static boolean isDescendant(Entity ancestor, Entity potentialDescendant) { Set<Entity> inspected = Sets.newLinkedHashSet(); Stack<Entity> toinspect = new Stack<Entity>(); toinspect.add(ancestor); while (!toinspect.isEmpty()) { Entity e = toinspect.pop(); if (e.getChildren().contains(potentialDescendant)) { return true; } inspected.add(e); toinspect.addAll(e.getChildren()); toinspect.removeAll(inspected); } return false; } private static final List<Entity> entitiesToStopOnShutdown = Lists.newArrayList(); private static final AtomicBoolean isShutdownHookRegistered = new AtomicBoolean(); public static void invokeStopOnShutdown(Entity entity) { if (isShutdownHookRegistered.compareAndSet(false, true)) { ResourceUtils.addShutdownHook(new Runnable() { @SuppressWarnings({ "unchecked", "rawtypes" }) public void run() { synchronized (entitiesToStopOnShutdown) { log.info("Brooklyn stopOnShutdown shutdown-hook invoked: stopping "+entitiesToStopOnShutdown); List<Task> stops = new ArrayList<Task>(); for (Entity entity: entitiesToStopOnShutdown) { try { stops.add(entity.invoke(Startable.STOP, new MutableMap())); } catch (Exception exc) { log.debug("stopOnShutdown of "+entity+" returned error: "+exc, exc); } } for (Task t: stops) { try { log.debug("stopOnShutdown of {} completed: {}", t, t.get()); } catch (Exception exc) { log.debug("stopOnShutdown of "+t+" returned error: "+exc, exc); } } } } }); } synchronized (entitiesToStopOnShutdown) { entitiesToStopOnShutdown.add(entity); } } /** convenience for starting an entity, esp a new Startable instance which has been created dynamically * (after the application is started) */ public static void start(Entity e, Collection<? extends Location> locations) { if (!isManaged(e) && !manage(e)) { log.warn("Using discouraged mechanism to start management -- Entities.start(Application, Locations) -- caller should create and use the preferred management context"); startManagement(e); } if (e instanceof Startable) Entities.invokeEffector((EntityLocal)e, e, Startable.START, MutableMap.of("locations", locations)).getUnchecked(); } /** stops, destroys, and unmanages the given entity -- does as many as are valid given the type and state */ public static void destroy(Entity e) { if (isManaged(e)) { if (e instanceof Startable) Entities.invokeEffector((EntityLocal)e, e, Startable.STOP).getUnchecked(); if (e instanceof EntityInternal) ((EntityInternal)e).destroy(); unmanage(e); log.debug("destroyed and unmanaged "+e+"; mgmt now "+ (e.getApplicationId()==null ? "(no app)" : e.getApplication().getManagementContext())+" - managed? "+isManaged(e)); } else { log.debug("skipping destroy of "+e+": not managed"); } } /** as {@link #destroy(Entity)} but catching all errors */ public static void destroyCatching(Entity entity) { try { destroy(entity); } catch (Exception e) { log.warn("ERROR destroying "+entity+" (ignoring): "+e, e); Exceptions.propagateIfFatal(e); } } /** stops, destroys, and unmanages all apps in the given context, * and then terminates the management context */ public static void destroyAll(ManagementContext mgmt) { Exception error = null; if (mgmt instanceof NonDeploymentManagementContext) { // log here because it is easy for tests to destroyAll(app.getMgmtContext()) // which will *not* destroy the mgmt context if the app has been stopped! log.warn("Entities.destroyAll invoked on non-deployment "+mgmt+" - not likely to have much effect! " + "(This usually means the mgmt context has been taken from entity has been destroyed. " + "To destroy other things on the management context ensure you keep a handle to the context " + "before the entity is destroyed, such as by creating the management context first.)"); } if (!mgmt.isRunning()) return; log.debug("destroying all apps in "+mgmt+": "+mgmt.getApplications()); for (Application app: mgmt.getApplications()) { log.debug("destroying app "+app+" (managed? "+isManaged(app)+"; mgmt is "+mgmt+")"); try { destroy(app); log.debug("destroyed app "+app+"; mgmt now "+mgmt); } catch (Exception e) { log.warn("problems destroying app "+app+" (mgmt now "+mgmt+", will rethrow at least one exception): "+e); if (error==null) error = e; } } if (mgmt instanceof ManagementContextInternal) ((ManagementContextInternal)mgmt).terminate(); if (error!=null) throw Exceptions.propagate(error); } /** as {@link #destroyAll(ManagementContext)} but catching all errors */ public static void destroyAllCatching(ManagementContext mgmt) { try { destroyAll(mgmt); } catch (Exception e) { log.warn("ERROR destroying "+mgmt+" (ignoring): "+e, e); Exceptions.propagateIfFatal(e); } } /** * stops, destroys, and unmanages the given application -- and terminates the mangaement context; * does as many as are valid given the type and state * @deprecated since 0.6.0 use destroy(Application) if you DONT want to destroy the mgmt context, * or destroy(app.getManagementContext()) if you want to destory everything in the app's mgmt context */ @Deprecated public static void destroyAll(Application app) { if (isManaged(app)) { ManagementContext managementContext = app.getManagementContext(); if (app instanceof Startable) Entities.invokeEffector((EntityLocal)app, app, Startable.STOP).getUnchecked(); if (app instanceof AbstractEntity) ((AbstractEntity)app).destroy(); unmanage(app); if (managementContext instanceof ManagementContextInternal) ((ManagementContextInternal)managementContext).terminate(); } } public static boolean isManaged(Entity e) { return ((EntityInternal)e).getManagementSupport().isDeployed() && ((EntityInternal)e).getManagementContext().isRunning(); } /** brings this entity under management iff its ancestor is managed, returns true in that case; * otherwise returns false in the expectation that the ancestor will become managed, * or throws exception if it has no parent or a non-application root * (will throw if e is an Application; see also {@link #startManagement(Entity)} ) */ public static boolean manage(Entity e) { Entity o = e.getParent(); Entity eum = e; //highest unmanaged ancestor if (o==null) throw new IllegalStateException("Can't manage "+e+" because it is an orphan"); while (o.getParent()!=null) { if (!isManaged(o)) eum = o; o = o.getParent(); } if (isManaged(o)) { ((EntityInternal)o).getManagementContext().getEntityManager().manage(eum); return true; } if (!(o instanceof Application)) throw new IllegalStateException("Can't manage "+e+" because it is not rooted at an application"); return false; } /** brings this entity under management, creating a local management context if necessary * (assuming root is an application). * returns existing management context if there is one (non-deployment), * or new local mgmt context if not, * or throwing exception if root is not an application * <p> * callers are recommended to use {@link #manage(Entity)} instead unless they know * a plain-vanilla non-root management context is sufficient (e.g. in tests) * <p> * this method may change, but is provided as a stop-gap to prevent ad-hoc things * being done in the code which are even more likely to break! */ public static ManagementContext startManagement(Entity e) { Entity o = e; Entity eum = e; //highest unmanaged ancestor while (o.getParent()!=null) { if (!isManaged(o)) eum = o; o = o.getParent(); } if (isManaged(o)) { ManagementContext mgmt = ((EntityInternal)o).getManagementContext(); mgmt.getEntityManager().manage(eum); return mgmt; } if (!(o instanceof Application)) throw new IllegalStateException("Can't manage "+e+" because it is not rooted at an application"); ManagementContext mgmt = new LocalManagementContext(); mgmt.getEntityManager().manage(o); return mgmt; } /** * Starts managing the given (unmanaged) app, using the given management context. * * @see #startManagement(Entity) */ public static ManagementContext startManagement(Application app, ManagementContext mgmt) { if (isManaged(app)) { throw new IllegalStateException("Application "+app+" is already managed, so can't set brooklyn properties"); } mgmt.getEntityManager().manage(app); return mgmt; } /** * Starts managing the given (unmanaged) app, setting the given brooklyn properties on the new * management context. * * @see #startManagement(Entity) */ public static ManagementContext startManagement(Application app, BrooklynProperties props) { if (isManaged(app)) { throw new IllegalStateException("Application "+app+" is already managed, so can't set brooklyn properties"); } ManagementContext mgmt = new LocalManagementContext(props); mgmt.getEntityManager().manage(app); return mgmt; } public static ManagementContext newManagementContext() { return new LocalManagementContext(); } public static ManagementContext newManagementContext(BrooklynProperties props) { return new LocalManagementContext(props); } public static ManagementContext newManagementContext(Map<?,?> props) { return new LocalManagementContext( BrooklynProperties.Factory.newEmpty().addFromMap(props)); } public static void unmanage(Entity entity) { if (((EntityInternal)entity).getManagementSupport().isDeployed()) { ((EntityInternal)entity).getManagementContext().getEntityManager().unmanage(entity); } } public static DownloadResolver newDownloader(EntityDriver driver) { return newDownloader(driver, ImmutableMap.<String,Object>of()); } public static DownloadResolver newDownloader(EntityDriver driver, Map<String,?> properties) { EntityInternal internal = (EntityInternal) driver.getEntity(); return internal.getManagementContext().getEntityDownloadsManager().newDownloader(driver, properties); } public static <T> Supplier<T> attributeSupplier(final Entity entity, final AttributeSensor<T> sensor) { return new Supplier<T>() { public T get() { return entity.getAttribute(sensor); } }; } public static <T> Supplier<T> attributeSupplier(final EntityAndAttribute<T> tuple) { return Entities.attributeSupplier(tuple.getEntity(), tuple.getAttribute()); } public static <T> Supplier<T> attributeSupplierWhenReady(final EntityAndAttribute<T> tuple) { return attributeSupplierWhenReady(tuple.getEntity(), tuple.getAttribute()); } @SuppressWarnings({ "unchecked", "serial" }) public static <T> Supplier<T> attributeSupplierWhenReady(final Entity entity, final AttributeSensor<T> sensor) { final Task<T> task = DependentConfiguration.attributeWhenReady(entity, sensor); return new Supplier<T>() { @Override public T get() { try { TypeToken<T> type = new TypeToken<T>(sensor.getType()) {}; return Tasks.resolveValue(task, (Class<T>) type.getRawType(), ((EntityInternal) entity).getExecutionContext(), "attributeSupplierWhenReady"); } catch (Exception e) { throw Exceptions.propagate(e); } } }; } public static void manage(Location loc, ManagementContext managementContext) { if (!managementContext.getLocationManager().isManaged(loc)) { log.warn("Deprecated use of unmanaged location ("+loc+"); will be managed automatically now but not supported in future versions"); // FIXME this occurs MOST OF THE TIME e.g. including BrooklynLauncher.location(locationString) // not sure what is the recommend way to convert from locationString to locationSpec, or the API we want to expose; // deprecating some of the LocationRegistry methods seems sensible? log.debug("Stack trace for location of: Deprecated use of unmanaged location; will be managed automatically now but not supported in future versions", new Exception("TRACE for: Deprecated use of unmanaged location")); managementContext.getLocationManager().manage(loc); } } /** fails-fast if value of the given key is null or unresolveable */ public static String getRequiredUrlConfig(Entity entity, ConfigKey<String> urlKey) { String url = entity.getConfig(urlKey); Preconditions.checkNotNull(url, "Key %s on %s should not be null", urlKey, entity); return ResourceUtils.create(entity).checkUrlExists(url); } /** as {@link #getRequiredUrlConfig(Entity, ConfigKey)} */ public static String getRequiredUrlConfig(Entity entity, HasConfigKey<String> urlKey) { return getRequiredUrlConfig(entity, urlKey.getConfigKey()); } /** submits a task factory to construct its task at the entity (in a precursor task) and then to submit it; * important if e.g. task construction relies on an entity being in scope (in tags, via {@link BrooklynTasks}) */ public static <T extends TaskAdaptable<?>> T submit(final Entity entity, final TaskFactory<T> taskFactory) { // TODO it is messy to have to do this, but not sure there is a cleaner way :( final Semaphore s = new Semaphore(0); final AtomicReference<T> result = new AtomicReference<T>(); final ExecutionContext executionContext = ((EntityInternal)entity).getManagementSupport().getExecutionContext(); executionContext.execute(new Runnable() { // TODO could give this task a name, like "create task from factory" @Override public void run() { T t = taskFactory.newTask(); result.set(t); s.release(); } }); try { s.acquire(); } catch (InterruptedException e) { throw Exceptions.propagate(e); } executionContext.submit(result.get().asTask()); return result.get(); } /** submits a task to run at the entity */ public static <T extends TaskAdaptable<?>> T submit(final Entity entity, final T task) { final ExecutionContext executionContext = ((EntityInternal)entity).getManagementSupport().getExecutionContext(); executionContext.submit(task.asTask()); return task; } /** logs a warning if an entity has a value for a config key */ public static void warnOnIgnoringConfig(Entity entity, ConfigKey<?> key) { if (((EntityInternal)entity).getConfigMap().getRawConfig(key)!=null) log.warn("Ignoring "+key+" set on "+entity+" ("+entity.getConfig(key)+")"); } }
package oshi.demo; import java.awt.BorderLayout; import java.awt.Container; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JMenuBar; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import oshi.SystemInfo; import oshi.demo.gui.Config; import oshi.demo.gui.FileStorePanel; import oshi.demo.gui.InterfacePanel; import oshi.demo.gui.MemoryPanel; import oshi.demo.gui.OsHwTextPanel; import oshi.demo.gui.OshiJPanel; import oshi.demo.gui.ProcessPanel; import oshi.demo.gui.ProcessorPanel; import oshi.demo.gui.UsbPanel; /** * Basic Swing class to demonstrate potential uses for OSHI in a monitoring GUI. * Not ready for production use and intended as inspiration/examples. */ public class OshiGui { private JFrame mainFrame; private JButton jMenu; private JMenuBar menuBar; private SystemInfo si = new SystemInfo(); public static void main(String[] args) { OshiGui gui = new OshiGui(); gui.init(); SwingUtilities.invokeLater(gui::setVisible); } private void setVisible() { mainFrame.setVisible(true); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jMenu.doClick(); } private void init() { // Create the external frame mainFrame = new JFrame(Config.GUI_TITLE); mainFrame.setSize(Config.GUI_WIDTH, Config.GUI_HEIGHT); mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); mainFrame.setResizable(true); mainFrame.setLocationByPlatform(true); mainFrame.setLayout(new BorderLayout()); // Add a menu bar menuBar = new JMenuBar(); mainFrame.setJMenuBar(menuBar); // Assign the first menu option to be clicked on visibility jMenu = getJMenu("OS & HW Info", 'O', "Hardware & OS Summary", new OsHwTextPanel(si)); menuBar.add(jMenu); // Add later menu items menuBar.add(getJMenu("Memory", 'M', "Memory Summary", new MemoryPanel(si))); menuBar.add(getJMenu("CPU", 'C', "CPU Usage", new ProcessorPanel(si))); menuBar.add(getJMenu("FileStores", 'F', "FileStore Usage", new FileStorePanel(si))); menuBar.add(getJMenu("Processes", 'P', "Processes", new ProcessPanel(si))); menuBar.add(getJMenu("USB Devices", 'U', "USB Device list", new UsbPanel(si))); menuBar.add(getJMenu("Network", 'N', "Network Params and Interfaces", new InterfacePanel(si))); } private JButton getJMenu(String title, char mnemonic, String toolTip, OshiJPanel panel) { JButton button = new JButton(title); button.setMnemonic(mnemonic); button.setToolTipText(toolTip); button.addActionListener(e -> { Container contentPane = this.mainFrame.getContentPane(); if (contentPane.getComponents().length <= 0 || contentPane.getComponent(0) != panel) { resetMainGui(); this.mainFrame.getContentPane().add(panel); refreshMainGui(); } }); return button; } private void resetMainGui() { this.mainFrame.getContentPane().removeAll(); } private void refreshMainGui() { this.mainFrame.revalidate(); this.mainFrame.repaint(); } }
package hudson.slaves; import hudson.AbortException; import hudson.Extension; import hudson.ExtensionList; import hudson.ExtensionPoint; import hudson.FilePath; import hudson.model.Computer; import hudson.model.Node; import hudson.model.TaskListener; import org.jenkinsci.remoting.CallableDecorator; import hudson.remoting.Channel; import hudson.remoting.ChannelBuilder; import jenkins.model.Jenkins; import java.io.IOException; /** * Receives notifications about status changes of {@link Computer}s. * * @author Kohsuke Kawaguchi * @since 1.246 */ public abstract class ComputerListener implements ExtensionPoint { /** * Called before {@link Channel} is constructed to provide opportunities to affect the way the channel is run. * * <p> * Among other things, this is useful to add {@link CallableDecorator}s. * * @since 1.THU */ public void onChannelBuilding(ChannelBuilder builder, SlaveComputer sc) {} /** * Called before a {@link ComputerLauncher} is asked to launch a connection with {@link Computer}. * * <p> * This enables you to do some configurable checks to see if we * want to bring this slave online or if there are considerations * that would keep us from doing so. * * <p> * Throwing {@link AbortException} would let you veto the launch operation. Other thrown exceptions * will also have the same effect, but their stack trace will be dumped, so they are meant for error situation. * * @param c * Computer that's being launched. Never null. * @param taskListener * Connected to the slave console log. Useful for reporting progress/errors on a lengthy operation. * Never null. * @throws AbortException * Exceptions will be recorded to the listener, and * the computer will not become online. * * @since 1.402 */ public void preLaunch(Computer c, TaskListener taskListener) throws IOException, InterruptedException { } /** * Called when a slave attempted to connect via {@link ComputerLauncher} but it failed. * * @param c * Computer that was trying to launch. Never null. * @param taskListener * Connected to the slave console log. Useful for reporting progress/errors on a lengthy operation. * Never null. * * @since 1.402 */ public void onLaunchFailure(Computer c, TaskListener taskListener) throws IOException, InterruptedException { } /** * Called before a {@link Computer} is marked online. * * <p> * This enables you to do some work on all the slaves * as they get connected. Unlike {@link #onOnline(Computer, TaskListener)}, * a failure to carry out this function normally will prevent * a computer from marked as online. * * @param channel * This is the channel object to talk to the slave. * (This is the same object returned by {@link Computer#getChannel()} once * it's connected. * @param root * The directory where this slave stores files. * The same as {@link Node#getRootPath()}, except that method returns * null until the slave is connected. So this parameter is passed explicitly instead. * @param listener * This is connected to the launch log of the computer. * Since this method is called synchronously from the thread * that launches a computer, if this method performs a time-consuming * operation, this listener should be notified of the progress. * This is also a good listener for reporting problems. * * @throws IOException * Exceptions will be recorded to the listener, and * the computer will not become online. * @throws InterruptedException * Exceptions will be recorded to the listener, and * the computer will not become online. * * @since 1.295 * @see #onOnline(Computer, TaskListener) */ public void preOnline(Computer c, Channel channel, FilePath root, TaskListener listener) throws IOException, InterruptedException { } /** * Called right after a {@link Computer} comes online. * * @deprecated as of 1.292 * Use {@link #onOnline(Computer, TaskListener)} */ public void onOnline(Computer c) {} /** * Called right after a {@link Computer} comes online. * * <p> * This enables you to do some work on all the slaves * as they get connected. * * <p> * Starting Hudson 1.312, this method is also invoked for the master, not just for slaves. * * @param listener * This is connected to the launch log of the computer. * Since this method is called synchronously from the thread * that launches a computer, if this method performs a time-consuming * operation, this listener should be notified of the progress. * This is also a good listener for reporting problems. * * @throws IOException * Exceptions will be recorded to the listener. Note that * throwing an exception doesn't put the computer offline. * @throws InterruptedException * Exceptions will be recorded to the listener. Note that * throwing an exception doesn't put the computer offline. * * @see #preOnline(Computer, Channel, FilePath, TaskListener) */ public void onOnline(Computer c, TaskListener listener) throws IOException, InterruptedException { // compatibility onOnline(c); } /** * Called right after a {@link Computer} went offline. */ public void onOffline(Computer c) {} /** * Indicates that the computer was marked as temporarily online by the administrator. * This is the reverse operation of {@link #onTemporarilyOffline(Computer, OfflineCause)} * * @since 1.452 */ public void onTemporarilyOnline(Computer c) {} /** * Indicates that the computer was marked as temporarily offline by the administrator. * This is the reverse operation of {@link #onTemporarilyOnline(Computer)} * * @since 1.452 */ public void onTemporarilyOffline(Computer c, OfflineCause cause) {} /** * Called when configuration of the node was changed, a node is added/removed, etc. * * <p> * This callback is to signal when there's any change to the list of slaves registered to the system, * including addition, removal, changing of the setting, and so on. * * @since 1.377 */ public void onConfigurationChange() {} /** * Registers this {@link ComputerListener} so that it will start receiving events. * * @deprecated as of 1.286 * put {@link Extension} on your class to have it auto-registered. */ public final void register() { all().add(this); } /** * Unregisters this {@link ComputerListener} so that it will never receive further events. * * <p> * Unless {@link ComputerListener} is unregistered, it will never be a subject of GC. */ public final boolean unregister() { return all().remove(this); } /** * All the registered {@link ComputerListener}s. */ public static ExtensionList<ComputerListener> all() { return Jenkins.getInstance().getExtensionList(ComputerListener.class); } }
package org.nusco.narjillos; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.nusco.narjillos.creature.genetics.Creature; import org.nusco.narjillos.creature.genetics.DNA; import org.nusco.narjillos.ecosystem.WaterDrop; import org.nusco.narjillos.ecosystem.Ecosystem; import org.nusco.narjillos.shared.physics.Vector; import org.nusco.narjillos.shared.utilities.Chronometer; import org.nusco.narjillos.shared.utilities.NumberFormat; import org.nusco.narjillos.shared.utilities.RanGen; public class Experiment { private static final int PARSE_INTERVAL = 10000; private final Ecosystem ecosystem; private final Chronometer ticksChronometer = new Chronometer(); private final long startTime = System.currentTimeMillis(); // arguments: [<git_commit>, <random_seed | dna_file | dna_document>] public Experiment(String... args) { LinkedList<String> argumentsList = toList(args); String gitCommit = (argumentsList.isEmpty()) ? "UNKNOWN_COMMIT" : argumentsList.removeFirst(); int seed = extractSeed(argumentsList); System.out.println("Experiment " + gitCommit + ":" + seed); RanGen.seed(seed); ecosystem = extractEcosystem(argumentsList); System.out.println(getHeadersString()); } private LinkedList<String> toList(String... args) { LinkedList<String> result = new LinkedList<>(); for (int i = 0; i < args.length; i++) result.add(args[i]); return result; } private int extractSeed(LinkedList<String> argumentsList) { if (argumentsList.isEmpty() || !isInteger(argumentsList.getFirst())) { System.out.print("Randomizing seed... "); return Math.abs(new Random().nextInt()); } return Integer.parseInt(argumentsList.removeFirst()); } private Ecosystem extractEcosystem(LinkedList<String> argumentsList) { if (argumentsList.isEmpty()) return new WaterDrop(); if(argumentsList.getFirst().endsWith(".nrj")) return new WaterDrop(readDNAFromFile(argumentsList.removeFirst())); return new WaterDrop(new DNA(argumentsList.removeFirst())); } private boolean isInteger(String argument) { try { Integer.parseInt(argument); return true; } catch (NumberFormatException e) { return false; } } private static DNA readDNAFromFile(String file) { try { List<String> lines = Files.readAllLines(Paths.get(file)); StringBuffer result = new StringBuffer(); for (String line : lines) result.append(line + "\n"); return new DNA(result.toString()); } catch (IOException e) { throw new RuntimeException(e); } } public boolean tick() { reportStatus(); getEcosystem().tick(); ticksChronometer.tick(); return areThereSurvivors(); } public Ecosystem getEcosystem() { return ecosystem; } public Chronometer getTicksChronometer() { return ticksChronometer; } private void reportStatus() { long ticks = ticksChronometer.getTotalTicks(); if (ticks % PARSE_INTERVAL != 0) return; System.out.println(getStatusString(ecosystem, ticks)); } private long getTimeElapsed() { long currentTime = System.currentTimeMillis(); long timeInSeconds = (currentTime - startTime) / 1000; return timeInSeconds; } private boolean areThereSurvivors() { if (getEcosystem().getNumberOfNarjillos() > 0) return true; System.out.println("*** Extinction happens. ***"); return false; } private String getHeadersString() { return "\n" + alignLeft("ticks") + alignLeft("time") + alignLeft("tps") + alignLeft("narj") + alignLeft("food") + " most_typical_dna"; } private String getStatusString(Ecosystem ecosystem, long tick) { return getStatusString(ecosystem, tick, getMostTypicalSpecimen(ecosystem)); } private Creature getMostTypicalSpecimen(Ecosystem ecosystem) { Creature mostTypicalSpecimen = ecosystem.getPopulation().getMostTypicalSpecimen(); if (mostTypicalSpecimen == null) return getNullCreature(); return mostTypicalSpecimen; } private String getStatusString(Ecosystem ecosystem, long tick, Creature mostTypicalSpecimen) { return alignLeft(NumberFormat.format(tick)) + alignLeft(NumberFormat.format(getTimeElapsed())) + alignLeft(ticksChronometer.getTicksInLastSecond()) + alignLeft(ecosystem.getNumberOfNarjillos()) + alignLeft(ecosystem.getNumberOfFoodPieces()) + " " + mostTypicalSpecimen.getDNA(); } private String alignLeft(Object label) { final String padding = " "; String paddedLabel = padding + label.toString(); return paddedLabel.substring(paddedLabel.length() - padding.length()); } private Creature getNullCreature() { return new Creature() { @Override public void tick() { } @Override public DNA getDNA() { return new DNA("{0_0_0_0}"); } @Override public Vector getPosition() { return Vector.ZERO; } @Override public String getLabel() { return "nobody"; } }; } public static void main(String... args) { final long CYCLES = 100_000_000; Experiment experiment = new Experiment(args); boolean finished = false; while (!finished && experiment.getTicksChronometer().getTotalTicks() < CYCLES) finished = !experiment.tick(); System.out.println("*** The experiment is over at tick " + NumberFormat.format(CYCLES) + " (" + experiment.getTimeElapsed() + "s) ***"); } }
package net.fortuna.ical4j.model.component; import java.io.FileInputStream; import java.io.IOException; import java.net.SocketException; import java.text.ParseException; import java.util.Calendar; import java.util.Iterator; import net.fortuna.ical4j.data.CalendarBuilder; import net.fortuna.ical4j.data.ParserException; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.ComponentTest; import net.fortuna.ical4j.model.Date; import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.Dur; import net.fortuna.ical4j.model.ParameterList; import net.fortuna.ical4j.model.Period; import net.fortuna.ical4j.model.PeriodList; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.PropertyList; import net.fortuna.ical4j.model.Recur; import net.fortuna.ical4j.model.TimeZone; import net.fortuna.ical4j.model.TimeZoneRegistry; import net.fortuna.ical4j.model.TimeZoneRegistryFactory; import net.fortuna.ical4j.model.ValidationException; import net.fortuna.ical4j.model.WeekDay; import net.fortuna.ical4j.model.parameter.TzId; import net.fortuna.ical4j.model.parameter.Value; import net.fortuna.ical4j.model.property.DtEnd; import net.fortuna.ical4j.model.property.DtStart; import net.fortuna.ical4j.model.property.ExDate; import net.fortuna.ical4j.model.property.RRule; import net.fortuna.ical4j.model.property.Summary; import net.fortuna.ical4j.model.property.Uid; import net.fortuna.ical4j.util.Calendars; import net.fortuna.ical4j.util.CompatibilityHints; import net.fortuna.ical4j.util.UidGenerator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A test case for VEvents. * @author Ben Fortuna */ public class VEventTest extends ComponentTest { private static Log log = LogFactory.getLog(VEventTest.class); private TimeZoneRegistry registry; private VTimeZone tz; private TzId tzParam; private VEvent weekdayNineToFiveEvents = null; private VEvent dailyWeekdayEvents = null; private VEvent monthlyWeekdayEvents = null; public void setUp() throws Exception { super.setUp(); // relax validation to avoid UID requirement.. CompatibilityHints.setHintEnabled( CompatibilityHints.KEY_RELAXED_VALIDATION, true); registry = TimeZoneRegistryFactory.getInstance().createRegistry(); // create timezone property.. tz = registry.getTimeZone("Australia/Melbourne").getVTimeZone(); // create tzid parameter.. tzParam = new TzId(tz.getProperty(Property.TZID).getValue()); Calendar weekday9AM = getCalendarInstance(); weekday9AM.set(2005, Calendar.MARCH, 7, 9, 0, 0); weekday9AM.set(Calendar.MILLISECOND, 0); Calendar weekday5PM = getCalendarInstance(); weekday5PM.set(2005, Calendar.MARCH, 7, 17, 0, 0); weekday5PM.set(Calendar.MILLISECOND, 0); // Do the recurrence until December 31st. Calendar untilCal = getCalendarInstance(); untilCal.set(2005, Calendar.DECEMBER, 31); untilCal.set(Calendar.MILLISECOND, 0); Date until = new Date(untilCal.getTime().getTime()); // 9:00AM to 5:00PM Rule using weekly Recur recurWeekly = new Recur(Recur.WEEKLY, until); recurWeekly.getDayList().add(WeekDay.MO); recurWeekly.getDayList().add(WeekDay.TU); recurWeekly.getDayList().add(WeekDay.WE); recurWeekly.getDayList().add(WeekDay.TH); recurWeekly.getDayList().add(WeekDay.FR); recurWeekly.setInterval(1); recurWeekly.setWeekStartDay(WeekDay.MO.getDay()); RRule rruleWeekly = new RRule(recurWeekly); // 9:00AM to 5:00PM Rule using daily frequency Recur recurDaily = new Recur(Recur.DAILY, until); recurDaily.getDayList().add(WeekDay.MO); recurDaily.getDayList().add(WeekDay.TU); recurDaily.getDayList().add(WeekDay.WE); recurDaily.getDayList().add(WeekDay.TH); recurDaily.getDayList().add(WeekDay.FR); recurDaily.setInterval(1); recurDaily.setWeekStartDay(WeekDay.MO.getDay()); RRule rruleDaily = new RRule(recurDaily); // 9:00AM to 5:00PM Rule using monthly frequency Recur recurMonthly = new Recur(Recur.MONTHLY, until); recurMonthly.getDayList().add(WeekDay.MO); recurMonthly.getDayList().add(WeekDay.TU); recurMonthly.getDayList().add(WeekDay.WE); recurMonthly.getDayList().add(WeekDay.TH); recurMonthly.getDayList().add(WeekDay.FR); recurMonthly.setInterval(1); recurMonthly.setWeekStartDay(WeekDay.MO.getDay()); RRule rruleMonthly = new RRule(recurMonthly); Summary summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI DEFINED WEEKLY"); weekdayNineToFiveEvents = new VEvent(); weekdayNineToFiveEvents.getProperties().add(rruleWeekly); weekdayNineToFiveEvents.getProperties().add(summary); DtStart dtStart = new DtStart(new DateTime(weekday9AM.getTime().getTime())); // dtStart.getParameters().add(Value.DATE); weekdayNineToFiveEvents.getProperties().add(dtStart); DtEnd dtEnd = new DtEnd(new DateTime(weekday5PM.getTime().getTime())); // dtEnd.getParameters().add(Value.DATE); weekdayNineToFiveEvents.getProperties().add(dtEnd); weekdayNineToFiveEvents.getProperties().add(new Uid("000001@modularity.net.au")); // ensure event is valid.. weekdayNineToFiveEvents.validate(); summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI DEFINED DAILY"); dailyWeekdayEvents = new VEvent(); dailyWeekdayEvents.getProperties().add(rruleDaily); dailyWeekdayEvents.getProperties().add(summary); DtStart dtStart2 = new DtStart(new DateTime(weekday9AM.getTime().getTime())); // dtStart2.getParameters().add(Value.DATE); dailyWeekdayEvents.getProperties().add(dtStart2); DtEnd dtEnd2 = new DtEnd(new DateTime(weekday5PM.getTime().getTime())); // dtEnd2.getParameters().add(Value.DATE); dailyWeekdayEvents.getProperties().add(dtEnd2); dailyWeekdayEvents.getProperties().add(new Uid("000002@modularity.net.au")); // ensure event is valid.. dailyWeekdayEvents.validate(); summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI DEFINED MONTHLY"); monthlyWeekdayEvents = new VEvent(); monthlyWeekdayEvents.getProperties().add(rruleMonthly); monthlyWeekdayEvents.getProperties().add(summary); DtStart dtStart3 = new DtStart(new DateTime(weekday9AM.getTime().getTime())); // dtStart3.getParameters().add(Value.DATE); monthlyWeekdayEvents.getProperties().add(dtStart3); DtEnd dtEnd3 = new DtEnd(new DateTime(weekday5PM.getTime().getTime())); // dtEnd3.getParameters().add(Value.DATE); monthlyWeekdayEvents.getProperties().add(dtEnd3); monthlyWeekdayEvents.getProperties().add(new Uid("000003@modularity.net.au")); // ensure event is valid.. monthlyWeekdayEvents.validate(); } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { // relax validation to avoid UID requirement.. CompatibilityHints.setHintEnabled( CompatibilityHints.KEY_RELAXED_VALIDATION, false); super.tearDown(); } /** * @return */ private Calendar getCalendarInstance() { return Calendar.getInstance(); //java.util.TimeZone.getTimeZone(TimeZones.GMT_ID)); } /** * @param filename * @return */ private net.fortuna.ical4j.model.Calendar loadCalendar(String filename) throws IOException, ParserException, ValidationException { net.fortuna.ical4j.model.Calendar calendar = Calendars.load( filename); calendar.validate(); log.info("File: " + filename); if (log.isDebugEnabled()) { log.debug("Calendar:\n=========\n" + calendar.toString()); } return calendar; } public final void testChristmas() { // create event start date.. java.util.Calendar calendar = getCalendarInstance(); calendar.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER); calendar.set(java.util.Calendar.DAY_OF_MONTH, 25); DtStart start = new DtStart(new Date(calendar.getTime())); start.getParameters().add(tzParam); start.getParameters().add(Value.DATE); Summary summary = new Summary("Christmas Day; \n this is a, test\\"); VEvent christmas = new VEvent(); christmas.getProperties().add(start); christmas.getProperties().add(summary); log.info(christmas); } /** * Test creating an event with an associated timezone. */ public final void testMelbourneCup() { TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry(); TimeZone timezone = registry.getTimeZone("Australia/Melbourne"); java.util.Calendar cal = java.util.Calendar.getInstance(timezone); cal.set(java.util.Calendar.YEAR, 2005); cal.set(java.util.Calendar.MONTH, java.util.Calendar.NOVEMBER); cal.set(java.util.Calendar.DAY_OF_MONTH, 1); cal.set(java.util.Calendar.HOUR_OF_DAY, 15); cal.clear(java.util.Calendar.MINUTE); cal.clear(java.util.Calendar.SECOND); DateTime dt = new DateTime(cal.getTime()); dt.setTimeZone(timezone); VEvent melbourneCup = new VEvent(dt, "Melbourne Cup"); log.info(melbourneCup); } public final void test2() { java.util.Calendar cal = getCalendarInstance(); cal.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER); cal.set(java.util.Calendar.DAY_OF_MONTH, 25); VEvent christmas = new VEvent(new Date(cal.getTime()), "Christmas Day"); // initialise as an all-day event.. christmas.getProperty(Property.DTSTART).getParameters().add(Value.DATE); // add timezone information.. christmas.getProperty(Property.DTSTART).getParameters().add(tzParam); log.info(christmas); } public final void test3() { java.util.Calendar cal = getCalendarInstance(); // tomorrow.. cal.add(java.util.Calendar.DAY_OF_MONTH, 1); cal.set(java.util.Calendar.HOUR_OF_DAY, 9); cal.set(java.util.Calendar.MINUTE, 30); VEvent meeting = new VEvent(new DateTime(cal.getTime().getTime()), new Dur(0, 1, 0, 0), "Progress Meeting"); // add timezone information.. meeting.getProperty(Property.DTSTART).getParameters().add(tzParam); log.info(meeting); } /** * Test Null Dates * Test Start today, End One month from now. * * @throws Exception */ public final void testGetConsumedTime() throws Exception { // Test Null Dates try { weekdayNineToFiveEvents.getConsumedTime(null, null); fail("Should've thrown an exception."); } catch (RuntimeException re) { log.info("Expecting an exception here."); } // Test Start 04/01/2005, End One month later. // Query Calendar Start and End Dates. Calendar queryStartDate = getCalendarInstance(); queryStartDate.set(2005, Calendar.APRIL, 1, 14, 47, 0); queryStartDate.set(Calendar.MILLISECOND, 0); DateTime queryStart = new DateTime(queryStartDate.getTime().getTime()); Calendar queryEndDate = getCalendarInstance(); queryEndDate.set(2005, Calendar.MAY, 1, 07, 15, 0); queryEndDate.set(Calendar.MILLISECOND, 0); DateTime queryEnd = new DateTime(queryEndDate.getTime().getTime()); Calendar week1EndDate = getCalendarInstance(); week1EndDate.set(2005, Calendar.APRIL, 8, 11, 15, 0); week1EndDate.set(Calendar.MILLISECOND, 0); Calendar week4StartDate = getCalendarInstance(); week4StartDate.set(2005, Calendar.APRIL, 24, 14, 47, 0); week4StartDate.set(Calendar.MILLISECOND, 0); DateTime week4Start = new DateTime(week4StartDate.getTime().getTime()); // This range is monday to friday every three weeks, starting from // March 7th 2005, which means for our query dates we need // April 18th through to the 22nd. PeriodList weeklyPeriods = weekdayNineToFiveEvents.getConsumedTime(queryStart, queryEnd); PeriodList dailyPeriods = dailyWeekdayEvents.getConsumedTime(queryStart, queryEnd); // week1EndDate.getTime()); dailyPeriods.addAll(dailyWeekdayEvents.getConsumedTime(week4Start, queryEnd)); Calendar expectedCal = Calendar.getInstance(); //TimeZone.getTimeZone(TimeZones.GMT_ID)); expectedCal.set(2005, Calendar.APRIL, 1, 9, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedStartOfFirstRange = new DateTime(expectedCal.getTime().getTime()); expectedCal.set(2005, Calendar.APRIL, 1, 17, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedEndOfFirstRange = new DateTime(expectedCal.getTime().getTime()); assertNotNull(weeklyPeriods); assertTrue(weeklyPeriods.size() > 0); Period firstPeriod = (Period) weeklyPeriods.toArray()[0]; assertEquals(expectedStartOfFirstRange, firstPeriod.getStart()); assertEquals(expectedEndOfFirstRange, firstPeriod.getEnd()); assertEquals(dailyPeriods, weeklyPeriods); } public final void testGetConsumedTimeDaily() throws Exception { // Test Starts 04/03/2005, Ends One week later. // Query Calendar Start and End Dates. Calendar queryStartDate = getCalendarInstance(); queryStartDate.set(2005, Calendar.APRIL, 3, 05, 12, 0); queryStartDate.set(Calendar.MILLISECOND, 0); Calendar queryEndDate = getCalendarInstance(); queryEndDate.set(2005, Calendar.APRIL, 10, 21, 55, 0); queryEndDate.set(Calendar.MILLISECOND, 0); // This range is Monday to Friday every day (which has a filtering // effect), starting from March 7th 2005. Our query dates are // April 3rd through to the 10th. PeriodList weeklyPeriods = weekdayNineToFiveEvents.getConsumedTime(new DateTime(queryStartDate.getTime()), new DateTime(queryEndDate.getTime())); PeriodList dailyPeriods = dailyWeekdayEvents.getConsumedTime(new DateTime(queryStartDate.getTime()), new DateTime(queryEndDate.getTime())); Calendar expectedCal = getCalendarInstance(); expectedCal.set(2005, Calendar.APRIL, 4, 9, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedStartOfFirstRange = new DateTime(expectedCal.getTime()); expectedCal.set(2005, Calendar.APRIL, 4, 17, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedEndOfFirstRange = new DateTime(expectedCal.getTime()); assertNotNull(dailyPeriods); assertTrue(dailyPeriods.size() > 0); Period firstPeriod = (Period) dailyPeriods.toArray()[0]; assertEquals(expectedStartOfFirstRange, firstPeriod.getStart()); assertEquals(expectedEndOfFirstRange, firstPeriod.getEnd()); assertEquals(weeklyPeriods, dailyPeriods); } /** * Test whether you can select weekdays using a monthly frequency. * <p> * This test really belongs in RecurTest, but the weekly range test * in this VEventTest matches so perfectly with the daily range test * that should produce the same results for some weeks that it was * felt leveraging the existing test code was more important. * <p> * Section 4.3.10 of the iCalendar specification RFC 2445 reads: * <pre> * If an integer modifier is not present, it means all days of * this type within the specified frequency. * </pre> * This test ensures compliance. */ public final void testGetConsumedTimeMonthly() throws Exception { // Test Starts 04/03/2005, Ends two weeks later. // Query Calendar Start and End Dates. Calendar queryStartDate = getCalendarInstance(); queryStartDate.set(2005, Calendar.APRIL, 3, 05, 12, 0); queryStartDate.set(Calendar.MILLISECOND, 0); Calendar queryEndDate = getCalendarInstance(); queryEndDate.set(2005, Calendar.APRIL, 17, 21, 55, 0); queryEndDate.set(Calendar.MILLISECOND, 0); // This range is Monday to Friday every month (which has a multiplying // effect), starting from March 7th 2005. Our query dates are // April 3rd through to the 17th. PeriodList monthlyPeriods = monthlyWeekdayEvents.getConsumedTime(new DateTime(queryStartDate.getTime()), new DateTime(queryEndDate.getTime())); PeriodList dailyPeriods = dailyWeekdayEvents.getConsumedTime(new DateTime(queryStartDate.getTime()), new DateTime(queryEndDate.getTime())); Calendar expectedCal = getCalendarInstance(); expectedCal.set(2005, Calendar.APRIL, 4, 9, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedStartOfFirstRange = new DateTime(expectedCal.getTime()); expectedCal.set(2005, Calendar.APRIL, 4, 17, 0, 0); expectedCal.set(Calendar.MILLISECOND, 0); Date expectedEndOfFirstRange = new DateTime(expectedCal.getTime()); assertNotNull(monthlyPeriods); assertTrue(monthlyPeriods.size() > 0); Period firstPeriod = (Period) monthlyPeriods.toArray()[0]; assertEquals(expectedStartOfFirstRange, firstPeriod.getStart()); assertEquals(expectedEndOfFirstRange, firstPeriod.getEnd()); assertEquals(dailyPeriods, monthlyPeriods); } public final void testGetConsumedTime2() throws Exception { String filename = "etc/samples/valid/derryn.ics"; net.fortuna.ical4j.model.Calendar calendar = loadCalendar(filename); Date start = new Date(); Calendar endCal = getCalendarInstance(); endCal.setTime(start); endCal.add(Calendar.WEEK_OF_YEAR, 4); // Date end = new Date(start.getTime() + (1000 * 60 * 60 * 24 * 7 * 4)); for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) { Component c = (Component) i.next(); if (c instanceof VEvent) { PeriodList consumed = ((VEvent) c).getConsumedTime(start, new Date(endCal.getTime().getTime())); log.debug("Event [" + c + "]"); log.debug("Consumed time [" + consumed + "]"); } } } public final void testGetConsumedTime3() throws Exception { String filename = "etc/samples/valid/calconnect10.ics"; net.fortuna.ical4j.model.Calendar calendar = loadCalendar(filename); VEvent vev = (VEvent) calendar.getComponent(Component.VEVENT); Date start = vev.getStartDate().getDate(); Calendar cal = getCalendarInstance(); cal.add(Calendar.YEAR, 1); Date latest = new Date(cal.getTime()); PeriodList pl = vev.getConsumedTime(start, latest); assertTrue(!pl.isEmpty()); } /** * Test COUNT rules. */ public void testGetConsumeTimeByCount() { Recur recur = new Recur(Recur.WEEKLY, 3); recur.setInterval(1); recur.getDayList().add(WeekDay.SU); log.info(recur); Calendar cal = getCalendarInstance(); cal.set(Calendar.DAY_OF_MONTH, 8); Date start = new DateTime(cal.getTime()); // cal.add(Calendar.DAY_OF_WEEK_IN_MONTH, 10); cal.add(Calendar.HOUR_OF_DAY, 1); Date end = new DateTime(cal.getTime()); // log.info(recur.getDates(start, end, Value.DATE_TIME)); RRule rrule = new RRule(recur); VEvent event = new VEvent(start, end, "Test recurrence COUNT"); event.getProperties().add(rrule); log.info(event); Calendar rangeCal = getCalendarInstance(); Date rangeStart = new DateTime(rangeCal.getTime()); rangeCal.add(Calendar.WEEK_OF_YEAR, 4); Date rangeEnd = new DateTime(rangeCal.getTime()); log.info(event.getConsumedTime(rangeStart, rangeEnd)); } /** * A test to confirm that the end date is calculated correctly * from a given start date and duration. */ public final void testEventEndDate() { Calendar cal = getCalendarInstance(); Date startDate = new Date(cal.getTime()); log.info("Start date: " + startDate); VEvent event = new VEvent(startDate, new Dur(3, 0, 0, 0), "3 day event"); Date endDate = event.getEndDate().getDate(); log.info("End date: " + endDate); cal.add(Calendar.DAY_OF_YEAR, 3); assertEquals(new Date(cal.getTime()), endDate); } /** * Test to ensure that EXDATE properties are correctly applied. * @throws ParseException */ public void testGetConsumedTimeWithExDate() throws ParseException { VEvent event1 = new VEvent(new DateTime("20050103T080000"), new Dur(0, 0, 15, 0), "Event 1"); Recur rRuleRecur = new Recur("FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,TU,WE,TH,FR"); RRule rRule = new RRule(rRuleRecur); event1.getProperties().add(rRule); ParameterList parameterList = new ParameterList(); parameterList.add(Value.DATE); ExDate exDate = new ExDate(parameterList, "20050106"); event1.getProperties().add(exDate); Date start = new Date("20050106"); Date end = new Date("20050107"); PeriodList list = event1.getConsumedTime(start, end); assertTrue(list.isEmpty()); } /** * Test to ensure that EXDATE properties are correctly applied. * @throws ParseException */ public void testGetConsumedTimeWithExDate2() throws IOException, ParserException { FileInputStream fin = new FileInputStream("etc/samples/valid/friday13.ics"); net.fortuna.ical4j.model.Calendar calendar = new CalendarBuilder().build(fin); VEvent event = (VEvent) calendar.getComponent(Component.VEVENT); Calendar cal = Calendar.getInstance(); cal.set(1997, 8, 2); Date start = new Date(cal.getTime()); cal.set(1997, 8, 4); Date end = new Date(cal.getTime()); PeriodList periods = event.getConsumedTime(start, end); assertTrue(periods.isEmpty()); } /* (non-Javadoc) * @see net.fortuna.ical4j.model.ComponentTest#testIsCalendarComponent() */ public void testIsCalendarComponent() { assertIsCalendarComponent(new VEvent()); } /** * Test equality of events with different alarm sub-components. */ public void testEquals() { Date date = new Date(); String summary = "test event"; PropertyList props = new PropertyList(); props.add(new DtStart(date)); props.add(new Summary(summary)); VEvent e1 = new VEvent(props); VEvent e2 = new VEvent(props); assertTrue(e1.equals(e2)); e2.getAlarms().add(new VAlarm()); assertFalse(e1.equals(e2)); } /** * Test VEvent validation. */ public void testValidation() throws SocketException, ValidationException { UidGenerator ug = new UidGenerator("1"); Uid uid = ug.generateUid(); DtStart start = new DtStart(); DtEnd end = new DtEnd(); VEvent event = new VEvent(); event.getProperties().add(uid); event.getProperties().add(start); event.getProperties().add(end); event.validate(); start.getParameters().replace(Value.DATE_TIME); event.validate(); start.getParameters().remove(Value.DATE_TIME); end.getParameters().replace(Value.DATE_TIME); event.validate(); // test 1.. start.getParameters().replace(Value.DATE); try { event.validate(); } catch (ValidationException ve) { log.info("Caught exception: [" + ve.getMessage() + "]"); } // test 2.. start.getParameters().replace(Value.DATE_TIME); end.getParameters().replace(Value.DATE); try { event.validate(); } catch (ValidationException ve) { log.info("Caught exception: [" + ve.getMessage() + "]"); } // test 3.. start.getParameters().replace(Value.DATE); end.getParameters().replace(Value.DATE_TIME); try { event.validate(); } catch (ValidationException ve) { log.info("Caught exception: [" + ve.getMessage() + "]"); } // test 3.. start.getParameters().remove(Value.DATE); end.getParameters().replace(Value.DATE); try { event.validate(); } catch (ValidationException ve) { log.info("Caught exception: [" + ve.getMessage() + "]"); } } /** * Unit tests for {@link Component#calculateRecurrenceSet(Period)}. */ public void testCalculateRecurrenceSet() throws ParseException, ValidationException { DateTime periodStart = new DateTime("20050101T000000"); DateTime periodEnd = new DateTime("20051231T235959"); Period period = new Period(periodStart, periodEnd); PeriodList recurrenceSet = weekdayNineToFiveEvents.calculateRecurrenceSet(period); assertTrue(!recurrenceSet.isEmpty()); } }
package org.bouncycastle.crypto.test; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.engines.RSABlindingEngine; import org.bouncycastle.crypto.engines.RSAEngine; import org.bouncycastle.crypto.generators.RSABlindingFactorGenerator; import org.bouncycastle.crypto.generators.RSAKeyPairGenerator; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.params.RSABlindingParameters; import org.bouncycastle.crypto.params.RSAKeyGenerationParameters; import org.bouncycastle.crypto.params.RSAKeyParameters; import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters; import org.bouncycastle.crypto.signers.PSSSigner; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; import java.math.BigInteger; import java.security.SecureRandom; /* * RSA PSS test vectors for PKCS#1 V2.1 with blinding */ public class PSSBlindTest extends SimpleTest { private final int DATA_LENGTH = 1000; private final int NUM_TESTS = 50; private final int NUM_TESTS_WITH_KEY_GENERATION = 10; private class FixedRandom extends SecureRandom { byte[] vals; FixedRandom( byte[] vals) { this.vals = vals; } public void nextBytes( byte[] bytes) { System.arraycopy(vals, 0, bytes, 0, vals.length); } } // Example 1: A 1024-bit RSA keypair private RSAKeyParameters pub1 = new RSAKeyParameters(false, new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16)); private RSAKeyParameters prv1 = new RSAPrivateCrtKeyParameters( new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16), new BigInteger("33a5042a90b27d4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b325",16), new BigInteger("e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e86296b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b3b6dcd3eda8e6443",16), new BigInteger("b69dca1cf7d4d7ec81e75b90fcca874abcde123fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc723e6963364a1f9425452b269a6799fd",16), new BigInteger("28fa13938655be1f8a159cbaca5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8dd3ede2448328f385d81b30e8e43b2fffa027861979",16), new BigInteger("1a8b38f398fa712049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729",16), new BigInteger("27156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24a79f4d",16)); // PSSExample1.1 private byte[] msg1a = Hex.decode("cdc87da223d786df3b45e0bbbc721326d1ee2af806cc315475cc6f0d9c66e1b62371d45ce2392e1ac92844c310102f156a0d8d52c1f4c40ba3aa65095786cb769757a6563ba958fed0bcc984e8b517a3d5f515b23b8a41e74aa867693f90dfb061a6e86dfaaee64472c00e5f20945729cbebe77f06ce78e08f4098fba41f9d6193c0317e8b60d4b6084acb42d29e3808a3bc372d85e331170fcbf7cc72d0b71c296648b3a4d10f416295d0807aa625cab2744fd9ea8fd223c42537029828bd16be02546f130fd2e33b936d2676e08aed1b73318b750a0167d0"); private byte[] slt1a = Hex.decode("dee959c7e06411361420ff80185ed57f3e6776af"); private byte[] sig1a = Hex.decode("9074308fb598e9701b2294388e52f971faac2b60a5145af185df5287b5ed2887e57ce7fd44dc8634e407c8e0e4360bc226f3ec227f9d9e54638e8d31f5051215df6ebb9c2f9579aa77598a38f914b5b9c1bd83c4e2f9f382a0d0aa3542ffee65984a601bc69eb28deb27dca12c82c2d4c3f66cd500f1ff2b994d8a4e30cbb33c"); // PSSExample1.2 private byte[] msg1b = Hex.decode("851384cdfe819c22ed6c4ccb30daeb5cf059bc8e1166b7e3530c4c233e2b5f8f71a1cca582d43ecc72b1bca16dfc7013226b9e"); private byte[] slt1b = Hex.decode("ef2869fa40c346cb183dab3d7bffc98fd56df42d"); private byte[] sig1b = Hex.decode("3ef7f46e831bf92b32274142a585ffcefbdca7b32ae90d10fb0f0c729984f04ef29a9df0780775ce43739b97838390db0a5505e63de927028d9d29b219ca2c4517832558a55d694a6d25b9dab66003c4cccd907802193be5170d26147d37b93590241be51c25055f47ef62752cfbe21418fafe98c22c4d4d47724fdb5669e843"); // Example 2: A 1025-bit RSA keypair private RSAKeyParameters pub2 = new RSAKeyParameters(false, new BigInteger("01d40c1bcf97a68ae7cdbd8a7bf3e34fa19dcca4ef75a47454375f94514d88fed006fb829f8419ff87d6315da68a1ff3a0938e9abb3464011c303ad99199cf0c7c7a8b477dce829e8844f625b115e5e9c4a59cf8f8113b6834336a2fd2689b472cbb5e5cabe674350c59b6c17e176874fb42f8fc3d176a017edc61fd326c4b33c9", 16), new BigInteger("010001", 16)); private RSAKeyParameters prv2 = new RSAPrivateCrtKeyParameters( new BigInteger("01d40c1bcf97a68ae7cdbd8a7bf3e34fa19dcca4ef75a47454375f94514d88fed006fb829f8419ff87d6315da68a1ff3a0938e9abb3464011c303ad99199cf0c7c7a8b477dce829e8844f625b115e5e9c4a59cf8f8113b6834336a2fd2689b472cbb5e5cabe674350c59b6c17e176874fb42f8fc3d176a017edc61fd326c4b33c9", 16), new BigInteger("010001", 16), new BigInteger("027d147e4673057377fd1ea201565772176a7dc38358d376045685a2e787c23c15576bc16b9f444402d6bfc5d98a3e88ea13ef67c353eca0c0ddba9255bd7b8bb50a644afdfd1dd51695b252d22e7318d1b6687a1c10ff75545f3db0fe602d5f2b7f294e3601eab7b9d1cecd767f64692e3e536ca2846cb0c2dd486a39fa75b1", 16), new BigInteger("016601e926a0f8c9e26ecab769ea65a5e7c52cc9e080ef519457c644da6891c5a104d3ea7955929a22e7c68a7af9fcad777c3ccc2b9e3d3650bce404399b7e59d1", 16), new BigInteger("014eafa1d4d0184da7e31f877d1281ddda625664869e8379e67ad3b75eae74a580e9827abd6eb7a002cb5411f5266797768fb8e95ae40e3e8a01f35ff89e56c079", 16), new BigInteger("e247cce504939b8f0a36090de200938755e2444b29539a7da7a902f6056835c0db7b52559497cfe2c61a8086d0213c472c78851800b171f6401de2e9c2756f31", 16), new BigInteger("b12fba757855e586e46f64c38a70c68b3f548d93d787b399999d4c8f0bbd2581c21e19ed0018a6d5d3df86424b3abcad40199d31495b61309f27c1bf55d487c1", 16), new BigInteger("564b1e1fa003bda91e89090425aac05b91da9ee25061e7628d5f51304a84992fdc33762bd378a59f030a334d532bd0dae8f298ea9ed844636ad5fb8cbdc03cad", 16)); // PSS Example 2.1 private byte[] msg2a = Hex.decode("daba032066263faedb659848115278a52c44faa3a76f37515ed336321072c40a9d9b53bc05014078adf520875146aae70ff060226dcb7b1f1fc27e9360"); private byte[] slt2a = Hex.decode("57bf160bcb02bb1dc7280cf0458530b7d2832ff7"); private byte[] sig2a = Hex.decode("014c5ba5338328ccc6e7a90bf1c0ab3fd606ff4796d3c12e4b639ed9136a5fec6c16d8884bdd99cfdc521456b0742b736868cf90de099adb8d5ffd1deff39ba4007ab746cefdb22d7df0e225f54627dc65466131721b90af445363a8358b9f607642f78fab0ab0f43b7168d64bae70d8827848d8ef1e421c5754ddf42c2589b5b3"); // PSS Example 2.2 private byte[] msg2b = Hex.decode("e4f8601a8a6da1be34447c0959c058570c3668cfd51dd5f9ccd6ad4411fe8213486d78a6c49f93efc2ca2288cebc2b9b60bd04b1e220d86e3d4848d709d032d1e8c6a070c6af9a499fcf95354b14ba6127c739de1bb0fd16431e46938aec0cf8ad9eb72e832a7035de9b7807bdc0ed8b68eb0f5ac2216be40ce920c0db0eddd3860ed788efaccaca502d8f2bd6d1a7c1f41ff46f1681c8f1f818e9c4f6d91a0c7803ccc63d76a6544d843e084e363b8acc55aa531733edb5dee5b5196e9f03e8b731b3776428d9e457fe3fbcb3db7274442d785890e9cb0854b6444dace791d7273de1889719338a77fe"); private byte[] slt2b = Hex.decode("7f6dd359e604e60870e898e47b19bf2e5a7b2a90"); private byte[] sig2b = Hex.decode("010991656cca182b7f29d2dbc007e7ae0fec158eb6759cb9c45c5ff87c7635dd46d150882f4de1e9ae65e7f7d9018f6836954a47c0a81a8a6b6f83f2944d6081b1aa7c759b254b2c34b691da67cc0226e20b2f18b42212761dcd4b908a62b371b5918c5742af4b537e296917674fb914194761621cc19a41f6fb953fbcbb649dea"); // Example 4: A 1027-bit RSA key pair private RSAKeyParameters pub4 = new RSAKeyParameters(false, new BigInteger("054adb7886447efe6f57e0368f06cf52b0a3370760d161cef126b91be7f89c421b62a6ec1da3c311d75ed50e0ab5fff3fd338acc3aa8a4e77ee26369acb81ba900fa83f5300cf9bb6c53ad1dc8a178b815db4235a9a9da0c06de4e615ea1277ce559e9c108de58c14a81aa77f5a6f8d1335494498848c8b95940740be7bf7c3705", 16), new BigInteger("010001", 16)); private RSAKeyParameters prv4 = new RSAPrivateCrtKeyParameters( new BigInteger("054adb7886447efe6f57e0368f06cf52b0a3370760d161cef126b91be7f89c421b62a6ec1da3c311d75ed50e0ab5fff3fd338acc3aa8a4e77ee26369acb81ba900fa83f5300cf9bb6c53ad1dc8a178b815db4235a9a9da0c06de4e615ea1277ce559e9c108de58c14a81aa77f5a6f8d1335494498848c8b95940740be7bf7c3705", 16), new BigInteger("010001", 16), new BigInteger("fa041f8cd9697ceed38ec8caa275523b4dd72b09a301d3541d72f5d31c05cbce2d6983b36183af10690bd46c46131e35789431a556771dd0049b57461bf060c1f68472e8a67c25f357e5b6b4738fa541a730346b4a07649a2dfa806a69c975b6aba64678acc7f5913e89c622f2d8abb1e3e32554e39df94ba60c002e387d9011", 16), new BigInteger("029232336d2838945dba9dd7723f4e624a05f7375b927a87abe6a893a1658fd49f47f6c7b0fa596c65fa68a23f0ab432962d18d4343bd6fd671a5ea8d148413995", 16), new BigInteger("020ef5efe7c5394aed2272f7e81a74f4c02d145894cb1b3cab23a9a0710a2afc7e3329acbb743d01f680c4d02afb4c8fde7e20930811bb2b995788b5e872c20bb1", 16), new BigInteger("026e7e28010ecf2412d9523ad704647fb4fe9b66b1a681581b0e15553a89b1542828898f27243ebab45ff5e1acb9d4df1b051fbc62824dbc6f6c93261a78b9a759", 16), new BigInteger("012ddcc86ef655998c39ddae11718669e5e46cf1495b07e13b1014cd69b3af68304ad2a6b64321e78bf3bbca9bb494e91d451717e2d97564c6549465d0205cf421", 16), new BigInteger("010600c4c21847459fe576703e2ebecae8a5094ee63f536bf4ac68d3c13e5e4f12ac5cc10ab6a2d05a199214d1824747d551909636b774c22cac0b837599abcc75", 16)); // PSS Example 4.1 private byte[] msg4a = Hex.decode("9fb03b827c8217d9"); private byte[] slt4a = Hex.decode("ed7c98c95f30974fbe4fbddcf0f28d6021c0e91d"); private byte[] sig4a = Hex.decode("0323d5b7bf20ba4539289ae452ae4297080feff4518423ff4811a817837e7d82f1836cdfab54514ff0887bddeebf40bf99b047abc3ecfa6a37a3ef00f4a0c4a88aae0904b745c846c4107e8797723e8ac810d9e3d95dfa30ff4966f4d75d13768d20857f2b1406f264cfe75e27d7652f4b5ed3575f28a702f8c4ed9cf9b2d44948"); // PSS Example 4.2 private byte[] msg4b = Hex.decode("0ca2ad77797ece86de5bf768750ddb5ed6a3116ad99bbd17edf7f782f0db1cd05b0f677468c5ea420dc116b10e80d110de2b0461ea14a38be68620392e7e893cb4ea9393fb886c20ff790642305bf302003892e54df9f667509dc53920df583f50a3dd61abb6fab75d600377e383e6aca6710eeea27156e06752c94ce25ae99fcbf8592dbe2d7e27453cb44de07100ebb1a2a19811a478adbeab270f94e8fe369d90b3ca612f9f"); private byte[] slt4b = Hex.decode("22d71d54363a4217aa55113f059b3384e3e57e44"); private byte[] sig4b = Hex.decode("049d0185845a264d28feb1e69edaec090609e8e46d93abb38371ce51f4aa65a599bdaaa81d24fba66a08a116cb644f3f1e653d95c89db8bbd5daac2709c8984000178410a7c6aa8667ddc38c741f710ec8665aa9052be929d4e3b16782c1662114c5414bb0353455c392fc28f3db59054b5f365c49e1d156f876ee10cb4fd70598"); // Example 8: A 1031-bit RSA key pair private RSAKeyParameters pub8 = new RSAKeyParameters(false, new BigInteger("495370a1fb18543c16d3631e3163255df62be6eee890d5f25509e4f778a8ea6fbbbcdf85dff64e0d972003ab3681fbba6dd41fd541829b2e582de9f2a4a4e0a2d0900bef4753db3cee0ee06c7dfae8b1d53b5953218f9cceea695b08668edeaadced9463b1d790d5ebf27e9115b46cad4d9a2b8efab0561b0810344739ada0733f", 16), new BigInteger("010001", 16)); private RSAKeyParameters prv8 = new RSAPrivateCrtKeyParameters( new BigInteger("495370a1fb18543c16d3631e3163255df62be6eee890d5f25509e4f778a8ea6fbbbcdf85dff64e0d972003ab3681fbba6dd41fd541829b2e582de9f2a4a4e0a2d0900bef4753db3cee0ee06c7dfae8b1d53b5953218f9cceea695b08668edeaadced9463b1d790d5ebf27e9115b46cad4d9a2b8efab0561b0810344739ada0733f", 16), new BigInteger("010001", 16), new BigInteger("6c66ffe98980c38fcdeab5159898836165f4b4b817c4f6a8d486ee4ea9130fe9b9092bd136d184f95f504a607eac565846d2fdd6597a8967c7396ef95a6eeebb4578a643966dca4d8ee3de842de63279c618159c1ab54a89437b6a6120e4930afb52a4ba6ced8a4947ac64b30a3497cbe701c2d6266d517219ad0ec6d347dbe9", 16), new BigInteger("08dad7f11363faa623d5d6d5e8a319328d82190d7127d2846c439b0ab72619b0a43a95320e4ec34fc3a9cea876422305bd76c5ba7be9e2f410c8060645a1d29edb", 16), new BigInteger("0847e732376fc7900f898ea82eb2b0fc418565fdae62f7d9ec4ce2217b97990dd272db157f99f63c0dcbb9fbacdbd4c4dadb6df67756358ca4174825b48f49706d", 16), new BigInteger("05c2a83c124b3621a2aa57ea2c3efe035eff4560f33ddebb7adab81fce69a0c8c2edc16520dda83d59a23be867963ac65f2cc710bbcfb96ee103deb771d105fd85", 16), new BigInteger("04cae8aa0d9faa165c87b682ec140b8ed3b50b24594b7a3b2c220b3669bb819f984f55310a1ae7823651d4a02e99447972595139363434e5e30a7e7d241551e1b9", 16), new BigInteger("07d3e47bf686600b11ac283ce88dbb3f6051e8efd04680e44c171ef531b80b2b7c39fc766320e2cf15d8d99820e96ff30dc69691839c4b40d7b06e45307dc91f3f", 16)); // PSS Example 8.1 private byte[] msg8a = Hex.decode("81332f4be62948415ea1d899792eeacf6c6e1db1da8be13b5cea41db2fed467092e1ff398914c714259775f595f8547f735692a575e6923af78f22c6997ddb90fb6f72d7bb0dd5744a31decd3dc3685849836ed34aec596304ad11843c4f88489f209735f5fb7fdaf7cec8addc5818168f880acbf490d51005b7a8e84e43e54287977571dd99eea4b161eb2df1f5108f12a4142a83322edb05a75487a3435c9a78ce53ed93bc550857d7a9fb"); private byte[] slt8a = Hex.decode("1d65491d79c864b373009be6f6f2467bac4c78fa"); private byte[] sig8a = Hex.decode("0262ac254bfa77f3c1aca22c5179f8f040422b3c5bafd40a8f21cf0fa5a667ccd5993d42dbafb409c520e25fce2b1ee1e716577f1efa17f3da28052f40f0419b23106d7845aaf01125b698e7a4dfe92d3967bb00c4d0d35ba3552ab9a8b3eef07c7fecdbc5424ac4db1e20cb37d0b2744769940ea907e17fbbca673b20522380c5"); // PSS Example 8.2 private byte[] msg8b = Hex.decode("e2f96eaf0e05e7ba326ecca0ba7fd2f7c02356f3cede9d0faabf4fcc8e60a973e5595fd9ea08"); private byte[] slt8b = Hex.decode("435c098aa9909eb2377f1248b091b68987ff1838"); private byte[] sig8b = Hex.decode("2707b9ad5115c58c94e932e8ec0a280f56339e44a1b58d4ddcff2f312e5f34dcfe39e89c6a94dcee86dbbdae5b79ba4e0819a9e7bfd9d982e7ee6c86ee68396e8b3a14c9c8f34b178eb741f9d3f121109bf5c8172fada2e768f9ea1433032c004a8aa07eb990000a48dc94c8bac8aabe2b09b1aa46c0a2aa0e12f63fbba775ba7e"); // Example 9: A 1536-bit RSA key pair private RSAKeyParameters pub9 = new RSAKeyParameters(false, new BigInteger("e6bd692ac96645790403fdd0f5beb8b9bf92ed10007fc365046419dd06c05c5b5b2f48ecf989e4ce269109979cbb40b4a0ad24d22483d1ee315ad4ccb1534268352691c524f6dd8e6c29d224cf246973aec86c5bf6b1401a850d1b9ad1bb8cbcec47b06f0f8c7f45d3fc8f319299c5433ddbc2b3053b47ded2ecd4a4caefd614833dc8bb622f317ed076b8057fe8de3f84480ad5e83e4a61904a4f248fb397027357e1d30e463139815c6fd4fd5ac5b8172a45230ecb6318a04f1455d84e5a8b", 16), new BigInteger("010001", 16)); private RSAKeyParameters prv9 = new RSAPrivateCrtKeyParameters( new BigInteger("e6bd692ac96645790403fdd0f5beb8b9bf92ed10007fc365046419dd06c05c5b5b2f48ecf989e4ce269109979cbb40b4a0ad24d22483d1ee315ad4ccb1534268352691c524f6dd8e6c29d224cf246973aec86c5bf6b1401a850d1b9ad1bb8cbcec47b06f0f8c7f45d3fc8f319299c5433ddbc2b3053b47ded2ecd4a4caefd614833dc8bb622f317ed076b8057fe8de3f84480ad5e83e4a61904a4f248fb397027357e1d30e463139815c6fd4fd5ac5b8172a45230ecb6318a04f1455d84e5a8b", 16), new BigInteger("010001", 16), new BigInteger("6a7fd84fb85fad073b34406db74f8d61a6abc12196a961dd79565e9da6e5187bce2d980250f7359575359270d91590bb0e427c71460b55d51410b191bcf309fea131a92c8e702738fa719f1e0041f52e40e91f229f4d96a1e6f172e15596b4510a6daec26105f2bebc53316b87bdf21311666070e8dfee69d52c71a976caae79c72b68d28580dc686d9f5129d225f82b3d615513a882b3db91416b48ce08888213e37eeb9af800d81cab328ce420689903c00c7b5fd31b75503a6d419684d629", 16), new BigInteger("f8eb97e98df12664eefdb761596a69ddcd0e76daece6ed4bf5a1b50ac086f7928a4d2f8726a77e515b74da41988f220b1cc87aa1fc810ce99a82f2d1ce821edced794c6941f42c7a1a0b8c4d28c75ec60b652279f6154a762aed165d47dee367", 16), new BigInteger("ed4d71d0a6e24b93c2e5f6b4bbe05f5fb0afa042d204fe3378d365c2f288b6a8dad7efe45d153eef40cacc7b81ff934002d108994b94a5e4728cd9c963375ae49965bda55cbf0efed8d6553b4027f2d86208a6e6b489c176128092d629e49d3d", 16), new BigInteger("2bb68bddfb0c4f56c8558bffaf892d8043037841e7fa81cfa61a38c5e39b901c8ee71122a5da2227bd6cdeeb481452c12ad3d61d5e4f776a0ab556591befe3e59e5a7fddb8345e1f2f35b9f4cee57c32414c086aec993e9353e480d9eec6289f", 16), new BigInteger("4ff897709fad079746494578e70fd8546130eeab5627c49b080f05ee4ad9f3e4b7cba9d6a5dff113a41c3409336833f190816d8a6bc42e9bec56b7567d0f3c9c696db619b245d901dd856db7c8092e77e9a1cccd56ee4dba42c5fdb61aec2669", 16), new BigInteger("77b9d1137b50404a982729316efafc7dfe66d34e5a182600d5f30a0a8512051c560d081d4d0a1835ec3d25a60f4e4d6aa948b2bf3dbb5b124cbbc3489255a3a948372f6978496745f943e1db4f18382ceaa505dfc65757bb3f857a58dce52156", 16)); // PSS Example 9.1 private byte[] msg9a = Hex.decode("a88e265855e9d7ca36c68795f0b31b591cd6587c71d060a0b3f7f3eaef43795922028bc2b6ad467cfc2d7f659c5385aa70ba3672cdde4cfe4970cc7904601b278872bf51321c4a972f3c95570f3445d4f57980e0f20df54846e6a52c668f1288c03f95006ea32f562d40d52af9feb32f0fa06db65b588a237b34e592d55cf979f903a642ef64d2ed542aa8c77dc1dd762f45a59303ed75e541ca271e2b60ca709e44fa0661131e8d5d4163fd8d398566ce26de8730e72f9cca737641c244159420637028df0a18079d6208ea8b4711a2c750f5"); private byte[] slt9a = Hex.decode("c0a425313df8d7564bd2434d311523d5257eed80"); private byte[] sig9a = Hex.decode("586107226c3ce013a7c8f04d1a6a2959bb4b8e205ba43a27b50f124111bc35ef589b039f5932187cb696d7d9a32c0c38300a5cdda4834b62d2eb240af33f79d13dfbf095bf599e0d9686948c1964747b67e89c9aba5cd85016236f566cc5802cb13ead51bc7ca6bef3b94dcbdbb1d570469771df0e00b1a8a06777472d2316279edae86474668d4e1efff95f1de61c6020da32ae92bbf16520fef3cf4d88f61121f24bbd9fe91b59caf1235b2a93ff81fc403addf4ebdea84934a9cdaf8e1a9e"); // PSS Example 9.2 private byte[] msg9b = Hex.decode("c8c9c6af04acda414d227ef23e0820c3732c500dc87275e95b0d095413993c2658bc1d988581ba879c2d201f14cb88ced153a01969a7bf0a7be79c84c1486bc12b3fa6c59871b6827c8ce253ca5fefa8a8c690bf326e8e37cdb96d90a82ebab69f86350e1822e8bd536a2e"); private byte[] slt9b = Hex.decode("b307c43b4850a8dac2f15f32e37839ef8c5c0e91"); private byte[] sig9b = Hex.decode("80b6d643255209f0a456763897ac9ed259d459b49c2887e5882ecb4434cfd66dd7e1699375381e51cd7f554f2c271704b399d42b4be2540a0eca61951f55267f7c2878c122842dadb28b01bd5f8c025f7e228418a673c03d6bc0c736d0a29546bd67f786d9d692ccea778d71d98c2063b7a71092187a4d35af108111d83e83eae46c46aa34277e06044589903788f1d5e7cee25fb485e92949118814d6f2c3ee361489016f327fb5bc517eb50470bffa1afa5f4ce9aa0ce5b8ee19bf5501b958"); public String getName() { return "PSSBlindTest"; } private void testSig( int id, RSAKeyParameters pub, RSAKeyParameters prv, byte[] slt, byte[] msg, byte[] sig) throws Exception { RSABlindingFactorGenerator blindFactorGen = new RSABlindingFactorGenerator(); RSABlindingEngine blindingEngine = new RSABlindingEngine(); PSSSigner blindSigner = new PSSSigner(blindingEngine, new SHA1Digest(), 20); PSSSigner signer = new PSSSigner(new RSAEngine(), new SHA1Digest(), 20); blindFactorGen.init(pub); BigInteger blindFactor = blindFactorGen.generateBlindingFactor(); RSABlindingParameters params = new RSABlindingParameters(pub, blindFactor); // generate a blind signature blindSigner.init(true, new ParametersWithRandom(params, new FixedRandom(slt))); blindSigner.update(msg, 0, msg.length); byte[] blindedData = blindSigner.generateSignature(); RSAEngine signerEngine = new RSAEngine(); signerEngine.init(true, prv); byte[] blindedSig = signerEngine.processBlock(blindedData, 0, blindedData.length); // unblind the signature blindingEngine.init(false, params); byte[] s = blindingEngine.processBlock(blindedSig, 0, blindedSig.length); //signature verification if (!areEqual(s, sig)) { fail("test " + id + " failed generation"); } //verify signature with PSSSigner signer.init(false, pub); signer.update(msg, 0, msg.length); if (!signer.verifySignature(s)) { fail("test " + id + " failed PSSSigner verification"); } } private boolean isProcessingOkay( RSAKeyParameters pub, RSAKeyParameters prv, byte[] data, SecureRandom random) throws Exception { RSABlindingFactorGenerator blindFactorGen = new RSABlindingFactorGenerator(); RSABlindingEngine blindingEngine = new RSABlindingEngine(); PSSSigner blindSigner = new PSSSigner(blindingEngine, new SHA1Digest(), 20); PSSSigner pssEng = new PSSSigner(new RSAEngine(), new SHA1Digest(), 20); random.nextBytes(data); blindFactorGen.init(pub); BigInteger blindFactor = blindFactorGen.generateBlindingFactor(); RSABlindingParameters params = new RSABlindingParameters(pub, blindFactor); // generate a blind signature blindSigner.init(true, new ParametersWithRandom(params, random)); blindSigner.update(data, 0, data.length); byte[] blindedData = blindSigner.generateSignature(); RSAEngine signerEngine = new RSAEngine(); signerEngine.init(true, prv); byte[] blindedSig = signerEngine.processBlock(blindedData, 0, blindedData.length); // unblind the signature blindingEngine.init(false, params); byte[] s = blindingEngine.processBlock(blindedSig, 0, blindedSig.length); //verify signature with PSSSigner pssEng.init(false, pub); pssEng.update(data, 0, data.length); return pssEng.verifySignature(s); } public void performTest() throws Exception { testSig(1, pub1, prv1, slt1a, msg1a, sig1a); testSig(2, pub1, prv1, slt1b, msg1b, sig1b); testSig(3, pub2, prv2, slt2a, msg2a, sig2a); testSig(4, pub2, prv2, slt2b, msg2b, sig2b); testSig(5, pub4, prv4, slt4a, msg4a, sig4a); testSig(6, pub4, prv4, slt4b, msg4b, sig4b); testSig(7, pub8, prv8, slt8a, msg8a, sig8a); testSig(8, pub8, prv8, slt8b, msg8b, sig8b); testSig(9, pub9, prv9, slt9a, msg9a, sig9a); testSig(10, pub9, prv9, slt9b, msg9b, sig9b); // loop test int failed = 0; byte[] data = new byte[DATA_LENGTH]; SecureRandom random = new SecureRandom(); RSAKeyParameters[] kprv ={prv1, prv2, prv4, prv8, prv9}; RSAKeyParameters[] kpub ={pub1, pub2, pub4, pub8, pub9}; int i = 0; for (int j = 0; j < NUM_TESTS; j++, i++) { if (i == kprv.length) { i = 0; } if (!isProcessingOkay(kpub[i], kprv[i], data, random)) { failed++; } } if (failed != 0) { fail("loop test failed - failures: " + failed); } // key generation test RSAKeyPairGenerator pGen = new RSAKeyPairGenerator(); RSAKeyGenerationParameters genParam = new RSAKeyGenerationParameters( BigInteger.valueOf(0x11), new SecureRandom(), 1024, 25); pGen.init(genParam); failed = 0; for (int k = 0; k < NUM_TESTS_WITH_KEY_GENERATION; k++) { AsymmetricCipherKeyPair pair = pGen.generateKeyPair(); for (int j = 0; j < NUM_TESTS; j++) { if (!isProcessingOkay((RSAKeyParameters)pair.getPublic(), (RSAKeyParameters)pair.getPrivate(), data, random)) { failed++; } } } if (failed != 0) { fail("loop test with key generation failed - failures: " + failed); } } public static void main( String[] args) { runTest(new PSSBlindTest()); } }
package org.amityregion5.tictactical; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.g2d.SpriteBatch; public class TicTactical extends Game { // is jus gam // TODO things n stuff OrthographicCamera cam; Texture X; Texture O; Texture grid; Texture selector; Texture movingDisplay; Texture winDisplay; SpriteBatch spritebatch; private char[][] board = new char[9][9]; private char[] big_board = new char[9]; private boolean turn = false; // false is X, True is O private int next_move = -1; private char win = 0; private int players = 0; @Override public void create () { cam = new OrthographicCamera(); X = new Texture(Gdx.files.internal("X.png")); O = new Texture(Gdx.files.internal("O.png")); selector = new Texture(Gdx.files.internal("selector.png")); movingDisplay = new Texture(Gdx.files.internal("isMovingNow.png")); grid = new Texture(Gdx.files.internal("grid.png")); winDisplay = new Texture(Gdx.files.internal("hasWon.png")); spritebatch = new SpriteBatch(); spritebatch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); } @Override public void render () { Gdx.gl.glClearColor(1, 1, 1, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); int grid_size = Math.min(Gdx.graphics.getHeight(), Gdx.graphics.getWidth()); int miniboard_size = ((grid_size - 60) / 3) - 10; int slot_size = (miniboard_size / 3) - (miniboard_size / 9); if (Gdx.input.justTouched()) { if((win == 0) || (Gdx.input.getX() <= grid_size - 30 && Gdx.input.getY() <= grid_size - 30 && Gdx.input.getY() >= 30 && Gdx.input.getX() >= 30)){ int in_x = Gdx.input.getX() - 30; int in_y = Gdx.graphics.getHeight() - Gdx.input.getY() - 30; int miniboard = -1; int slot = -1; miniboard = (((in_x / (miniboard_size + 10))) % 3) + 3 * (in_y / (miniboard_size + 10)); slot = ((in_x - (miniboard % 3) * (miniboard_size + 10)) / ((miniboard_size + 10) / 3) % 3) + 3 * ((in_y - (miniboard / 3) * (miniboard_size + 10)) / ((miniboard_size + 10) / 3)); if(!(miniboard == -1 || slot == -1) && board[miniboard][slot] == 0 && (miniboard == next_move || next_move == -1) && big_board[miniboard] == 0){ //Grids arranged as follows: /* * 6 7 8 * 3 4 5 * 0 1 2 * */ if(turn){ board[miniboard][slot] = 'o'; }else{ board[miniboard][slot] = 'x'; } turn = !turn; char result = evaluate(board[miniboard], slot); if(result == 'x'){ big_board[miniboard] = 'X'; }else if(result == 'o'){ big_board[miniboard] = 'O'; } char[] board0 = new char[9]; for(int i = 0; i < 9; i++){ board0[i] = big_board[i]; } char winner = evaluate(board0, miniboard); if(winner == 'X' || winner == 'O'){ win = winner; }else{ int tie_test = 0; for(int i = 0; i < 9; i++){ if(big_board[i] != 0){ tie_test += 9; }else{ for(int j = 0; j < 9; j ++){ if(board[i][j] != 0){ tie_test++; } } } } if(tie_test == 81){ win = 'T'; } } if(big_board[slot] == 0){ next_move = slot; }else{ next_move = -1; } } }else if(win != 0){ reset(); } } spritebatch.setProjectionMatrix(cam.combined); spritebatch.begin();{ spritebatch.draw(grid, 30, 30, grid_size - 60, grid_size - 60); for(int i = 1; i <= 3; i ++){ for(int j = 1; j <= 3; j ++){ spritebatch.draw(grid, 30 + (i * 2.5f) + ((grid_size - 60) * (i - 1)) / 3, 30 + (j * 2.5f) + ((grid_size - 60) * (j - 1)) / 3, miniboard_size, miniboard_size); if(((i - 1) + (j- 1) * 3 == next_move || next_move == -1) && win == 0){ spritebatch.draw(selector, 30 + (i * 2.5f) + ((grid_size - 60) * (i - 1)) / 3, 30 + (j * 2.5f) + ((grid_size - 60) * (j - 1)) / 3, miniboard_size, miniboard_size); } } } //drawing x's and o's for(int i = 0; i < 9; i++){ for(int j = 0; j < 9; j ++){ if(board[i][j] == 'x'){ spritebatch.draw(X, 32.5f + ((i % 3) * 2.5f) + ((j % 3) * 2.5f) + ((grid_size - 60) * (i % 3)) / 3 + ((miniboard_size * (j % 3) / 3) + slot_size / 2) - (slot_size / 3), 32.5f + ((i / 3) * 2.5f) + ((j / 3) * 2.5f) + ((grid_size - 60) * (i / 3)) / 3 + ((miniboard_size * (j / 3) / 3) + slot_size / 2) - (slot_size / 3), slot_size, slot_size); }else if(board[i][j] == 'o'){ spritebatch.draw(O, 32.5f + ((i % 3) * 2.5f) + ((j % 3) * 2.5f) + ((grid_size - 60) * (i % 3)) / 3 + ((miniboard_size * (j % 3) / 3) + slot_size / 2) - (slot_size / 3), 32.5f + ((i / 3) * 2.5f) + ((j / 3) * 2.5f) + ((grid_size - 60) * (i / 3)) / 3 + ((miniboard_size * (j / 3) / 3) + slot_size / 2) - (slot_size / 3), slot_size, slot_size); } } if(big_board[i] == 'X'){ spritebatch.draw(X, 30 + (((i % 3) + 1) * 2.5f) + ((grid_size - 60) * (i % 3)) / 3, 30 + ((i / 3) * 2.5f) + ((grid_size - 60) * (i / 3)) / 3, miniboard_size, miniboard_size); }else if(big_board[i] == 'O'){ spritebatch.draw(O, 30 + (((i % 3) + 1) * 2.5f) + ((grid_size - 60) * (i % 3)) / 3, 30 + ((i / 3) * 2.5f) + ((grid_size - 60) * (i / 3)) / 3, miniboard_size, miniboard_size); } } //printing win statements if(win != 0){ if(win == 'X'){ spritebatch.draw(X, grid_size - 30 + slot_size, miniboard_size * 2 , miniboard_size, miniboard_size); spritebatch.draw(winDisplay, grid_size - 30 + slot_size * 1.25f, miniboard_size * 2 - slot_size * 1.25f, miniboard_size, miniboard_size); }else if(win == 'O'){ spritebatch.draw(O, grid_size - 30 + slot_size, miniboard_size * 2 , miniboard_size, miniboard_size); spritebatch.draw(winDisplay, grid_size - 30 + slot_size * 1.25f, miniboard_size * 2 - slot_size * 1.25f, miniboard_size, miniboard_size); } } //printing whose turn it b if(win == 0){ if(turn){ spritebatch.draw(O, grid_size - 30 + slot_size, miniboard_size * 2 , miniboard_size, miniboard_size); }else{ spritebatch.draw(X, grid_size - 30 + slot_size, miniboard_size * 2 , miniboard_size, miniboard_size); } spritebatch.draw(movingDisplay, grid_size - 30 + slot_size, miniboard_size * 2 - slot_size, miniboard_size, miniboard_size); } } spritebatch.end(); } @Override public void dispose () { X.dispose(); O.dispose(); grid.dispose(); selector.dispose(); movingDisplay.dispose(); winDisplay.dispose(); spritebatch.dispose(); } @Override public void resize(int width, int height) { super.resize(width, height); cam.setToOrtho(false, width, height); cam.update(); } @Override public void resume() { // TODO Auto-generated method stub super.resume(); } @Override public void pause() { // TODO Auto-generated method stub super.pause(); } public char evaluate(char[] b, int s){ if(b[s] != ' '){ if(s == 0){ if((b[0] == b[1] && b[1] == b[2]) || (b[0] == b[3] && b[3] == b[6]) || (b[0] == b[4] && b[4] == b[8])){ return b[s]; } }else if(s == 1){ if((b[0] == b[1] && b[1] == b[2]) || (b[1] == b[4] && b[4] == b[7])){ return b[s]; } }else if(s == 2){ if((b[0] == b[1] && b[1] == b[2]) || (b[2] == b[5] && b[5] == b[8]) || (b[2] == b[4] && b[4] == b[6])){ return b[s]; } }else if(s == 3){ if((b[0] == b[3] && b[3] == b[6]) || (b[3] == b[4] && b[4] == b[5])){ return b[s]; } }else if(s == 4){ if((b[3] == b[4] && b[4] == b[5]) || (b[1] == b[4] && b[4] == b[7]) || (b[0] == b[4] && b[4] == b[8] || (b[2] == b[4] && b[4] == b[6]))){ return b[s]; } }else if(s == 5){ if((b[2] == b[5] && b[5] == b[8]) || (b[3] == b[4] && b[4] == b[5])){ return b[s]; } }else if(s == 6){ if((b[6] == b[7] && b[7] == b[8]) || (b[0] == b[3] && b[3] == b[6]) || (b[2] == b[4] && b[4] == b[6])){ return b[s]; } }else if(s == 7){ if((b[6] == b[7] && b[7] == b[8]) || (b[1] == b[4] && b[4] == b[7])){ return b[s]; } }else if(s == 8){ if((b[6] == b[7] && b[7] == b[8]) || (b[2] == b[5] && b[5] == b[8]) || (b[0] == b[4] && b[4] == b[8])){ return b[s]; } } } return 0; } public void reset(){ win = 0; next_move = -1; turn = false; board = new char[9][9]; players = 0; big_board = new char[9]; } }
package org.zstack.test; import org.zstack.core.Platform; import org.zstack.core.componentloader.ComponentLoader; import org.zstack.header.exception.CloudRuntimeException; import java.io.*; import java.net.URL; import java.util.ArrayList; import java.util.List; import static org.zstack.utils.StringDSL.ln; public class BeanConstructor { private List<String> xmls = new ArrayList<String>(); private List<String> excludedXmls = new ArrayList<String>(); private static final String SPRING_XML_NAME = "spring-config-for-unit-test-from-BeanConstructor.xml"; protected ComponentLoader loader; protected String springConfigPath; private boolean loadAll = false; private String coreBeans = ln( "<import resource=\"springConfigXml/ThreadFacade.xml\" />", "<import resource=\"springConfigXml/CloudBus.xml\" />", "<import resource=\"springConfigXml/validation.xml\" />", "<import resource=\"springConfigXml/InventoryFacade.xml\" />", "<import resource=\"springConfigXml/DatabaseFacade.xml\" />", "<import resource=\"springConfigXml/JobQueueFacade.xml\" />", "<import resource=\"springConfigXml/GlobalConfigFacade.xml\" />", "<import resource=\"springConfigXml/ProgressBar.xml\" />", "<import resource=\"springConfigXml/RESTFacade.xml\" />", "<import resource=\"springConfigXml/QueryFacade.xml\" />", "<import resource=\"springConfigXml/ansibleFacade.xml\" />", "<import resource=\"springConfigXml/CascadeFacade.xml\" />", "<import resource=\"springConfigXml/tag.xml\" />", "<import resource=\"springConfigXml/Aspect.xml\" />", "<import resource=\"springConfigXml/keyValueFacade.xml\" />", "<import resource=\"springConfigXml/jmx.xml\" />", "<import resource=\"springConfigXml/logFacade.xml\" />", "<import resource=\"springConfigXml/Error.xml\" />", "<import resource=\"springConfigXml/gc.xml\" />", "<import resource=\"springConfigXml/debug.xml\" />", "<import resource=\"springConfigXml/SchedulerFacade.xml\" />" ).toString(); public BeanConstructor() { } public BeanConstructor addXml(String xmlName) { if (this.getClass().getClassLoader().getResource(String.format("springConfigXml/%s", xmlName)) == null) { throw new IllegalArgumentException(String.format("Cannot find %s in test/src/test/resources/springConfigXml/", xmlName)); } xmls.add(xmlName); return this; } public BeanConstructor excludeXml(String name) { excludedXmls.add(name); return this; } public BeanConstructor addAllConfigInZstackXml() { loadAll = true; return this; } protected void generateSpringConfig() { try { URL templatePath = this.getClass().getClassLoader().getResource("zstack-template.xml"); File template = new File(templatePath.getPath()); BufferedReader input = new BufferedReader(new FileReader(template)); List<String> contents = new ArrayList<String>(); String line = null; while ((line = input.readLine()) != null) { contents.add(line); } String configPath = "target/test-classes/" + SPRING_XML_NAME; int insertPos = contents.size() - 1; if (loadAll) { String r = String.format("\t<import resource=\"zstack.xml\" />"); contents.add(insertPos, r); } else { for (String bean: coreBeans.split("\\n")) { contents.add(insertPos, bean); } } for (String c : xmls) { String r = String.format("\t<import resource=\"springConfigXml/%s\" />", c); contents.add(insertPos, r); } File tmpSpringConfig = new File(configPath); FileWriter fw = new FileWriter(tmpSpringConfig.getAbsolutePath()); BufferedWriter bw = new BufferedWriter(fw); for (String s : contents) { bw.write(s + "\n"); } bw.close(); fw.close(); springConfigPath = configPath; } catch (Exception e) { throw new CloudRuntimeException("Unable to create temporary spring xml config", e); } } public ComponentLoader build() { excludeXmls(); generateSpringConfig(); System.setProperty("spring.xml", SPRING_XML_NAME); loader = Platform.getComponentLoader(); return loader; } private void excludeXmls() { List<String> tmp = new ArrayList<String>(); for (String xml : xmls) { if (excludedXmls.contains(xml)) { continue; } tmp.add(xml); } xmls = tmp; } }
import java.awt.event.KeyEvent; import java.util.HashMap; import java.util.ArrayList; import java.util.Iterator; import java.awt.image.BufferedImage; import java.awt.Rectangle; import javax.imageio.ImageIO; import java.io.File; import java.io.IOException; public class PlayerModel extends Model implements InputResponder { // Tracks whether a particular button was pressed down private boolean upDown; private boolean downDown; private boolean leftDown; private boolean rightDown; private boolean zDown; private boolean xDown; // Contains necessary images to correctly display character sprite private BufferedImage[] playerFrames; private BufferedImage defensePodImage; private BufferedImage cobaltImage; private int curFrame; // Coordinates to keep positioning of character sprite on viewing screen -- // refers to top-left corner of its bounding box private int xPos; private int yPos; // Used in collision detection with enemies, boundaries, bullets, and walls private int spriteWidth; private int spriteHeight; private ArrayList<Bullet> bulletList; // User bullets private MillisecTimer bulletTimer; private MillisecTimer cobaltTimer; private int score; private int lives; private int missleLevel; private int laserLevel; private int ringLevel; private int fragmentCount; private int defensePodLevel; private float defensePodOscillator; // characters speed private float velocity; public enum BulletType { RING, MISSLE, LASER, BASIC } private BulletType bulletType; private LevelModel levelModel; private TileMap tileMap; PlayerModel(LevelModel levelModel, TileMap tileMap) { // No buttons pressed on player creation upDown = false; downDown = false; leftDown = false; rightDown = false; zDown = false; xDown = false; // Starting position of sprite -- sprite's upper left pixel (1,1) xPos = 64; yPos = 128; // Initial character attribute on creation score = 0; lives = 4; missleLevel = 0; ringLevel = 0; laserLevel = 0; fragmentCount = 0; defensePodLevel = 0; defensePodOscillator = 0; cobaltTimer = null; // Characters movement speed // Note movement updates at milliseconds since last frame(~33) * // velocity(.1) // so 33 * .1 = 3.3 pixels moved per frame, which meets the // specification velocity = .1f; bulletList = new ArrayList<Bullet>(); bulletTimer = new MillisecTimer(); bulletType = BulletType.BASIC; // Loads Images used to show which direction the character sprite is // moving/aiming playerFrames = new BufferedImage[8]; try { playerFrames[0] = ImageIO.read(new File("assets/player_up.png")); playerFrames[1] = ImageIO.read(new File("assets/player_up_right.png")); playerFrames[2] = ImageIO.read(new File("assets/player_right.png")); playerFrames[3] = ImageIO.read(new File("assets/player_down_right.png")); playerFrames[4] = ImageIO.read(new File("assets/player_down.png")); playerFrames[5] = ImageIO.read(new File("assets/player_down_left.png")); playerFrames[6] = ImageIO.read(new File("assets/player_left.png")); playerFrames[7] = ImageIO.read(new File("assets/player_up_left.png")); spriteWidth = playerFrames[0].getWidth(); spriteHeight = playerFrames[0].getHeight(); defensePodImage = ImageIO.read(new File("assets/defensePodImage.png")); cobaltImage = ImageIO.read(new File("assets/cobaltBomb.png")); } catch (IOException e) { e.printStackTrace(); } curFrame = 2; this.levelModel = levelModel; this.tileMap = tileMap; // levelModel.getModelController().getViewController().getDrawPanel().getInputHandler().registerInputResponder(this); } /* * returns List of tiles that sprite is currently touching Notes: Character * sprite size = 32 x 64 pixels or 1 x 2 tiles exactly Thus: character can * either be touching 2, 4, or 6 tiles at any given time */ // This Method returns an array of references to different types of tiles // -- used later to ensure character sprite can't move through solid tiles public ArrayList<Integer> onTiles() { ArrayList<Integer> onTiles = new ArrayList<Integer>(); // Tile size in pixels int tileWidth = tileMap.getTileWidth(); int tileHeight = tileMap.getTileHeight(); int coverWide = 1; int coverHigh = 1; // Character only touching 1 column of tiles(Perfectly aligned vertically) if (xPos % tileWidth == 0) { coverWide = 1; } // Character touching 2 columns of tiles else { coverWide = 2; } // Character touching 2 rows of tiles(Perfectly aligned) if (yPos % tileHeight == 0) { coverHigh = 2; } // Character touching 3 rows of tiles else { coverHigh = 3; } // Obtains upper-left tile that the character sprite is currently on int tileCoordX = (xPos + levelModel.getDistanceScrolled()) / tileWidth; int tileCoordY = yPos / tileHeight; // Obtains all tiles character is currently touching for (int y = 0; y < coverHigh; y++) { for (int x = 0; x < coverWide; x++) { // adds the different types of tiles that the character is // touching to the return list(references technically) onTiles.add(tileMap.getTile( ((tileCoordY + y) * tileMap.getTileMapWidth()) + (tileCoordX + x)) ); } } return onTiles; } // Flags that a key is pressed down public void keyDownResponse(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP) upDown = true; if (e.getKeyCode() == KeyEvent.VK_DOWN) downDown = true; if (e.getKeyCode() == KeyEvent.VK_LEFT) leftDown = true; if (e.getKeyCode() == KeyEvent.VK_RIGHT) rightDown = true; if (e.getKeyCode() == KeyEvent.VK_Z) zDown = true; if (e.getKeyCode() == KeyEvent.VK_X) xDown = true; } // Flags when a key is released -- think holding down fire key for constant fire public void keyUpResponse(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP) upDown = false; if (e.getKeyCode() == KeyEvent.VK_DOWN) downDown = false; if (e.getKeyCode() == KeyEvent.VK_LEFT) leftDown = false; if (e.getKeyCode() == KeyEvent.VK_RIGHT) rightDown = false; if (e.getKeyCode() == KeyEvent.VK_Z) zDown = false; if (e.getKeyCode() == KeyEvent.VK_X) xDown = false; if (e.getKeyCode() == KeyEvent.VK_ENTER) { if (levelModel.paused == true) levelModel.paused = false; else levelModel.paused = true; } } // Applies pickup's modifier and plays associated sound public void getPickup(String type) { switch (type) { case "fragment": fragmentCount += 1; SoundManager.get().playSound("fragment"); if (fragmentCount > 32) { fragmentCount = 0; lives += 1; } break; case "ring": ringLevel += 1; bulletType = BulletType.RING; SoundManager.get().playSound("pickup"); break; case "missle": missleLevel += 1; bulletType = BulletType.MISSLE; SoundManager.get().playSound("pickup"); break; case "laser": laserLevel += 1; bulletType = BulletType.LASER; SoundManager.get().playSound("pickup"); break; case "speed": velocity += .05; SoundManager.get().playSound("pickup"); break; case "defense_pod": defensePodLevel += 1; SoundManager.get().playSound("pickup"); break; } } public int update(float dt) { return update(dt, 0); } /* * The update is called explicitly in LevelModel's update method. */ public int update(float dt, int scrollDelta) { // x => fire weapon if (xDown == true && bulletTimer.getDt() > 250) { bulletTimer.reset(); switch(bulletType) { case BASIC: fireBasic(); SoundManager.get().playSound("bullet"); break; case RING: fireRing(); SoundManager.get().playSound("ring"); break; case MISSLE: fireMissle(); SoundManager.get().playSound("missle"); break; case LASER: fireLaser(); SoundManager.get().playSound("laser"); break; } } // use CobaltBomb if (zDown) cobaltBomb(); // retain previous frames coordinates int oldX = xPos; int oldY = yPos; // Hold change in x and y variables between current and previous frame float deltaX = 0; float deltaY = 0; // Move: North-east if (upDown == true && rightDown == true) { deltaX = velocity * dt; deltaY = -velocity * dt; if (xDown == false) curFrame = 1; } // Move: South-east else if (downDown == true && rightDown == true) { deltaX = velocity * dt; deltaY = velocity * dt; if (xDown == false) curFrame = 3; } // Move: South-west else if (downDown == true && leftDown == true) { deltaX = -velocity * dt; deltaY = velocity * dt; if (xDown == false) curFrame = 5; } // Move: North-west else if (upDown == true && leftDown == true) { deltaX = -velocity * dt; deltaY = -velocity * dt; if (xDown == false) curFrame = 7; } // Move: North else if (upDown == true) { deltaY = -velocity * dt; if (xDown == false) curFrame = 0; } // Move: East else if (rightDown == true) { deltaX = velocity * dt; if (xDown == false) curFrame = 2; } // Move: South else if (downDown == true) { deltaY = velocity * dt; if (xDown == false) curFrame = 4; } // Move: West else if (leftDown == true) { deltaX = -velocity * dt; if (xDown == false) curFrame = 6; } // Applying change in character Location from previous frame // Updates x coordinate xPos += deltaX; ArrayList<Integer> tiles = onTiles(); // Ensures player doesn't move horizontally through solid object tiles for (int i = 0; i < tiles.size(); i++) { if (tiles.get(i) < 17 || tiles.get(i) > 23) { xPos = oldX - deltaX; if (xPos < 0) levelModel.playerDeath(); } } // Ensures player doesn't move vertically through solid object tiles yPos += deltaY; tiles = onTiles(); for (int i = 0; i < tiles.size(); i++) { if (tiles.get(i) < 17 || tiles.get(i) > 23) { yPos = oldY; } } // Restricts player from moving off left side of screen if (xPos < 0) xPos = 0; // Restricts player from moving off right side of screen if (xPos > ViewController.SCREEN_WIDTH - spriteWidth) xPos = ViewController.SCREEN_WIDTH - spriteWidth; // Restricts player from moving off north side of screen if (yPos < 0) yPos = 0; // Restricts player from moving off south side of screen if (yPos > ViewController.SCREEN_HEIGHT - spriteHeight) yPos = ViewController.SCREEN_HEIGHT - spriteHeight; // Checks if player collides with any pickups for (int xx = 0; xx < levelModel.getLevelPickups().size(); xx++) { Pickup pk = levelModel.getLevelPickups().get(xx); if (Utils.boxCollision(new Rectangle(xPos, yPos, spriteWidth, spriteHeight), new Rectangle(pk.getXPos(), pk.getYPos(), pk.getWidth(), pk.getHeight()))) { getPickup(pk.type); score += ScoreTable.scoreForPickup(pk); levelModel.getLevelPickups().remove(xx); xx } } // updates the defense pod's position and determines if it killed an enemy(updates scoretable if so) if (defensePodLevel > 0) { // updates pod position defensePodOscillator += ((float) defensePodLevel / 2 * dt); Rectangle boundingBox = new Rectangle(getDefensePodXPos(), getDefensePodYPos(), defensePodImage.getWidth(), defensePodImage.getHeight()); // defense pod's hitbox // determines if pod contacted and killed an enemy for (int i = 0; i < levelModel.getActiveEnemies().size(); i++) { EnemyModel em = levelModel.getActiveEnemies().get(i); if (Utils.boxCollision(em.getBoundingBox(), boundingBox)) { em.kill(); score += ScoreTable.scoreForKilled(em); Pickup[] p = em.getDrop(); if (p[0] != null) levelModel.getLevelPickups().add(p[0]); if (p[1] != null) levelModel.getLevelPickups().add(p[1]); } } } // Updates bullet: position, enemy damaged/killed, off-screen(expires) for (Iterator<Bullet> iterator = bulletList.iterator(); iterator.hasNext();) { Bullet bullet = iterator.next(); // removes off-screen bullets if (bullet.shouldDelete()) { iterator.remove(); } else { bullet.update(dt); Rectangle boundingBox = bullet.getBoundingBox(); int tileCoordX; int tileCoordY; int tile; boolean deleted = false; /* * nested four loop only is grabbing the 4 corners of the * bullet's hit box and checking the type of tiles that they * contact. The current bullets range from 8x8 to 17x17, so they * all can contact the same range of tiles at any given time: * 1-4 A bullet expires on contact with a solid object(besides * ring bullets) */ for (int y = bullet.yPos; y < bullet.yPos + boundingBox.getHeight(); y += boundingBox.getHeight()) { for (int x = bullet.xPos; x < bullet.xPos + boundingBox.getWidth(); x += boundingBox.getWidth()) { tileCoordX = (x + levelModel.getDistanceScrolled()) / tileMap.getTileWidth(); tileCoordY = y / tileMap.getTileHeight(); // flags bullet to be deleted if it contacts solid tile(besides ring bullets) tile = tileMap.getTile(((tileCoordY) * tileMap.getTileMapWidth()) + (tileCoordX)); if (tile < 17 || tile > 23) { if (!(bullet instanceof RingBullet)) deleted = true; } } } if (deleted) { iterator.remove(); continue; } /* * For loop: Determines if a bullet contacts an enemy On * contact: Damages/kills enemy and is deleted unless it's a * ring bullet On Kill: updates scoreboard, determines drop */ for (int i = 0; i < levelModel.getActiveEnemies().size(); i++) { EnemyModel enemy = levelModel.getActiveEnemies().get(i); if (bullet.collidesWith(enemy.getBoundingBox())) { boolean kill = enemy.hit(bullet.getPower()); if (kill == true) { SoundManager.get().playSound("kill"); score += ScoreTable.scoreForKilled(enemy); Pickup[] p = enemy.getDrop(); if (p[0] != null) levelModel.getLevelPickups().add(p[0]); if (p[1] != null) levelModel.getLevelPickups().add(p[1]); } else { SoundManager.get().playSound("hit"); } } } } } return 0; } public void death() { lives -= 1; // Starting position of character respawn xPos = 64; yPos = 128; // Sets level of weapon character was using at death to zero if (bulletType == BulletType.MISSLE) missleLevel = 0; else if (bulletType == BulletType.LASER) laserLevel = 0; else if (bulletType == BulletType.RING) ringLevel = 0; // Eliminates collected fragments and defense pod fragmentCount = 0; defensePodLevel = 0; defensePodOscillator = 0; cobaltTimer = null; velocity = .1f; bulletList.clear(); bulletTimer = new MillisecTimer(); bulletType = BulletType.BASIC; curFrame = 2; } private void cobaltBomb() { if (fragmentCount >= 4) { levelModel.cobaltBomb(); fragmentCount -= 4; cobaltTimer = new MillisecTimer(); } } private void fireBasic() { bulletList.add(new Bullet(xPos + (spriteWidth / 2), yPos + (spriteHeight / 2), curFrame)); } private void fireRing() { // 1 ring => levels 1-4 -- fires facing direction bulletList.add(new RingBullet(xPos + (spriteWidth / 2), yPos + (spriteHeight / 2), curFrame)); // 2 rings => levels 5-9 -- fires forward and backward of // shooting direction if (ringLevel >= 5) { bulletList.add(new RingBullet(xPos + (spriteWidth / 2), yPos + (spriteHeight / 2), (curFrame + 4) % 8)); } // 4 rings => levels 10+ -- fires 1 behind and 3 in facing // direction (straight, 45 degrees up, 45 degrees down) if (ringLevel >= 10) { bulletList.add(new RingBullet(xPos + (spriteWidth / 2), yPos + (spriteHeight / 2), (curFrame + 1) % 8)); bulletList.add(new RingBullet(xPos + (spriteWidth / 2), yPos + (spriteHeight / 2), (curFrame + 7) % 8)); } } private void fireMissle() { // 1 missile => levels: 1-4 -- Fires right bulletList.add(new MissleBullet(xPos + (spriteWidth / 2), yPos + (spriteHeight / 2), 2)); // 2 missiles => levels: 5-9 -- Fires: left, right if (missleLevel >= 5) { bulletList.add(new MissleBullet(xPos + (spriteWidth / 2), yPos + (spriteHeight / 2), 6)); } // 4 missiles => levels: 10+ -- Fires: up, down, left, right if (missleLevel >= 10) { bulletList.add(new MissleBullet(xPos + (spriteWidth / 2), yPos + (spriteHeight / 2), 0)); bulletList.add(new MissleBullet(xPos + (spriteWidth / 2), yPos + (spriteHeight / 2), 4)); } } private void fireLaser() { // 4 lasers => levels 10+ -- fires forward & backward of // player facing direction and 1 perpendicular to both those if (laserLevel >= 10) { bulletList.add(new LaserBullet(xPos + (spriteWidth / 2), yPos + (spriteHeight / 2), (curFrame + 1) % 8)); bulletList.add(new LaserBullet(xPos + (spriteWidth / 2), yPos + (spriteHeight / 2), (curFrame + 7) % 8)); bulletList.add(new LaserBullet(xPos + (spriteWidth / 2), yPos + (spriteHeight / 2), (curFrame + 3) % 8)); bulletList.add(new LaserBullet(xPos + (spriteWidth / 2), yPos + (spriteHeight / 2), (curFrame + 5) % 8)); } // 2 lasers => levels 5-9 -- fires forward & backward of // player facing direction else if (laserLevel >= 5) { bulletList.add(new LaserBullet(xPos + (spriteWidth / 2), yPos + (spriteHeight / 2), (curFrame + 4) % 8)); bulletList.add(new LaserBullet(xPos + (spriteWidth / 2), yPos + (spriteHeight / 2), curFrame)); } // 1 laser => levels 1-4 -- fires facing direction else { bulletList.add(new LaserBullet(xPos + (spriteWidth / 2), yPos + (spriteHeight / 2), curFrame)); } } public int getXPos() { return xPos; } public int getYPos() { return yPos; } public int getWidth() { return spriteWidth; } public int getHeight() { return spriteHeight; } public int getLaserLevel() { return laserLevel; } public int getMissleLevel() { return missleLevel; } public int getRingLevel() { return laserLevel; } public int getScore() { return score; } public int getLives() { return lives; } public int getFragmentCount() { return fragmentCount; } public int getDefensePodLevel() { return defensePodLevel; } public double getDefensePodOscillator() { return Math.toRadians(defensePodOscillator % 360); } public int getDefensePodXPos() { return (int) (getXPos() + (int) getWidth() / 2 + (Math.cos(getDefensePodOscillator()) * 64)); } public int getDefensePodYPos() { return (int) (getYPos() + (int) getHeight() / 2 + (Math.sin(getDefensePodOscillator()) * 64)); } public float getCobaltDt() { if (cobaltTimer != null) { float dt = cobaltTimer.getDt(); if (dt < 1500) return cobaltTimer.getDt(); else { cobaltTimer = null; return 0.0f; } } else { return 0.0f; } } public BufferedImage getCobaltBombImage() { return cobaltImage; } public Rectangle getBoundingBox() { return new Rectangle(xPos, yPos, spriteWidth, spriteHeight); } public ArrayList<Bullet> getBulletList() { return bulletList; } public BufferedImage getPlayerImage() { return playerFrames[curFrame]; } public BufferedImage getDefensePodImage() { return defensePodImage; } public HashMap<String, Model> getVisibleModels() { return new HashMap<String, Model>(); } }
package jolie.process; import jolie.runtime.FaultException; import jolie.runtime.ParallelExecution; public class ParallelProcess implements Process { final private Process[] children; public ParallelProcess( Process[] children ) { this.children = children; } public void run() throws FaultException { (new ParallelExecution( children )).run(); } public Process clone( TransformationReason reason ) { return new ParallelProcess( children ); } public boolean isKillable() { for( Process child : children ) { if ( child.isKillable() == false ) { return false; } } return true; } }
package simulation; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import interface_objects.InputObject; import interface_objects.OutputModel; /** * SolveModelTest * This class is the main app class called in the backend. * It is responsible to get the json model file produced in the frontend and process into the model used in the backend. * Then it executes all analysis creating a output file that has the json analysed file to be send back to the frontend. * */ public class SolveModel { /** * This method is responsible to execute all steps to generate the analysis file. * @param args Default command line arguments. */ public static void main(String[] args) { //This is the default filePath to be executed if no file is pass through parameters String filePath = "temp/"; String inputFile = "default.json"; String outputFile = "output.out"; try { //creating the backend model to be analysed ModelSpec modelSpec = convertModelFromFile(filePath + inputFile); //Analyse the model TroposCSPAlgorithm solver = new TroposCSPAlgorithm(modelSpec); //long startTime = System.currentTimeMillis(); //Scaleability Testing solver.solveModel(); //long endTime = System.currentTimeMillis(); //Scalability Testing //System.out.print("Time:" + (endTime - startTime)); //Scalability Testing createOutputFile(solver, filePath + outputFile); } catch (RuntimeException e) { try { File file; file = new File(filePath + outputFile); if (!file.exists()) { file.createNewFile(); } PrintWriter printFile = new PrintWriter(file); String message = "{ \"errorMessage\" : \"RuntimeException: " + e.getMessage() + "\" }"; message = message.replaceAll("\\r\\n|\\r|\\n", " "); printFile.printf(message); printFile.close(); } catch (Exception f) { throw new RuntimeException("Error while writing ErrorMessage: " + f.getMessage()); } // throw new RuntimeException(e.getMessage()); } catch (Exception e) { try { File file; file = new File(filePath + outputFile); if (!file.exists()) { file.createNewFile(); } PrintWriter printFile = new PrintWriter(file); String message = "{ \"errorMessage\" : \"Exception: " + e.getMessage() + "\" }"; message = message.replaceAll("\\r\\n|\\r|\\n", " "); printFile.printf(message); printFile.close(); } catch (Exception f) { throw new RuntimeException("Error while writing ErrorMessage: " + f.getMessage()); } } } /** * This method converts the Output object with the analyzed data into a json object file to be sent to frontend. * @param TroposCSPAlgorithm * The solver object that contains all necessary data. * @param filePath * Name of the file to be read by CGI to be sent to frontend */ private static void createOutputFile(TroposCSPAlgorithm solver, String filePath) { //Gson gson = new Gson(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); OutputModel outputModel = solver.getSpec().getOutputModel(); try { File file; file = new File(filePath); if (!file.exists()) { file.createNewFile(); } PrintWriter printFile = new PrintWriter(file); //printFile.printf(sb.toString()); printFile.printf(gson.toJson(outputModel)); printFile.close(); } catch (Exception e) { throw new RuntimeException("Error in createOutputFile: " + e.getMessage()); } } /** * This method converts the model file sent by the frontend into the ModelSpecPojo in order to be analysed * @param filePath * Path to the file with the frontend model * @return * ModelSpecPojo backend model */ private static ModelSpec convertModelFromFile(String filePath) { try{ Gson gson = new Gson(); InputObject frontendObject = gson.fromJson(new FileReader(filePath), InputObject.class); ModelSpec modelSpec = ModelSpecBuilder.buildModelSpec(frontendObject); return modelSpec; }catch(Exception e){ throw new RuntimeException("Error in convertModelFromFile() method: /n" + e.getMessage()); } } }
package org.ccnx.ccn.test; import org.ccnx.ccn.config.PlatformConfiguration; import org.junit.Test; /** * Test the automatic platform detection in PlatformConfiguration. * * This is really a non-test. Just an easy place to run the test for visual inspection. */ public class PlatformTest { @Test public void testNeedSignatureLock() throws Exception { System.out.println("need signatures: " + PlatformConfiguration.needSignatureLock()); } }
package io.datakernel.ot; import com.google.gson.TypeAdapter; import io.datakernel.annotation.Nullable; import io.datakernel.async.Stage; import io.datakernel.eventloop.Eventloop; import io.datakernel.jmx.EventloopJmxMBeanEx; import io.datakernel.jmx.JmxAttribute; import io.datakernel.jmx.StageStats; import io.datakernel.util.gson.GsonAdapters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.sql.DataSource; import java.io.IOException; import java.sql.*; import java.util.*; import java.util.concurrent.ExecutorService; import static io.datakernel.jmx.ValueStats.SMOOTHING_WINDOW_5_MINUTES; import static io.datakernel.util.CollectionUtils.difference; import static io.datakernel.util.CollectionUtils.union; import static io.datakernel.util.Preconditions.checkState; import static io.datakernel.util.gson.GsonAdapters.indent; import static io.datakernel.util.gson.GsonAdapters.ofList; import static java.util.Collections.nCopies; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.*; public class OTRemoteSql<D> implements OTRemote<Integer, D>, EventloopJmxMBeanEx { private final Logger logger = LoggerFactory.getLogger(getClass()); public static final double DEFAULT_SMOOTHING_WINDOW = SMOOTHING_WINDOW_5_MINUTES; public static final String DEFAULT_REVISION_TABLE = "ot_revisions"; public static final String DEFAULT_DIFFS_TABLE = "ot_diffs"; public static final String DEFAULT_BACKUP_TABLE = "ot_revisions_backup"; private final Eventloop eventloop; private final ExecutorService executor; private final OTSystem<D> otSystem; private final DataSource dataSource; private final TypeAdapter<List<D>> diffsAdapter; private String tableRevision = DEFAULT_REVISION_TABLE; private String tableDiffs = DEFAULT_DIFFS_TABLE; private String tableBackup = DEFAULT_BACKUP_TABLE; private String createdBy = null; private final StageStats stageCreateCommitId = StageStats.create(DEFAULT_SMOOTHING_WINDOW); private final StageStats stagePush = StageStats.create(DEFAULT_SMOOTHING_WINDOW); private final StageStats stageGetHeads = StageStats.create(DEFAULT_SMOOTHING_WINDOW); private final StageStats stageLoadCommit = StageStats.create(DEFAULT_SMOOTHING_WINDOW); private final StageStats stageIsSnapshot = StageStats.create(DEFAULT_SMOOTHING_WINDOW); private final StageStats stageLoadSnapshot = StageStats.create(DEFAULT_SMOOTHING_WINDOW); private final StageStats stageSaveSnapshot = StageStats.create(DEFAULT_SMOOTHING_WINDOW); private OTRemoteSql(Eventloop eventloop, ExecutorService executor, OTSystem<D> otSystem, TypeAdapter<List<D>> diffsAdapter, DataSource dataSource) { this.eventloop = eventloop; this.executor = executor; this.otSystem = otSystem; this.dataSource = dataSource; this.diffsAdapter = diffsAdapter; } public static <D> OTRemoteSql<D> create(Eventloop eventloop, ExecutorService executor, DataSource dataSource, OTSystem<D> otSystem, TypeAdapter<D> diffAdapter) { TypeAdapter<List<D>> listAdapter = indent(ofList(diffAdapter), "\t"); return new OTRemoteSql<>(eventloop, executor, otSystem, listAdapter, dataSource); } public OTRemoteSql<D> withCreatedBy(String createdBy) { this.createdBy = createdBy; return this; } public OTRemoteSql<D> withCustomTableNames(String tableRevision, String tableDiffs, @Nullable String tableBackup) { this.tableRevision = tableRevision; this.tableDiffs = tableDiffs; this.tableBackup = tableBackup; return this; } public DataSource getDataSource() { return dataSource; } public TypeAdapter<List<D>> getDiffsAdapter() { return diffsAdapter; } private String sql(String sql) { return sql .replace("{revisions}", tableRevision) .replace("{diffs}", tableDiffs) .replace("{backup}", Objects.toString(tableBackup, "")); } public void truncateTables() throws SQLException { logger.trace("Truncate tables"); try (Connection connection = dataSource.getConnection()) { Statement statement = connection.createStatement(); statement.execute(sql("TRUNCATE TABLE {diffs}")); statement.execute(sql("TRUNCATE TABLE {revisions}")); } } @Override public Stage<Integer> createCommitId() { return Stage.ofCallable(executor, () -> { logger.trace("Start Create id"); try (Connection connection = dataSource.getConnection()) { connection.setAutoCommit(true); try (PreparedStatement statement = connection.prepareStatement( sql("INSERT INTO {revisions} (type, created_by) VALUES (?, ?)"), Statement.RETURN_GENERATED_KEYS)) { statement.setString(1, "NEW"); statement.setString(2, createdBy); statement.executeUpdate(); ResultSet generatedKeys = statement.getGeneratedKeys(); generatedKeys.next(); int id = generatedKeys.getInt(1); logger.trace("Id created: {}", id); return id; } } }).whenComplete(stageCreateCommitId.recordStats()); } private String toJson(List<D> diffs) throws IOException { return GsonAdapters.toJson(diffsAdapter, diffs); } @SuppressWarnings("unchecked") private List<D> fromJson(String json) throws IOException { return GsonAdapters.fromJson(diffsAdapter, json); } private static String in(int n) { return nCopies(n, "?").stream().collect(joining(", ", "(", ")")); } public Stage<Void> push(OTCommit<Integer, D> commit) { return push(singletonList(commit)); } @Override public Stage<Void> push(Collection<OTCommit<Integer, D>> commits) { if (commits.isEmpty()) return Stage.of(null); return Stage.ofCallable(executor, () -> { logger.trace("Push {} commits: {}", commits.size(), commits.stream().map(OTCommit::idsToString).collect(toList())); try (Connection connection = dataSource.getConnection()) { connection.setAutoCommit(false); for (OTCommit<Integer, D> commit : commits) { for (Integer parentId : commit.getParents().keySet()) { List<D> diff = commit.getParents().get(parentId); try (PreparedStatement ps = connection.prepareStatement( sql("INSERT INTO {diffs}(revision_id, parent_id, diff) VALUES (?, ?, ?)"))) { ps.setInt(1, commit.getId()); ps.setInt(2, parentId); ps.setString(3, toJson(diff)); ps.executeUpdate(); } } } Set<Integer> commitIds = commits.stream().map(OTCommit::getId).collect(toSet()); Set<Integer> commitsParentIds = commits.stream().flatMap(commit -> commit.getParents().keySet().stream()).collect(toSet()); Set<Integer> headCommitIds = difference(commitIds, commitsParentIds); Set<Integer> innerCommitIds = union(commitsParentIds, difference(commitIds, headCommitIds)); if (!headCommitIds.isEmpty()) { try (PreparedStatement ps = connection.prepareStatement( sql("UPDATE {revisions} SET type='HEAD' WHERE type='NEW' AND id IN " + in(headCommitIds.size())))) { int pos = 1; for (Integer id : headCommitIds) { ps.setInt(pos++, id); } ps.executeUpdate(); } } if (!innerCommitIds.isEmpty()) { try (PreparedStatement ps = connection.prepareStatement( sql("UPDATE {revisions} SET type='INNER' WHERE id IN " + in(innerCommitIds.size())))) { int pos = 1; for (Integer id : innerCommitIds) { ps.setInt(pos++, id); } ps.executeUpdate(); } } connection.commit(); logger.trace("{} commits pushed: {}", commits.size(), commits.stream().map(OTCommit::idsToString).collect(toList())); } return (Void) null; }).whenComplete(stagePush.recordStats()); } @Override public Stage<Set<Integer>> getHeads() { return Stage.ofCallable(executor, () -> { logger.trace("Get Heads"); try (Connection connection = dataSource.getConnection()) { try (PreparedStatement ps = connection.prepareStatement( sql("SELECT id FROM {revisions} WHERE type='HEAD'"))) { ResultSet resultSet = ps.executeQuery(); Set<Integer> result = new HashSet<>(); while (resultSet.next()) { int id = resultSet.getInt(1); result.add(id); } logger.trace("Current heads: {}", result); return result; } } }).whenComplete(stageGetHeads.recordStats()); } @Override public Stage<List<D>> loadSnapshot(Integer revisionId) { logger.trace("Load snapshot: {}", revisionId); return Stage.ofCallable(executor, () -> { try (Connection connection = dataSource.getConnection()) { try (PreparedStatement ps = connection.prepareStatement( sql("SELECT snapshot FROM {revisions} WHERE id=?"))) { ps.setInt(1, revisionId); ResultSet resultSet = ps.executeQuery(); if (!resultSet.next()) throw new IOException("No snapshot for id: " + revisionId); String str = resultSet.getString(1); List<D> snapshot = str == null ? Collections.emptyList() : fromJson(str); logger.trace("Snapshot loaded: {}", revisionId); return otSystem.squash(snapshot); } } }).whenComplete(stageLoadSnapshot.recordStats()); } @Override public Stage<OTCommit<Integer, D>> loadCommit(Integer revisionId) { return Stage.ofCallable(executor, () -> { logger.trace("Start load commit: {}", revisionId); try (Connection connection = dataSource.getConnection()) { Map<Integer, List<D>> parentDiffs = new HashMap<>(); long timestamp = 0; boolean snapshot = false; try (PreparedStatement ps = connection.prepareStatement( sql("SELECT UNIX_TIMESTAMP({revisions}.timestamp) AS timestamp, {revisions}.snapshot IS NOT NULL AS snapshot, {diffs}.parent_id, {diffs}.diff " + "FROM {revisions} " + "LEFT JOIN {diffs} ON {diffs}.revision_id={revisions}.id " + "WHERE {revisions}.id=?"))) { ps.setInt(1, revisionId); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { timestamp = resultSet.getLong(1) * 1000L; snapshot = resultSet.getBoolean(2); int parentId = resultSet.getInt(3); String diffString = resultSet.getString(4); if (diffString != null) { List<D> diff = fromJson(diffString); parentDiffs.put(parentId, diff); } } } if (timestamp == 0) { throw new IOException("No commit with id: " + revisionId); } logger.trace("Finish load commit: {}, parentIds: {}", revisionId, parentDiffs.keySet()); return OTCommit.of(revisionId, parentDiffs).withCommitMetadata(timestamp, snapshot); } }).whenComplete(stageLoadCommit.recordStats()); } @Override public Stage<Void> saveSnapshot(Integer revisionId, List<D> diffs) { return Stage.ofCallable(executor, () -> { logger.trace("Start save snapshot: {}, diffs: {}", revisionId, diffs.size()); try (Connection connection = dataSource.getConnection()) { String snapshot = toJson(otSystem.squash(diffs)); try (PreparedStatement ps = connection.prepareStatement(sql("" + "UPDATE {revisions} " + "SET snapshot = ? " + "WHERE id = ?"))) { ps.setString(1, snapshot); ps.setInt(2, revisionId); ps.executeUpdate(); logger.trace("Finish save snapshot: {}, diffs: {}", revisionId, diffs.size()); return (Void) null; } } }).whenComplete(stageSaveSnapshot.recordStats()); } @Override public Stage<Void> cleanup(Integer minId) { return Stage.ofCallable(executor, () -> { logger.trace("Start cleanup: {}", minId); try (Connection connection = dataSource.getConnection()) { connection.setAutoCommit(false); try (PreparedStatement ps = connection.prepareStatement( sql("DELETE FROM {revisions} WHERE id < ?"))) { ps.setInt(1, minId); ps.executeUpdate(); } try (PreparedStatement ps = connection.prepareStatement( sql("DELETE FROM {diffs} WHERE revision_id < ?"))) { ps.setInt(1, minId); ps.executeUpdate(); } connection.commit(); logger.trace("Finish cleanup: {}", minId); } return null; }); } @Override public Stage<Void> backup(Integer checkpointId, List<D> diffs) { checkState(this.tableBackup != null); return Stage.ofCallable(executor, () -> { try (Connection connection = dataSource.getConnection()) { try (PreparedStatement statement = connection.prepareStatement( sql("INSERT INTO {backup}(id, snapshot) VALUES (?, ?)"))) { statement.setInt(1, checkpointId); statement.setString(2, toJson(diffs)); statement.executeUpdate(); return null; } } }); } @Override public Eventloop getEventloop() { return eventloop; } @JmxAttribute public StageStats getStageCreateCommitId() { return stageCreateCommitId; } @JmxAttribute public StageStats getStagePush() { return stagePush; } @JmxAttribute public StageStats getStageGetHeads() { return stageGetHeads; } @JmxAttribute public StageStats getStageLoadCommit() { return stageLoadCommit; } @JmxAttribute public StageStats getStageIsSnapshot() { return stageIsSnapshot; } @JmxAttribute public StageStats getStageLoadSnapshot() { return stageLoadSnapshot; } @JmxAttribute public StageStats getStageSaveSnapshot() { return stageSaveSnapshot; } }
package com.ecyrd.jspwiki.plugin; import java.util.Properties; import com.ecyrd.jspwiki.TestEngine; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * @author jalkanen * * @since */ public class TableOfContentsTest extends TestCase { TestEngine testEngine; /* * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); Properties props = new Properties(); props.load(TestEngine.findTestProperties()); testEngine = new TestEngine( props ); } /* * @see TestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); testEngine.deletePage( "Test" ); } public void testHeadingVariables() throws Exception { String src="[{SET foo=bar}]\n\n[{TableOfContents}]\n\n!!!Heading [{$foo}]"; testEngine.saveText( "Test", src ); String res = testEngine.getHTML( "Test" ); // FIXME: The <p> should not be here. assertEquals( "\n<p><div class=\"toc\">\n"+ "<h4>Table of Contents</h4>\n"+ "<ul>\n"+ "<li class=\"toclevel-1\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-HeadingBar\">Heading bar</a></li>\n"+ "</ul>\n</div>\n\n</p>"+ "\n<h2 id=\"section-Test-HeadingBar\">Heading bar</h2>\n", res ); } public static Test suite() { return new TestSuite( TableOfContentsTest.class ); } }
import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.ArrayList; import java.util.Iterator; import java.util.Scanner; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; import services.WebShopGrpc; import services.Webshop.Availability; import services.Webshop.Costs; import services.Webshop.Customer; import services.Webshop.ListProductsParams; import services.Webshop.Order; import services.Webshop.OrderId; import services.Webshop.Payment; import services.Webshop.Product; import services.Webshop.ProductId; import services.Webshop.Order.Status; /** * The WebShopClient that is able to request information from the WebShopServer. * * @author Tobias Freundorfer * */ public class WebShopClient { private static final Logger logger = Logger.getLogger(WebShopClient.class.getName()); /** * Channel for the connection to the server. */ private final ManagedChannel channel; /** * The blocking Stub (response is synchronous). */ private final WebShopGrpc.WebShopBlockingStub blockingStub; /** * Creates a new instance of the WebShopClient connected to the * WebShopServer. * * @param host * The hostname of the WebShopServer. * @param port * The port of the WebShopServer. */ public WebShopClient(String host, int port) { this.channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build(); this.blockingStub = WebShopGrpc.newBlockingStub(this.channel); // Check if connection was successful if(!this.pingHost(host, port, 1000)){ logger.warning("Could not establish a connection to host " + host + ":" + port); System.exit(0); } } /** * Sends the listProduct request to the WebShopServer. */ public void sendListProductsRequest() { logger.info("### Sending request for listProducts."); ListProductsParams req = ListProductsParams.newBuilder().setLimit(10).build(); Iterator<Product> it; try { it = this.blockingStub.listProducts(req); } catch (StatusRuntimeException e) { logger.warning("### RPC failed: {0}" + e.getStatus()); return; } logger.info("### Received response"); System.out.println(" while (it.hasNext()) { Product p = it.next(); System.out.println("Product: " + p.toString()); } } /** * Sends the checkAvailability request to the WebShopServer. * * @param id * The ProductId for which the availability should be requested. */ public void sendCheckAvailabilityRequest(ProductId id) { logger.info("### Sending request for checkAvailability with productId = " + id.getId()); Availability av; try { av = this.blockingStub.checkAvailability(id); } catch (StatusRuntimeException e) { logger.warning("### RPC failed: {0}" + e.getStatus()); return; } logger.info("### Received response."); System.out.println("Availability for productId " + id.getId() + " = " + av.getAvailable()); } /** * Sends the storeOrder request for the given Order. * * @param order * The order that should be stored. */ public void sendStoreOrderRequest(Order order) { logger.info("### Sending request storeOrder."); OrderId orderId = null; try { orderId = this.blockingStub.storeOrderDetails(order); } catch (StatusRuntimeException e) { logger.warning("### RPC failed: {0}" + e.getStatus()); return; } logger.info("### Received response."); System.out.println("Created new order with orderId = " + orderId.getId()); } /** * Sends the getOrderDetails request for the given orderId. * * @param id * The OrderId for which the order details should be requested. */ public void sendGetOrderRequest(OrderId id) { logger.info("### Sending request getOrderDetails for orderId = " + id.getId() + "."); Order order = null; try { order = this.blockingStub.getOrderDetails(id); } catch (StatusRuntimeException e) { logger.warning("### RPC failed: {0}" + e.getStatus()); return; } logger.info("### Received response."); if (!order.getId().isEmpty()) { System.out.println("Order:"); System.out.println(order.toString() + "\n Status: " + order.getStatus().toString()); } else { logger.warning("### Server returned empty Order."); System.out.println("Order could not be found."); } } /** * Sends the cancelOrder request for the given orderId. * * @param id * The id of the order that should be canceled. */ public void sendCancelOrderRequest(OrderId id) { logger.info("### Sending request cancelOrder with orderId = " + id.getId()); Order order = null; try { order = this.blockingStub.cancelOrder(id); } catch (StatusRuntimeException e) { logger.warning("### RPC failed: {0}" + e.getStatus()); return; } logger.info("### Received response."); if (!order.getId().isEmpty()) { System.out.println("Order:"); System.out.println(order.toString()); } else { logger.warning("### Server returned empty Order."); System.out.println("Order could not be found."); } } /** * Sends the calcTransactionCosts request for the given orderId. * * @param id * The orderId for which the transaction costs should be * calculated. */ public void sendCalcTransactionCostsRequest(OrderId id) { logger.info("### Sending request calcTransactionCosts with orderId = " + id.getId()); Costs costs = null; try { costs = this.blockingStub.calcTransactionCosts(id); } catch (StatusRuntimeException e) { logger.warning("### RPC failed: {0}" + e.getStatus()); return; } if (costs.getCosts() == 0.0) { logger.warning("### Returned costs were 0. Is the orderId valid?"); } else { System.out.println("Costs: \n " + costs.getCosts() + " EUR"); } } /** * Sends the conductPayment request for the given payment. * * @param payment * The payment that should be conducted. */ public void sendConductPaymentRequest(Payment payment) { logger.info("### Sending request for conductPayment."); Order order = null; try { order = this.blockingStub.conductPayment(payment); } catch (StatusRuntimeException e) { logger.warning("### RPC failed: {0}" + e.getStatus()); return; } if (!order.getId().isEmpty()) { System.out.println("Order:\n " + order.toString()); } else { logger.warning("### Server returned empty Order."); System.out.println("Order could not be found."); } } /** * Sends the calcShipmentCosts request for the given orderId. Shipment costs * are the total weight of all products within an order. * * @param id * The orderId of the order to calculate. */ public void sendCalcShipmentCostsRequest(OrderId id) { logger.info("### Sending request for calcShipmentCosts with orderId =" + id.getId() + "."); Costs weight = null; try { weight = this.blockingStub.calcShipmentCosts(id); } catch (StatusRuntimeException e) { logger.warning("### RPC failed: {0}" + e.getStatus()); return; } logger.info("### Received response."); if (weight.getCosts() == 0.0) { logger.warning("### Returned costs were 0. Is the orderId valid?"); } else { System.out.println("Weight: \n " + weight.getCosts() + " KG"); } } /** * Sends the shipProducts request for the given orderId. * * @param id * The orderId of the order that should be shipped. */ public void sendShipProductsRequest(OrderId id) { logger.info("### Sending request for sendShipProducts with orderId =" + id.getId() + "."); Order order = null; try { order = this.blockingStub.shipProducts(id); } catch (StatusRuntimeException e) { logger.warning("### RPC failed: {0}" + e.getStatus()); return; } logger.info("### Received response."); if (!order.getId().isEmpty()) { System.out.println("Order:\n " + order.toString()); } else { logger.warning("### Server returned empty Order."); System.out.println("Order could not be found."); } } /** * Initiates the shutdown sequence. * * @throws InterruptedException * Thrown if shutdown was interrupted. */ public void shutdown() throws InterruptedException { channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); } public static void main(String[] args) { // Read input args String hostname = ""; int port = -1; for (int i = 0; i < args.length; i++) { if (args[i].equals("-h")) { // Check if there's a following command if ((i + 1) < args.length) { hostname = args[i + 1]; i++; } else { WebShopClient.showArgsPrompt(); System.exit(0); } } if (args[i].equals("-p")) { if ((i + 1) < args.length) { try { port = Integer.parseInt(args[i + 1]); i++; } catch (NumberFormatException e) { WebShopClient.showArgsPrompt(); System.exit(0); } } else { WebShopClient.showArgsPrompt(); System.exit(0); } } } if (hostname.isEmpty() || port == -1) { WebShopClient.showArgsPrompt(); System.exit(0); } System.out.println("Connecting to " + hostname + ":" + port); WebShopClient client = new WebShopClient(hostname, port); // Loop for user input commands Scanner scanner = new Scanner(System.in); boolean receiveUserCommands = true; while (receiveUserCommands) { WebShopClient.showUserCommandPrompt(); System.out.println("\n Enter command: \n"); String command = scanner.nextLine(); if (command.equals("listProducts")) { client.sendListProductsRequest(); } else if (command.equals("shutdown")) { try { client.shutdown(); receiveUserCommands = false; } catch (InterruptedException e) { logger.warning("Client was interrupted at shutdown."); receiveUserCommands = false; } } else if (command.startsWith("checkAvailability")) { String[] arr = command.split(" "); if (arr.length != 2) { logger.warning("### Wrong syntax."); } else { client.sendCheckAvailabilityRequest(ProductId.newBuilder().setId(arr[1]).build()); } } else if (command.equals("storeOrder")) { ArrayList<ProductId> productIds = new ArrayList<>(); int amountOfProducts = 0; System.out.println("\n Enter the amount of products: "); try { amountOfProducts = Integer.parseInt(scanner.nextLine()); } catch (NumberFormatException e) { logger.warning("### Parsing was not possible. Please enter a number."); break; } for (int i = 0; i < amountOfProducts; i++) { System.out.println("\n Enter productId: "); productIds.add(ProductId.newBuilder().setId(scanner.nextLine()).build()); } String customerId = UUID.randomUUID().toString(); System.out.println("\n Enter customer firstname: "); String firstname = scanner.nextLine(); System.out.println("\n Enter customer lastname: "); String lastname = scanner.nextLine(); System.out.println("\n Enter customer shipping address: "); String shipadd = scanner.nextLine(); System.out.println("\n Enter customer payment details: "); String paymentDetails = scanner.nextLine(); Customer customer = Customer.newBuilder().setId(customerId).setFirstname(firstname) .setLastname(lastname).setShippingAddress(shipadd).setPaymentDetails(paymentDetails).build(); // Initially always status NEW String orderId = UUID.randomUUID().toString(); Order order = Order.newBuilder().setId(orderId).setStatus(Status.NEW).setCustomer(customer).build(); for (int i = 0; i < productIds.size(); i++) { order = order.toBuilder().addProducts(productIds.get(i)).build(); } client.sendStoreOrderRequest(order); } else if (command.startsWith("getOrder")) { String[] arr = command.split(" "); if (arr.length != 2) { logger.warning("### Wrong syntax."); } else { client.sendGetOrderRequest(OrderId.newBuilder().setId(arr[1]).build()); } } else if (command.startsWith("cancelOrder")) { String[] arr = command.split(" "); if (arr.length != 2) { logger.warning("### Wrong syntax."); } else { client.sendCancelOrderRequest(OrderId.newBuilder().setId(arr[1]).build()); } } else if (command.startsWith("calcTransactionCosts")) { String[] arr = command.split(" "); if (arr.length != 2) { logger.warning("### Wrong syntax."); } else { client.sendCalcTransactionCostsRequest(OrderId.newBuilder().setId(arr[1]).build()); } } else if (command.startsWith("conductPayment")) { String[] arr = command.split(" "); if (arr.length != 3) { logger.warning("### Wrong syntax."); } else { float amount = 0.0F; try { amount = Float.parseFloat(arr[2]); } catch (NumberFormatException ex) { logger.warning("### Parsing was not possible. Please enter a floating point number."); } Payment payment = Payment.newBuilder().setId(OrderId.newBuilder().setId(arr[1])).setAmount(amount) .build(); client.sendConductPaymentRequest(payment); } } else if (command.startsWith("calcShipmentCosts")) { String[] arr = command.split(" "); if (arr.length != 2) { logger.warning("### Wrong syntax."); } else { client.sendCalcShipmentCostsRequest(OrderId.newBuilder().setId(arr[1]).build()); } } else if(command.startsWith("shipProducts")){ String[] arr = command.split(" "); if (arr.length != 2) { logger.warning("### Wrong syntax."); } else { client.sendShipProductsRequest(OrderId.newBuilder().setId(arr[1]).build()); } } } scanner.close(); } /** * Shows the command prompt for user commands. */ private static void showUserCommandPrompt() { System.out.println("Available Commands: \n"); System.out.println("listProducts \n\t Lists all the products registered in the servers database."); System.out.println("checkAvailability <ProductId> \n\t Checks the availability for the given productId"); System.out.println("storeOrder \n\t Interactively creates a new Order and stores it."); System.out.println("getOrder <OrderId> \n\t Returns an order for the given orderId."); System.out.println("cancelOrder <OrderId> \n\t Cancels an Order for the given orderId."); System.out .println("calcTransactionCosts <OrderId> \n\t Calculates the transaction costs for the given orderId."); System.out.println( "conductPayment <OrderId> <Amount> \n\t Conducts the paymont for the given orderId and amount."); System.out.println("calcShipmentCosts <OrderId> \n\t Calculates the shipment costs for the given orderId."); System.out.println("shipProducts <OrderId> \n\t Ships all products for the given orderId."); System.out.println("shutdown \n\t Terminates this client and closes all connections."); } /** * Shows the args prompt for startup arguments. */ private static void showArgsPrompt() { System.out.println("Usage: \n <appname> command argument"); System.out.println("-h \t The host address to connect to. \n -p \t The port to connect to."); } /** * Pings the given host and returns whether it has responded. * @param host The host to ping to. * @param port The port to ping to. * @param timeout The timeout in ms. * @return */ private boolean pingHost(String host, int port, int timeout) { try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(host, port), timeout); return true; } catch (IOException e) { return false; } } }
package io.github.ihongs.serv.matrix; import io.github.ihongs.Cnst; import io.github.ihongs.Core; import io.github.ihongs.HongsException; import io.github.ihongs.action.ActionHelper; import io.github.ihongs.cmdlet.CmdletHelper; import io.github.ihongs.cmdlet.anno.Cmdlet; import io.github.ihongs.db.Table; import io.github.ihongs.db.link.Loop; import io.github.ihongs.util.Synt; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * * @author hong */ @Cmdlet("matrix.data") public class DataCmdlet { @Cmdlet("revert") public static void revert(String[] args) throws HongsException, InterruptedException { Map opts = CmdletHelper.getOpts(args, new String[] { "conf=s", "form=s", "user:s", "memo:s", "time:i", "!A", "?Usage: revert --conf CONF_NAME --form FORM_NAME [--time TIMESTAMP] ID0 ID1 ..." }); String conf = (String) opts.get("conf"); String form = (String) opts.get("form"); String user = (String) opts.get("user"); String memo = (String) opts.get("memo"); Set< String > ds = Synt.asSet ( opts.get("")); long ct = Synt.declare(opts.get("time"), 0L ); long dt = Core.ACTION_TIME .get() /1000; Data dr = Data.getInstance( conf,form ); form = dr.getFormId( ); if (user == null) { user = Cnst.ADM_UID; } Map sd = new HashMap(); sd.put("form_id",form); sd.put("user_id",user); sd.put("memo" ,memo); Table tb = dr.getTable(); String tn = tb.tableName ; Loop lp ; int c = 0 ; int i = 0 ; if (ct == 0) { String fa = "`a`.*" ; String fc = "COUNT(*) AS _cnt_" ; String qa = "SELECT "+fa+" FROM `"+tn+"` AS `a` WHERE `a`.`form_id` = ? AND `a`.`etime` = ?"; String qc = "SELECT "+fc+" FROM `"+tn+"` AS `a` WHERE `a`.`form_id` = ? AND `a`.`etime` = ?"; if (! ds.isEmpty() ) { c = ds.size(); qa = qa + " AND a.id IN (?)"; lp = tb.db.query(qa, 0, 0, form, 0, ds); } else { lp = tb.db.query(qa, 0, 0, form, 0 ); c = Synt .declare ( tb.db.fetchOne( qc, form, 0 ) .get("_cnt_"), 0 ); } } else { String fx = "`x`.*" ; String fa = "`a`.id, MAX(a.ctime) AS ctime" ; String fc = "COUNT(DISTINCT a.id) AS _cnt_" ; String qa = "SELECT "+fa+" FROM `"+tn+"` AS `a` WHERE `a`.`form_id` = ? AND `a`.`ctime` <= ?"; String qc = "SELECT "+fc+" FROM `"+tn+"` AS `a` WHERE `a`.`form_id` = ? AND `a`.`ctime` <= ?"; String qx = " WHERE x.id = b.id AND x.ctime = b.ctime AND x.`form_id` = ? AND x.`ctime` <= ?"; if (! ds.isEmpty() ) { c = ds.size(); qa = qa + " AND a.id IN (?)"; qx = qx + " AND x.id IN (?)"; qa = qa + " GROUP BY `a`.id"; qx = "SELECT "+fx+" FROM `"+tn+"` AS `x`, ("+qa+") AS `b` "+qx; lp = tb.db.query(qx, 0, 0, form, ct, ds, form, ct, ds); } else { qa = qa + " GROUP BY `a`.id"; qx = "SELECT "+fx+" FROM `"+tn+"` AS `x`, ("+qa+") AS `b` "+qx; lp = tb.db.query(qx, 0, 0, form, ct , form, ct ); c = Synt .declare ( tb.db.fetchOne( qc, form, ct ) .get("_cnt_"), 0 ); } } long tm = System.currentTimeMillis(); CmdletHelper.progres(tm, c, i); dr.begin( ); for(Map od : lp ) { String id = ( String ) od.get( Cnst.ID_KEY ); if (Synt.declare(od.get("etime"), 0L) != 0L) { if (Synt.declare(od.get("state"), 1 ) >= 1 ) { sd.put ("rtime", od.get("ctime")); dr.redo( dt, id, sd ); } else { dr.drop( dt, id, sd ); }} else { if (Synt.declare(od.get("state"), 1 ) >= 1 ) { od = Synt.toMap( od.get( "data")); od.putAll(sd); dr.set(id,od); } else { dr.delDoc(id); }} ds.remove(id); CmdletHelper.progres(tm, c, ++ i); // if (i % 500 == 0) { // dr.commit( ); } for(String id:ds) { dr.delDoc(id); CmdletHelper.progres(tm, c, ++ i); // if (i % 500 == 0) { // dr.commit( ); } dr.commit( ); CmdletHelper.progred( ); CmdletHelper.println("Revert "+i+" item(s) in "+dr.getDbName()); } @Cmdlet("import") public static void impart(String[] args) throws HongsException, InterruptedException { Map opts = CmdletHelper.getOpts(args, new String[] { "conf=s", "form=s", "user:s", "memo:s", "!A", "?Usage: import --conf CONF_NAME --form FORM_NAME DATA DATA ..." }); String conf = (String) opts.get("conf"); String form = (String) opts.get("form"); String user = (String) opts.get("user"); String memo = (String) opts.get("memo"); long dt = Core.ACTION_TIME .get() /1000; Data dr = Data.getInstance( conf,form ); form = dr.getFormId( ); if (user == null) { user = Cnst.ADM_UID; } dr.begin(); int i = 0; String[] dats = (String[]) opts.get(""); for(String text : dats) { String id ; Map data = data(text); id = (String) data.get(Cnst.ID_KEY); if (id == null) { id = Core.newIdentity( ); data.put(Cnst.ID_KEY, id); } data.put("form_id", form); data.put("user_id", user); data.put("memo" , memo); i += dr.save(dt,id, data); // if (i % 500 == 0) { // dr.commit( ); } dr.commit( ); CmdletHelper.println("Import "+i+" item(s) to "+dr.getDbName()); } @Cmdlet("update") public static void update(String[] args) throws HongsException, InterruptedException { Map opts = CmdletHelper.getOpts(args, new String[] { "conf=s", "form=s", "user:s", "memo:s", "!A", "?Usage: update --conf CONF_NAME --form FORM_NAME FIND DATA" }); String conf = (String) opts.get("conf"); String form = (String) opts.get("form"); String user = (String) opts.get("user"); String memo = (String) opts.get("memo"); long dt = Core.ACTION_TIME .get() /1000; Data dr = Data.getInstance( conf,form ); form = dr.getFormId( ); if (user == null) { user = Cnst.ADM_UID; } String[] dats = (String[]) opts.get(""); if (dats.length < 2) { CmdletHelper.println("Need FIND DATA."); return; } Map rd = data(dats[0]); Map sd = data(dats[1]); sd.put("form_id",form); sd.put("user_id",user); sd.put("memo" ,memo); rd.put(Cnst.RB_KEY , Synt.setOf(Cnst.ID_KEY)); dr.begin(); int i = 0; for(Map od : dr.search(rd, 0, 0)) { String id = (String) od.get(Cnst.ID_KEY) ; i += dr.save(dt, id, sd); // if (i % 500 == 0) { // dr.commit( ); } dr.commit( ); CmdletHelper.println("Update "+i+" item(s) in "+dr.getDbName()); } @Cmdlet("delete") public static void delete(String[] args) throws HongsException, InterruptedException { Map opts = CmdletHelper.getOpts(args, new String[] { "conf=s", "form=s", "user:s", "memo:s", "!A", "?Usage: delete --conf CONF_NAME --form FORM_NAME FIND_TERM" }); String conf = (String) opts.get("conf"); String form = (String) opts.get("form"); String user = (String) opts.get("user"); String memo = (String) opts.get("memo"); long dt = Core.ACTION_TIME .get() /1000; Data dr = Data.getInstance( conf,form ); form = dr.getFormId( ); if (user == null) { user = Cnst.ADM_UID; } String[] dats = (String[]) opts.get(""); if (dats.length < 1) { CmdletHelper.println("Need FIND_TERM."); return; } Map rd = data(dats[0]); Map sd = new HashMap(); sd.put("form_id",form); sd.put("user_id",user); sd.put("memo" ,memo); rd.put(Cnst.RB_KEY , Synt.setOf(Cnst.ID_KEY)); dr.begin(); int i = 0; for(Map od : dr.search(rd, 0, 0)) { String id = (String) od.get(Cnst.ID_KEY) ; i += dr.drop(dt, id, sd); // if (i % 500 == 0) { // dr.commit( ); } dr.commit( ); CmdletHelper.println("Delete "+i+" item(s) in "+dr.getDbName()); } @Cmdlet("search") public static void search(String[] args) throws HongsException { Map opts = CmdletHelper.getOpts(args, new String[] { "conf=s", "form=s", "!A", "?Usage: search --conf CONF_NAME --form FORM_NAME FIND_TERM" }); String conf = (String) opts.get("conf"); String form = (String) opts.get("form"); Data dr = Data.getInstance( conf,form ); String[] dats = (String[]) opts.get(""); if (dats.length < 1) { CmdletHelper.println("Need FIND_TERM."); return; } Map rd = data(dats[0]); for(Map od : dr.search(rd, 0, 0)) { CmdletHelper.preview(od); } } private static Map data(String text) { text = text.trim(); if (text.startsWith("<") && text.endsWith(">")) { throw new UnsupportedOperationException("Unsupported html: "+ text); } else if (text.startsWith("[") && text.endsWith("]")) { throw new UnsupportedOperationException("Unsupported list: "+ text); } else if (text.startsWith("{") && text.endsWith("}")) { return (Map) io.github.ihongs.util.Data.toObject(text); } else { return ActionHelper.parseQuery(text); } } }
package io.airlift.http.client; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.google.common.collect.ListMultimap; import com.google.common.io.ByteStreams; import com.google.common.util.concurrent.ThreadFactoryBuilder; import io.airlift.testing.Assertions; import io.airlift.units.Duration; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.server.ssl.SslSelectChannelConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.nio.channels.UnresolvedAddressException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import static com.google.common.base.Throwables.propagate; import static io.airlift.http.client.Request.Builder.prepareDelete; import static io.airlift.http.client.Request.Builder.prepareGet; import static io.airlift.http.client.Request.Builder.preparePost; import static io.airlift.http.client.Request.Builder.preparePut; import static io.airlift.testing.Assertions.assertInstanceOf; import static io.airlift.testing.Assertions.assertLessThan; import static io.airlift.testing.Closeables.closeQuietly; import static io.airlift.units.Duration.nanosSince; import static java.lang.String.format; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.testng.Assert.fail; public abstract class AbstractHttpClientTest { protected EchoServlet servlet; protected Server server; protected URI baseURI; private String scheme = "http"; private String host = "127.0.0.1"; private String keystore = null; protected AbstractHttpClientTest() { } protected AbstractHttpClientTest(String host, String keystore) { scheme = "https"; this.host = host; this.keystore = keystore; } public abstract <T, E extends Exception> T executeRequest(Request request, ResponseHandler<T, E> responseHandler) throws Exception; public abstract <T, E extends Exception> T executeRequest(HttpClientConfig config, Request request, ResponseHandler<T, E> responseHandler) throws Exception; @BeforeMethod public void abstractSetup() throws Exception { servlet = new EchoServlet(); int port; try (ServerSocket socket = new ServerSocket()) { socket.bind(new InetSocketAddress(0)); port = socket.getLocalPort(); } baseURI = new URI(scheme, null, host, port, null, null, null); Server server = new Server(); server.setSendServerVersion(false); SelectChannelConnector httpConnector; if (keystore != null) { SslContextFactory sslContextFactory = new SslContextFactory(keystore); sslContextFactory.setKeyStorePassword("changeit"); httpConnector = new SslSelectChannelConnector(sslContextFactory); } else { httpConnector = new SelectChannelConnector(); } httpConnector.setName(scheme); httpConnector.setPort(port); server.addConnector(httpConnector); ServletHolder servletHolder = new ServletHolder(servlet); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
package com.codenvy.im; import com.codenvy.im.artifacts.Artifact; import com.codenvy.im.restlet.InstallationManager; import javax.annotation.Nullable; import java.io.IOException; import java.nio.file.Path; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import static java.nio.file.Files.exists; import static java.nio.file.Files.size; /** * @author Alexander Reshetnyak */ public class DownloadingDescriptor { private final Map<Path, Long> artifacts; private final long totalSize; private final AtomicReference<String> downloadResult; public DownloadingDescriptor(Map<Path, Long> artifacts) { this.artifacts = artifacts; this.downloadResult = new AtomicReference<>(); long tSize = 0; for (Long l : this.artifacts.values()) { tSize += l; } this.totalSize = tSize; } /** * Get total size in bytes of artifacts these will downloaded. * * @return long */ public long getTotalSize() { return totalSize; } /** * Get downloaded bytes of artifacts. * * @return long * @throws IOException */ public long getDownloadedSize() throws IOException { long downloadedSize = 0; for (Path path : artifacts.keySet()) { if (exists(path)) { downloadedSize += size(path); } } return downloadedSize; } /** * Create DownloadingDescriptor for specific artifact. * * @param artifact * Artifact * @param version * String * @param manager * InstallationManager * @return DownloadingDescriptor * @throws IOException */ public static DownloadingDescriptor valueOf(Artifact artifact, String version, InstallationManager manager) throws IOException { Map<Path, Long> m = new LinkedHashMap<>(); m.put(manager.getLocalPath(artifact, version), manager.getSize(artifact, version)); return new DownloadingDescriptor(m); } /** * Create DownloadingDescriptor for specific artifact. * * @param artifacts * Map with artifacts. * @param manager * InstallationManager * @return DownloadingDescriptor * @throws IOException */ public static DownloadingDescriptor valueOf(Map<Artifact, String> artifacts, InstallationManager manager) throws IOException { Map<Path, Long> m = new LinkedHashMap<>(); for (Map.Entry<Artifact, String> e : artifacts.entrySet()) { Artifact artifact = e.getKey(); String version = e.getValue(); m.put(manager.getLocalPath(artifact, version), manager.getSize(artifact, version)); } return new DownloadingDescriptor(m); } /** * @return String * The JSON with result of download. */ @Nullable public String getDownloadResult() { return downloadResult.get(); } /** * Set Result of download. * * @param downloadResult * String, the JSON with result of download. */ public void setDownloadResult(String downloadResult) { this.downloadResult.set(downloadResult); } }
package org.flymine.objectstore.dummy; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import org.flymine.objectstore.*; import org.flymine.objectstore.query.*; import org.flymine.sql.query.ExplainResult; /** * Generate dummy Results from a query. Used for testing purposes. * * @author Andrew Varley */ public class ObjectStoreDummyImpl extends ObjectStoreAbstractImpl { private List rows = new ArrayList(); private int resultsSize = 0; private int executeTime = 10; private int executeCalls = 0; private int poisonRowNo = -1; /** * Construct an ObjectStoreDummyImpl */ public ObjectStoreDummyImpl() { } /** * Set the max offset allowed * @param offset the max offset allowed in queries */ public void setMaxOffset(int offset) { this.maxOffset = offset; } /** * Set the max limit allowed * @param limit the max limit allowed in queries */ public void setMaxLimit(int limit) { this.maxLimit = limit; } /** * Set the max time allowed * @param time the max time allowed for queries */ public void setMaxTime(int time) { this.maxTime = time; } /** * Sets a row number to throw an ObjectStoreException on. * * @param row the row which, if accessed will throw an ObjectStoreException */ public void setPoisonRowNo(int row) { poisonRowNo = row; } /** * Execute a Query on this ObjectStore * * @param q the Query to execute * @return the results of the Query * @throws ObjectStoreException if an error occurs during the running of the Query */ public Results execute(Query q) throws ObjectStoreException { Results res = new Results(q, this); return res; } /** * Execute a Query on this ObjectStore, asking for a certain range of rows to be returned. * This will usually only be called by the Results object returned from * <code>execute(Query q)</code>. * * @param q the Query to execute * @param start the start row * @param limit the maximum numberof rows to be returned * @return a list of ResultsRows * @throws ObjectStoreException if an error occurs during the running of the Query */ public List execute(Query q, int start, int limit) throws ObjectStoreException { checkStartLimit(start, limit); if (executeTime > maxTime) { throw new ObjectStoreException("Query will take longer than " + maxTime); } List results = new ArrayList(); // If we are asking for rows completely outside resultsSize, throw ObjectStoreException if (start > resultsSize) { return new ArrayList(); //throw new ArrayIndexOutOfBoundsException("Start row outside results size"); } for (int i = start; ((i <= (start + limit - 1)) && (i < resultsSize)); i++) { if (i == poisonRowNo) { throw new ObjectStoreException("Poison row number " + i + " reached"); } if (i < rows.size()) { results.add(rows.get(i)); } else { results.add(getRow(q)); } } executeCalls++; return results; } /** * Adds a row to be returned * * @param row a row to be returned */ public void addRow(ResultsRow row) { rows.add(row); } /** * Set the number of rows to be contained in the returned Results object * * @param size the number of rows in the returned Results object */ public void setResultsSize(int size) { this.resultsSize = size; } /** * Set the time it will take to do an execute * * @param time the time to do an execute */ public void setExecuteTime(int time) { this.executeTime = time; } /** * Gets the number of execute calls made to this ObjectStore * * @return the number of execute calls made (not including the initial no-argument call) */ public int getExecuteCalls() { return executeCalls; } /** * Gets the next row to be returned. * * @param q the Query to return results for * @throws ObjectStoreException if a class cannot be instantiated */ private ResultsRow getRow(Query q) throws ObjectStoreException { ResultsRow row; row = new ResultsRow(); List classes = q.getSelect(); Iterator i = classes.iterator(); while (i.hasNext()) { QueryNode qn = (QueryNode) i.next(); Object obj = null; if (qn instanceof QueryClass) { try { obj = ((QueryClass) qn).getType().newInstance(); } catch (Exception e) { throw new ObjectStoreException("Cannot instantiate class " + ((QueryClass) qn).getType().getName(), e); } } else { // Either a function, expression or Field obj = new Integer(1); } row.add(obj); } return row; } /** * Returns an empty ExplainResult object * * @param q the query to estimate rows for * @return parsed results of EXPLAIN * @throws ObjectStoreException if an error occurs explining the query */ public ExplainResult estimate(Query q) throws ObjectStoreException { return new ExplainResult(); } /** * returns an empty ExplainResult object * * @param q the query to explain * @param start first row required, numbered from zero * @param limit the maximum number of rows to be returned * @return parsed results of EXPLAIN * @throws ObjectStoreException if an error occurs explining the query */ public ExplainResult estimate(Query q, int start, int limit) throws ObjectStoreException { return new ExplainResult(); } /** * return the resultsSize parameter that simulates number of rows returned from query * * @param q Flymine Query on which to run COUNT(*) * @return the number of rows to be produced by query */ public int count(Query q) { return this.resultsSize; } }
package org.intermine.objectstore.intermine; import junit.framework.Test; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Map; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.Vector; import java.util.List; import java.util.ArrayList; import org.intermine.metadata.Model; import org.intermine.objectstore.Failure; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStoreFactory; import org.intermine.objectstore.SetupDataTestCase; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryValue; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryExpression; import org.intermine.objectstore.query.QueryFunction; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.BagConstraint; import org.intermine.sql.Database; import org.intermine.sql.DatabaseFactory; import org.intermine.testing.OneTimeTestCase; import org.intermine.util.TypeUtil; import org.intermine.model.testmodel.*; public class SqlGeneratorTest extends SetupDataTestCase { protected static Database db; protected static HashMap results2 = new HashMap(); public SqlGeneratorTest(String arg) { super(arg); } public static Test suite() { return OneTimeTestCase.buildSuite(SqlGeneratorTest.class); } public static void oneTimeSetUp() throws Exception { SetupDataTestCase.oneTimeSetUp(); setUpResults(); db = DatabaseFactory.getDatabase("db.unittest"); } public static void setUpResults() throws Exception { results.put("SelectSimpleObject", "SELECT intermine_Alias.OBJECT AS \"intermine_Alias\", intermine_Alias.id AS \"intermine_Aliasid\" FROM Company AS intermine_Alias ORDER BY intermine_Alias.id"); results2.put("SelectSimpleObject", Collections.singleton("Company")); results.put("SubQuery", "SELECT DISTINCT intermine_All.intermine_Arrayname AS a1_, intermine_All.intermine_Alias AS \"intermine_Alias\" FROM (SELECT DISTINCT intermine_Array.OBJECT AS intermine_Array, intermine_Array.CEOId AS intermine_ArrayCEOId, intermine_Array.addressId AS intermine_ArrayaddressId, intermine_Array.id AS intermine_Arrayid, intermine_Array.name AS intermine_Arrayname, intermine_Array.vatNumber AS intermine_ArrayvatNumber, 5 AS intermine_Alias FROM Company AS intermine_Array) AS intermine_All ORDER BY intermine_All.intermine_Arrayname, intermine_All.intermine_Alias"); results2.put("SubQuery", Collections.singleton("Company")); results.put("WhereSimpleEquals", "SELECT DISTINCT a1_.name AS a2_ FROM Company AS a1_ WHERE a1_.vatNumber = 1234 ORDER BY a1_.name"); results2.put("WhereSimpleEquals", Collections.singleton("Company")); results.put("WhereSimpleNotEquals", "SELECT DISTINCT a1_.name AS a2_ FROM Company AS a1_ WHERE a1_.vatNumber != 1234 ORDER BY a1_.name"); results2.put("WhereSimpleNotEquals", Collections.singleton("Company")); results.put("WhereSimpleNegEquals", "SELECT DISTINCT a1_.name AS a2_ FROM Company AS a1_ WHERE a1_.vatNumber != 1234 ORDER BY a1_.name"); results2.put("WhereSimpleNegEquals", Collections.singleton("Company")); results.put("WhereSimpleLike", "SELECT DISTINCT a1_.name AS a2_ FROM Company AS a1_ WHERE a1_.name LIKE 'Company%' ORDER BY a1_.name"); results2.put("WhereSimpleLike", Collections.singleton("Company")); results.put("WhereEqualsString", "SELECT DISTINCT a1_.name AS a2_ FROM Company AS a1_ WHERE a1_.name = 'CompanyA' ORDER BY a1_.name"); results2.put("WhereEqualsString", Collections.singleton("Company")); results.put("WhereAndSet", "SELECT DISTINCT a1_.name AS a2_ FROM Company AS a1_ WHERE (a1_.name LIKE 'Company%' AND a1_.vatNumber > 2000) ORDER BY a1_.name"); results2.put("WhereAndSet", Collections.singleton("Company")); results.put("WhereOrSet", "SELECT DISTINCT a1_.name AS a2_ FROM Company AS a1_ WHERE (a1_.name LIKE 'CompanyA%' OR a1_.vatNumber > 2000) ORDER BY a1_.name"); results2.put("WhereOrSet", Collections.singleton("Company")); results.put("WhereNotSet", "SELECT DISTINCT a1_.name AS a2_ FROM Company AS a1_ WHERE ( NOT (a1_.name LIKE 'Company%' AND a1_.vatNumber > 2000)) ORDER BY a1_.name"); results2.put("WhereNotSet", Collections.singleton("Company")); results.put("WhereSubQueryField", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a1_.name AS orderbyfield0 FROM Department AS a1_ WHERE a1_.name IN (SELECT DISTINCT a1_.name FROM Department AS a1_) ORDER BY a1_.name, a1_.id"); results2.put("WhereSubQueryField", Collections.singleton("Department")); results.put("WhereSubQueryClass", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Company AS a1_ WHERE a1_.id IN (SELECT DISTINCT a1_.id FROM Company AS a1_ WHERE a1_.name = 'CompanyA') ORDER BY a1_.id"); results2.put("WhereSubQueryClass", Collections.singleton("Company")); results.put("WhereNotSubQueryClass", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Company AS a1_ WHERE a1_.id NOT IN (SELECT DISTINCT a1_.id FROM Company AS a1_ WHERE a1_.name = 'CompanyA') ORDER BY a1_.id"); results2.put("WhereNotSubQueryClass", Collections.singleton("Company")); results.put("WhereNegSubQueryClass", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Company AS a1_ WHERE a1_.id NOT IN (SELECT DISTINCT a1_.id FROM Company AS a1_ WHERE a1_.name = 'CompanyA') ORDER BY a1_.id"); results2.put("WhereNegSubQueryClass", Collections.singleton("Company")); results.put("WhereClassClass", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id FROM Company AS a1_, Company AS a2_ WHERE a1_.id = a2_.id ORDER BY a1_.id, a2_.id"); results2.put("WhereClassClass", Collections.singleton("Company")); results.put("WhereNotClassClass", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id FROM Company AS a1_, Company AS a2_ WHERE a1_.id != a2_.id ORDER BY a1_.id, a2_.id"); results2.put("WhereNotClassClass", Collections.singleton("Company")); results.put("WhereNegClassClass", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id FROM Company AS a1_, Company AS a2_ WHERE a1_.id != a2_.id ORDER BY a1_.id, a2_.id"); results2.put("WhereNegClassClass", Collections.singleton("Company")); Integer id1 = (Integer) TypeUtil.getFieldValue(data.get("CompanyA"), "id"); results.put("WhereClassObject", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Company AS a1_ WHERE a1_.id = " + id1 + " ORDER BY a1_.id"); results2.put("WhereClassObject", Collections.singleton("Company")); results.put("Contains11", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id FROM Department AS a1_, Manager AS a2_ WHERE (a1_.managerId = a2_.id AND a1_.name = 'DepartmentA1') ORDER BY a1_.id, a2_.id"); results2.put("Contains11", new HashSet(Arrays.asList(new String[] {"Department", "Manager"}))); results.put("ContainsNot11", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id FROM Department AS a1_, Manager AS a2_ WHERE (a1_.managerId != a2_.id AND a1_.name = 'DepartmentA1') ORDER BY a1_.id, a2_.id"); results2.put("ContainsNot11", new HashSet(Arrays.asList(new String[] {"Department", "Manager"}))); results.put("ContainsNeg11", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id FROM Department AS a1_, Manager AS a2_ WHERE (a1_.managerId != a2_.id AND a1_.name = 'DepartmentA1') ORDER BY a1_.id, a2_.id"); results2.put("ContainsNeg11", new HashSet(Arrays.asList(new String[] {"Department", "Manager"}))); results.put("Contains1N", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id FROM Company AS a1_, Department AS a2_ WHERE (a1_.id = a2_.companyId AND a1_.name = 'CompanyA') ORDER BY a1_.id, a2_.id"); results2.put("Contains1N", new HashSet(Arrays.asList(new String[] {"Department", "Company"}))); results.put("ContainsN1", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id FROM Department AS a1_, Company AS a2_ WHERE (a1_.companyId = a2_.id AND a2_.name = 'CompanyA') ORDER BY a1_.id, a2_.id"); results2.put("ContainsN1", new HashSet(Arrays.asList(new String[] {"Department", "Company"}))); results.put("ContainsMN", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id FROM Contractor AS a1_, Company AS a2_, CompanysContractors AS indirect0 WHERE ((a1_.id = indirect0.Companys AND indirect0.Contractors = a2_.id) AND a1_.name = 'ContractorA') ORDER BY a1_.id, a2_.id"); results2.put("ContainsMN", new HashSet(Arrays.asList(new String[] {"Contractor", "Company", "CompanysContractors"}))); results.put("ContainsDuplicatesMN", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id FROM Contractor AS a1_, Company AS a2_, OldComsOldContracts AS indirect0 WHERE (a1_.id = indirect0.OldComs AND indirect0.OldContracts = a2_.id) ORDER BY a1_.id, a2_.id"); results2.put("ContainsDuplicatesMN", new HashSet(Arrays.asList(new String[] {"Contractor", "Company", "OldComsOldContracts"}))); id1 = (Integer) TypeUtil.getFieldValue(data.get("EmployeeA1"), "id"); results.put("ContainsObject", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Department AS a1_ WHERE a1_.managerId = " + id1 + " ORDER BY a1_.id"); results2.put("ContainsObject", Collections.singleton("Department")); results.put("SimpleGroupBy", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, COUNT(*) AS a2_ FROM Company AS a1_, Department AS a3_ WHERE a1_.id = a3_.companyId GROUP BY a1_.OBJECT, a1_.CEOId, a1_.addressId, a1_.id, a1_.name, a1_.vatNumber ORDER BY a1_.id, COUNT(*)"); results2.put("SimpleGroupBy", new HashSet(Arrays.asList(new String[] {"Department", "Company"}))); results.put("MultiJoin", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id, a3_.OBJECT AS a3_, a3_.id AS a3_id, a4_.OBJECT AS a4_, a4_.id AS a4_id FROM Company AS a1_, Department AS a2_, Manager AS a3_, Address AS a4_ WHERE (a1_.id = a2_.companyId AND a2_.managerId = a3_.id AND a3_.addressId = a4_.id AND a3_.name = 'EmployeeA1') ORDER BY a1_.id, a2_.id, a3_.id, a4_.id"); results2.put("MultiJoin", new HashSet(Arrays.asList(new String[] {"Department", "Manager", "Company", "Address"}))); results.put("SelectComplex", "SELECT DISTINCT (AVG(a1_.vatNumber) + 20) AS a3_, a2_.name AS a4_, a2_.OBJECT AS a2_, a2_.id AS a2_id FROM Company AS a1_, Department AS a2_ GROUP BY a2_.OBJECT, a2_.companyId, a2_.id, a2_.managerId, a2_.name ORDER BY (AVG(a1_.vatNumber) + 20), a2_.name, a2_.id"); results2.put("SelectComplex", new HashSet(Arrays.asList(new String[] {"Department", "Company"}))); results.put("SelectClassAndSubClasses", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a1_.name AS orderbyfield0 FROM Employee AS a1_ ORDER BY a1_.name, a1_.id"); results2.put("SelectClassAndSubClasses", Collections.singleton("Employee")); results.put("SelectInterfaceAndSubClasses", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Employable AS a1_ ORDER BY a1_.id"); results2.put("SelectInterfaceAndSubClasses", Collections.singleton("Employable")); results.put("SelectInterfaceAndSubClasses2", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM RandomInterface AS a1_ ORDER BY a1_.id"); results2.put("SelectInterfaceAndSubClasses2", Collections.singleton("RandomInterface")); results.put("SelectInterfaceAndSubClasses3", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM ImportantPerson AS a1_ ORDER BY a1_.id"); results2.put("SelectInterfaceAndSubClasses3", Collections.singleton("ImportantPerson")); results.put("OrderByAnomaly", "SELECT DISTINCT 5 AS a2_, a1_.name AS a3_ FROM Company AS a1_ ORDER BY a1_.name"); results2.put("OrderByAnomaly", Collections.singleton("Company")); Integer id2 = (Integer) TypeUtil.getFieldValue(data.get("CompanyA"), "id"); Integer id3 = (Integer) TypeUtil.getFieldValue(data.get("DepartmentA1"), "id"); results.put("SelectClassObjectSubquery", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Company AS a1_, Department AS a2_ WHERE (a1_.id = " + id2 + " AND a1_.id = a2_.companyId AND a2_.id IN (SELECT DISTINCT a1_.id FROM Department AS a1_ WHERE a1_.id = " + id3 + ")) ORDER BY a1_.id"); results2.put("SelectClassObjectSubquery", new HashSet(Arrays.asList(new String[] {"Department", "Company"}))); results.put("SelectUnidirectionalCollection", "SELECT DISTINCT a2_.OBJECT AS a2_, a2_.id AS a2_id FROM Company AS a1_, Secretary AS a2_, HasSecretarysSecretarys AS indirect0 WHERE (a1_.name = 'CompanyA' AND (a1_.id = indirect0.Secretarys AND indirect0.HasSecretarys = a2_.id)) ORDER BY a2_.id"); results2.put("SelectUnidirectionalCollection", new HashSet(Arrays.asList(new String[] {"Company", "Secretary", "HasSecretarysSecretarys"}))); results.put("EmptyAndConstraintSet", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Company AS a1_ WHERE true ORDER BY a1_.id"); results2.put("EmptyAndConstraintSet", Collections.singleton("Company")); results.put("EmptyOrConstraintSet", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Company AS a1_ WHERE false ORDER BY a1_.id"); results2.put("EmptyOrConstraintSet", Collections.singleton("Company")); results.put("EmptyNandConstraintSet", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Company AS a1_ WHERE false ORDER BY a1_.id"); results2.put("EmptyNandConstraintSet", Collections.singleton("Company")); results.put("EmptyNorConstraintSet", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Company AS a1_ WHERE true ORDER BY a1_.id"); results2.put("EmptyNorConstraintSet", Collections.singleton("Company")); results.put("BagConstraint", "SELECT DISTINCT Company.OBJECT AS \"Company\", Company.id AS \"Companyid\" FROM Company AS Company WHERE (Company.name IN ('CompanyA', 'goodbye', 'hello')) ORDER BY Company.id"); results2.put("BagConstraint", Collections.singleton("Company")); results.put("BagConstraint2", "SELECT DISTINCT Company.OBJECT AS \"Company\", Company.id AS \"Companyid\" FROM Company AS Company WHERE (Company.id IN (" + id2 + ")) ORDER BY Company.id"); results2.put("BagConstraint2", Collections.singleton("Company")); results.put("InterfaceField", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Employable AS a1_ WHERE a1_.name = 'EmployeeA1' ORDER BY a1_.id"); results2.put("InterfaceField", Collections.singleton("Employable")); results.put("InterfaceReference", NO_RESULT); results.put("InterfaceCollection", NO_RESULT); Set res = new HashSet(); res.add("SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a1__1.debt AS a2_, a1_.age AS a3_ FROM Employee AS a1_, Broke AS a1__1 WHERE a1_.id = a1__1.id AND (a1__1.debt > 0 AND a1_.age > 0) ORDER BY a1_.id, a1__1.debt, a1_.age"); res.add("SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a1_.debt AS a2_, a1__1.age AS a3_ FROM Broke AS a1_, Employee AS a1__1 WHERE a1_.id = a1__1.id AND (a1_.debt > 0 AND a1__1.age > 0) ORDER BY a1_.id, a1_.debt, a1__1.age"); results.put("DynamicInterfacesAttribute", res); results2.put("DynamicInterfacesAttribute", new HashSet(Arrays.asList(new String[] {"Employee", "Broke"}))); res = new HashSet(); res.add("SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Employable AS a1_, Broke AS a1__1 WHERE a1_.id = a1__1.id ORDER BY a1_.id"); res.add("SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Broke AS a1_, Employable AS a1__1 WHERE a1_.id = a1__1.id ORDER BY a1_.id"); results.put("DynamicClassInterface", res); results2.put("DynamicClassInterface", new HashSet(Arrays.asList(new String[] {"Employable", "Broke"}))); res = new HashSet(); res.add("SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id, a3_.OBJECT AS a3_, a3_.id AS a3_id FROM Department AS a1_, Broke AS a1__1, Company AS a2_, Bank AS a3_ WHERE a1_.id = a1__1.id AND (a2_.id = a1_.companyId AND a3_.id = a1__1.bankId) ORDER BY a1_.id, a2_.id, a3_.id"); res.add("SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id, a3_.OBJECT AS a3_, a3_.id AS a3_id FROM Broke AS a1_, Department AS a1__1, Company AS a2_, Bank AS a3_ WHERE a1_.id = a1__1.id AND (a2_.id = a1__1.companyId AND a3_.id = a1_.bankId) ORDER BY a1_.id, a2_.id, a3_.id"); results.put("DynamicClassRef1", res); results2.put("DynamicClassRef1", new HashSet(Arrays.asList(new String[] {"Department", "Broke", "Company", "Bank"}))); res = new HashSet(); res.add("SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id, a3_.OBJECT AS a3_, a3_.id AS a3_id FROM Department AS a1_, Broke AS a1__1, Company AS a2_, Bank AS a3_ WHERE a1_.id = a1__1.id AND (a1_.companyId = a2_.id AND a1__1.bankId = a3_.id) ORDER BY a1_.id, a2_.id, a3_.id"); res.add("SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id, a3_.OBJECT AS a3_, a3_.id AS a3_id FROM Broke AS a1_, Department AS a1__1, Company AS a2_, Bank AS a3_ WHERE a1_.id = a1__1.id AND (a1__1.companyId = a2_.id AND a1_.bankId = a3_.id) ORDER BY a1_.id, a2_.id, a3_.id"); results.put("DynamicClassRef2", res); results2.put("DynamicClassRef2", new HashSet(Arrays.asList(new String[] {"Department", "Broke", "Company", "Bank"}))); res = new HashSet(); res.add("SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id, a3_.OBJECT AS a3_, a3_.id AS a3_id FROM Company AS a1_, Bank AS a1__1, Department AS a2_, Broke AS a3_ WHERE a1_.id = a1__1.id AND (a1_.id = a2_.companyId AND a1_.id = a3_.bankId) ORDER BY a1_.id, a2_.id, a3_.id"); res.add("SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id, a3_.OBJECT AS a3_, a3_.id AS a3_id FROM Bank AS a1_, Company AS a1__1, Department AS a2_, Broke AS a3_ WHERE a1_.id = a1__1.id AND (a1_.id = a2_.companyId AND a1_.id = a3_.bankId) ORDER BY a1_.id, a2_.id, a3_.id"); results.put("DynamicClassRef3", res); results2.put("DynamicClassRef3", new HashSet(Arrays.asList(new String[] {"Department", "Broke", "Company", "Bank"}))); res = new HashSet(); res.add("SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id, a3_.OBJECT AS a3_, a3_.id AS a3_id FROM Company AS a1_, Bank AS a1__1, Department AS a2_, Broke AS a3_ WHERE a1_.id = a1__1.id AND (a2_.companyId = a1_.id AND a3_.bankId = a1_.id) ORDER BY a1_.id, a2_.id, a3_.id"); res.add("SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a2_.OBJECT AS a2_, a2_.id AS a2_id, a3_.OBJECT AS a3_, a3_.id AS a3_id FROM Bank AS a1_, Company AS a1__1, Department AS a2_, Broke AS a3_ WHERE a1_.id = a1__1.id AND (a2_.companyId = a1_.id AND a3_.bankId = a1_.id) ORDER BY a1_.id, a2_.id, a3_.id"); results.put("DynamicClassRef4", res); results2.put("DynamicClassRef4", new HashSet(Arrays.asList(new String[] {"Department", "Broke", "Company", "Bank"}))); res = new HashSet(); res.add("SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Employable AS a1_, Broke AS a1__1, HasAddress AS a2_, Broke AS a2__1 WHERE a1_.id = a1__1.id AND a2_.id = a2__1.id AND a1_.id = a2_.id ORDER BY a1_.id"); res.add("SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Employable AS a1_, Broke AS a1__1, Broke AS a2_, HasAddress AS a2__1 WHERE a1_.id = a1__1.id AND a2_.id = a2__1.id AND a1_.id = a2_.id ORDER BY a1_.id"); res.add("SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Broke AS a1_, Employable AS a1__1, HasAddress AS a2_, Broke AS a2__1 WHERE a1_.id = a1__1.id AND a2_.id = a2__1.id AND a1_.id = a2_.id ORDER BY a1_.id"); res.add("SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Broke AS a1_, Employable AS a1__1, Broke AS a2_, HasAddress AS a2__1 WHERE a1_.id = a1__1.id AND a2_.id = a2__1.id AND a1_.id = a2_.id ORDER BY a1_.id"); results.put("DynamicClassConstraint", res); results2.put("DynamicClassConstraint", new HashSet(Arrays.asList(new String[] {"Employable", "Broke", "HasAddress"}))); results.put("ContainsConstraintNull", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Employee AS a1_ WHERE a1_.addressId IS NULL ORDER BY a1_.id"); results2.put("ContainsConstraintNull", Collections.singleton("Employee")); results.put("ContainsConstraintNotNull", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Employee AS a1_ WHERE a1_.addressId IS NOT NULL ORDER BY a1_.id"); results2.put("ContainsConstraintNotNull", Collections.singleton("Employee")); results.put("SimpleConstraintNull", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Manager AS a1_ WHERE a1_.title IS NULL ORDER BY a1_.id"); results2.put("SimpleConstraintNull", Collections.singleton("Manager")); results.put("SimpleConstraintNotNull", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Manager AS a1_ WHERE a1_.title IS NOT NULL ORDER BY a1_.id"); results2.put("SimpleConstraintNotNull", Collections.singleton("Manager")); results.put("TypeCast", "SELECT DISTINCT (a1_.age)::TEXT AS a2_ FROM Employee AS a1_ ORDER BY (a1_.age)::TEXT"); results2.put("TypeCast", Collections.singleton("Employee")); results.put("IndexOf", "SELECT STRPOS(a1_.name, 'oy') AS a2_ FROM Employee AS a1_ ORDER BY STRPOS(a1_.name, 'oy')"); results2.put("IndexOf", Collections.singleton("Employee")); results.put("Substring", "SELECT SUBSTR(a1_.name, 2, 2) AS a2_ FROM Employee AS a1_ ORDER BY SUBSTR(a1_.name, 2, 2)"); results2.put("Substring", Collections.singleton("Employee")); results.put("Substring2", "SELECT SUBSTR(a1_.name, 2) AS a2_ FROM Employee AS a1_ ORDER BY SUBSTR(a1_.name, 2)"); results2.put("Substring2", Collections.singleton("Employee")); results.put("OrderByReference", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id, a1_.departmentId AS orderbyfield0 FROM Employee AS a1_ ORDER BY a1_.departmentId, a1_.id"); results2.put("OrderByReference", Collections.singleton("Employee")); results.put("FailDistinctOrder", new Failure(ObjectStoreException.class, "Field a1_.age in the ORDER BY list must be in the SELECT list, or the whole QueryClass org.intermine.model.testmodel.Employee must be in the SELECT list, or the query made non-distinct")); String largeBagConstraintText = new BufferedReader(new InputStreamReader(TruncatedSqlGeneratorTest.class.getClassLoader().getResourceAsStream("test/largeBag.sql"))).readLine(); results.put("LargeBagConstraint", largeBagConstraintText); results2.put("LargeBagConstraint", Collections.singleton("Employee")); results2.put("LargeBagConstraintUsingTable", Collections.singleton("Employee")); results.put("LargeBagConstraintUsingTable", "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Employee AS a1_ WHERE a1_.name IN (SELECT value FROM " + LARGE_BAG_TABLE_NAME + ") ORDER BY a1_.id"); } final static String LARGE_BAG_TABLE_NAME = "large_string_bag_table"; public void executeTest(String type) throws Exception { Query q = (Query) queries.get(type); Object expected = results.get(type); if (expected instanceof Failure) { try { SqlGenerator.generate(q, 0, Integer.MAX_VALUE, getSchema(), db, new HashMap()); fail(type + " was expected to fail"); } catch (Exception e) { assertEquals(type + " was expected to produce a particular exception", expected, new Failure(e)); } } else { Map bagTableNames = new HashMap(); if (type.equals("LargeBagConstraintUsingTable")) { // special case - the Map will tell generate() what table to use to find the values // of large bags Query largeBagQuery = (Query) queries.get("LargeBagConstraintUsingTable"); BagConstraint largeBagConstraint = (BagConstraint) largeBagQuery.getConstraint(); bagTableNames.put(largeBagConstraint, "large_string_bag_table"); } String generated = SqlGenerator.generate(q, 0, Integer.MAX_VALUE, getSchema(), db, bagTableNames); if (expected instanceof String) { assertEquals("", results.get(type), generated); } else if (expected instanceof Collection) { boolean hasEqual = false; Iterator expectedIter = ((Collection) expected).iterator(); while ((!hasEqual) && expectedIter.hasNext()) { String expectedString = (String) expectedIter.next(); hasEqual = expectedString.equals(generated); } assertTrue(generated, hasEqual); } else { assertTrue("No result found for " + type, false); } assertEquals(results2.get(type), SqlGenerator.findTableNames(q, getSchema())); // TODO: extend sql so that it can represent these if (!("TypeCast".equals(type) || "IndexOf".equals(type) || "Substring".equals(type) || "Substring2".equals(type) || type.startsWith("Empty") || type.startsWith("BagConstraint") || "LargeBagConstraint".equals(type))) { // And check that the SQL generated is high enough quality to be parsed by the optimiser. org.intermine.sql.query.Query sql = new org.intermine.sql.query.Query(generated); } } } public void testSelectQueryValue() throws Exception { QueryValue v1 = new QueryValue(new Integer(5)); QueryValue v2 = new QueryValue("Hello"); QueryValue v3 = new QueryValue(new Date(1046275720000l)); QueryValue v4 = new QueryValue(Boolean.TRUE); StringBuffer buffer = new StringBuffer(); SqlGenerator.queryEvaluableToString(buffer, v1, null, null); SqlGenerator.queryEvaluableToString(buffer, v2, null, null); SqlGenerator.queryEvaluableToString(buffer, v3, null, null); SqlGenerator.queryEvaluableToString(buffer, v4, null, null); assertEquals("5'Hello'1046275720000'true'", buffer.toString()); } public void testSelectQueryExpression() throws Exception { QueryValue v1 = new QueryValue(new Integer(5)); QueryValue v2 = new QueryValue(new Integer(7)); QueryExpression e1 = new QueryExpression(v1, QueryExpression.ADD, v2); QueryExpression e2 = new QueryExpression(v1, QueryExpression.SUBTRACT, v2); QueryExpression e3 = new QueryExpression(v1, QueryExpression.MULTIPLY, v2); QueryExpression e4 = new QueryExpression(v1, QueryExpression.DIVIDE, v2); StringBuffer buffer = new StringBuffer(); SqlGenerator.queryEvaluableToString(buffer, e1, null, null); SqlGenerator.queryEvaluableToString(buffer, e2, null, null); SqlGenerator.queryEvaluableToString(buffer, e3, null, null); SqlGenerator.queryEvaluableToString(buffer, e4, null, null); assertEquals("(5 + 7)(5 - 7)(5 * 7)(5 / 7)", buffer.toString()); } public void testSelectQuerySubstringExpression() throws Exception { QueryValue v1 = new QueryValue("Hello"); QueryValue v2 = new QueryValue(new Integer(3)); QueryValue v3 = new QueryValue(new Integer(5)); QueryExpression e1 = new QueryExpression(v1, v2, v3); StringBuffer buffer = new StringBuffer(); SqlGenerator.queryEvaluableToString(buffer, e1, null, null); assertEquals("SUBSTR('Hello', 3, 5)", buffer.toString()); } /* TODO public void testSelectQueryField() throws Exception { QueryClass c1 = new QueryClass(Department.class); QueryField f1 = new QueryField(c1, "name"); Query q1 = new Query(); q1.addFrom(c1); StringBuffer buffer = new StringBuffer(); SqlGenerator.queryEvaluableToString(buffer, f1, q1); assertEquals("a1_.name", buffer.toString()); } public void testSelectQueryFunction() throws Exception { QueryClass c1 = new QueryClass(Company.class); QueryField v1 = new QueryField(c1, "vatNumber"); QueryFunction f1 = new QueryFunction(); QueryFunction f2 = new QueryFunction(v1, QueryFunction.SUM); QueryFunction f3 = new QueryFunction(v1, QueryFunction.AVERAGE); QueryFunction f4 = new QueryFunction(v1, QueryFunction.MIN); QueryFunction f5 = new QueryFunction(v1, QueryFunction.MAX); Query q1 = new Query(); q1.addFrom(c1); StringBuffer buffer = new StringBuffer(); SqlGenerator.queryEvaluableToString(buffer, f1, q1); SqlGenerator.queryEvaluableToString(buffer, f2, q1); SqlGenerator.queryEvaluableToString(buffer, f3, q1); SqlGenerator.queryEvaluableToString(buffer, f4, q1); SqlGenerator.queryEvaluableToString(buffer, f5, q1); assertEquals("COUNT(*)SUM(a1_.vatNumber)AVG(a1_.vatNumber)MIN(a1_.vatNumber)MAX(a1_.vatNumber)", buffer.toString()); } */ public void testInvalidClass() throws Exception { Query q = new Query(); QueryClass c1 = new QueryClass(Company.class); q.addFrom(c1); q.addToSelect(c1); try { SqlGenerator.generate(q, 0, Integer.MAX_VALUE, new DatabaseSchema(new Model("nothing", "http: fail("Expected: ObjectStoreException"); } catch (ObjectStoreException e) { } } public void testRegisterOffset() throws Exception { DatabaseSchema schema = getSchema(); Query q = new Query(); QueryClass c1 = new QueryClass(Company.class); q.addFrom(c1); q.addToSelect(c1); assertEquals(getRegisterOffset1(), SqlGenerator.generate(q, 0, Integer.MAX_VALUE, schema, db, new HashMap())); SqlGenerator.registerOffset(q, 5, schema, db, new Integer(10), new HashMap()); assertEquals(getRegisterOffset1(), SqlGenerator.generate(q, 0, Integer.MAX_VALUE, schema, db, new HashMap())); assertEquals(getRegisterOffset2() + "a1_.id > 10 ORDER BY a1_.id OFFSET 5", SqlGenerator.generate(q, 10, Integer.MAX_VALUE, schema, db, new HashMap())); SqlGenerator.registerOffset(q, 11000, schema, db, new Integer(20), new HashMap()); assertEquals(getRegisterOffset1(), SqlGenerator.generate(q, 0, Integer.MAX_VALUE, schema, db, new HashMap())); assertEquals(getRegisterOffset2() + "a1_.id > 10 ORDER BY a1_.id OFFSET 5", SqlGenerator.generate(q, 10, Integer.MAX_VALUE, schema, db, new HashMap())); assertEquals(getRegisterOffset2() + "a1_.id > 20 ORDER BY a1_.id OFFSET 5", SqlGenerator.generate(q, 11005, Integer.MAX_VALUE, schema, db, new HashMap())); SqlGenerator.registerOffset(q, 21000, schema, db, new Integer(30), new HashMap()); assertEquals(getRegisterOffset1(), SqlGenerator.generate(q, 0, Integer.MAX_VALUE, schema, db, new HashMap())); assertEquals(getRegisterOffset2() + "a1_.id > 10 ORDER BY a1_.id OFFSET 5", SqlGenerator.generate(q, 10, Integer.MAX_VALUE, schema, db, new HashMap())); assertEquals(getRegisterOffset2() + "a1_.id > 10 ORDER BY a1_.id OFFSET 11000", SqlGenerator.generate(q, 11005, Integer.MAX_VALUE, schema, db, new HashMap())); assertEquals(getRegisterOffset2() + "a1_.id > 30 ORDER BY a1_.id OFFSET 5", SqlGenerator.generate(q, 21005, Integer.MAX_VALUE, schema, db, new HashMap())); SqlGenerator.registerOffset(q, 21005, schema, db, new Integer(31), new HashMap()); assertEquals(getRegisterOffset1(), SqlGenerator.generate(q, 0, Integer.MAX_VALUE, schema, db, new HashMap())); assertEquals(getRegisterOffset2() + "a1_.id > 10 ORDER BY a1_.id OFFSET 5", SqlGenerator.generate(q, 10, Integer.MAX_VALUE, schema, db, new HashMap())); assertEquals(getRegisterOffset2() + "a1_.id > 10 ORDER BY a1_.id OFFSET 11000", SqlGenerator.generate(q, 11005, Integer.MAX_VALUE, schema, db, new HashMap())); assertEquals(getRegisterOffset2() + "a1_.id > 30 ORDER BY a1_.id OFFSET 5", SqlGenerator.generate(q, 21005, Integer.MAX_VALUE, schema, db, new HashMap())); SqlGenerator.registerOffset(q, 11002, schema, db, new Integer(29), new HashMap()); assertEquals(getRegisterOffset1(), SqlGenerator.generate(q, 0, Integer.MAX_VALUE, schema, db, new HashMap())); assertEquals(getRegisterOffset2() + "a1_.id > 10 ORDER BY a1_.id OFFSET 5", SqlGenerator.generate(q, 10, Integer.MAX_VALUE, schema, db, new HashMap())); assertEquals(getRegisterOffset2() + "a1_.id > 10 ORDER BY a1_.id OFFSET 11000", SqlGenerator.generate(q, 11005, Integer.MAX_VALUE, schema, db, new HashMap())); assertEquals(getRegisterOffset2() + "a1_.id > 30 ORDER BY a1_.id OFFSET 5", SqlGenerator.generate(q, 21005, Integer.MAX_VALUE, schema, db, new HashMap())); SqlGenerator.registerOffset(q, 101000, schema, db, new Integer(40), new HashMap()); assertEquals(getRegisterOffset1(), SqlGenerator.generate(q, 0, Integer.MAX_VALUE, schema, db, new HashMap())); assertEquals(getRegisterOffset2() + "a1_.id > 10 ORDER BY a1_.id OFFSET 5", SqlGenerator.generate(q, 10, Integer.MAX_VALUE, schema, db, new HashMap())); assertEquals(getRegisterOffset2() + "a1_.id > 10 ORDER BY a1_.id OFFSET 11000", SqlGenerator.generate(q, 11005, Integer.MAX_VALUE, schema, db, new HashMap())); assertEquals(getRegisterOffset2() + "a1_.id > 10 ORDER BY a1_.id OFFSET 21000", SqlGenerator.generate(q, 21005, Integer.MAX_VALUE, schema, db, new HashMap())); assertEquals(getRegisterOffset2() + "a1_.id > 40 ORDER BY a1_.id OFFSET 5", SqlGenerator.generate(q, 101005, Integer.MAX_VALUE, schema, db, new HashMap())); } protected DatabaseSchema getSchema() { return new DatabaseSchema(model, Collections.EMPTY_LIST); } public String getRegisterOffset1() { return "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Company AS a1_ ORDER BY a1_.id"; } public String getRegisterOffset2() { return "SELECT DISTINCT a1_.OBJECT AS a1_, a1_.id AS a1_id FROM Company AS a1_ WHERE "; } }
package com.iterable.iterableapi; import android.app.Dialog; import android.content.Context; import android.graphics.Color; import android.graphics.Point; import android.util.TypedValue; import android.view.Display; import android.view.Gravity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class IterableInAppManager { static final String TAG = "IterableInAppManager"; /** * Displays an InApp Notification from the dialogOptions; with a click callback handler. * @param context * @param dialogOptions * @param clickCallback */ public static void showNotification(Context context, JSONObject dialogOptions, String messageId, IterableHelper.IterableActionHandler clickCallback) { if(dialogOptions != null) { String type = dialogOptions.optString(IterableConstants.ITERABLE_IN_APP_TYPE); if (type.equalsIgnoreCase(IterableConstants.ITERABLE_IN_APP_TYPE_FULL)) { showFullScreenDialog(context, dialogOptions, messageId, clickCallback); } else { showNotificationDialog(context, dialogOptions, messageId, clickCallback); } } else { IterableLogger.d(TAG, "In-App notification not displayed: showNotification must contain valid dialogOptions"); } } /** * Creates and shows a pop-up InApp Notification; with a click callback handler. * @param context * @param dialogParameters * @param clickCallback */ static void showNotificationDialog(Context context, JSONObject dialogParameters, String messageId, IterableHelper.IterableActionHandler clickCallback) { Dialog dialog = new Dialog(context, android.R.style.Theme_Material_NoActionBar); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCanceledOnTouchOutside(true); dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); Window window = dialog.getWindow(); lp.copyFrom(window.getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; lp.dimAmount = .8f; lp.gravity = getNotificationLocation(dialogParameters.optString(IterableConstants.ITERABLE_IN_APP_TYPE)); window.setAttributes(lp); LinearLayout verticalLayout = new LinearLayout(context); verticalLayout.setOrientation(LinearLayout.VERTICAL); verticalLayout.setBackgroundColor(getIntColorFromJson(dialogParameters, IterableConstants.ITERABLE_IN_APP_BACKGROUND_COLOR, Color.WHITE)); Point screenSize = getScreenSize(context); int fontConstant = getFontConstant(screenSize); //Title JSONObject titleJson = dialogParameters.optJSONObject(IterableConstants.ITERABLE_IN_APP_TITLE); if (titleJson != null) { TextView title = new TextView(context); title.setText(titleJson.optString(IterableConstants.ITERABLE_IN_APP_TEXT)); title.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontConstant / 24); title.setGravity(Gravity.CENTER); title.setPadding(10, 5, 10, 5); title.setTextColor(getIntColorFromJson(titleJson, IterableConstants.ITERABLE_IN_APP_COLOR, Color.BLACK)); verticalLayout.addView(title); } //Body JSONObject bodyJson = dialogParameters.optJSONObject(IterableConstants.ITERABLE_IN_APP_BODY); if (bodyJson != null) { TextView bodyText = new TextView(context); bodyText.setText(bodyJson.optString(IterableConstants.ITERABLE_IN_APP_TEXT)); bodyText.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontConstant / 36); bodyText.setGravity(Gravity.CENTER); bodyText.setTextColor(getIntColorFromJson(bodyJson, IterableConstants.ITERABLE_IN_APP_COLOR, Color.BLACK)); bodyText.setPadding(10,0,10,10); verticalLayout.addView(bodyText); } //Buttons JSONArray buttonJson = dialogParameters.optJSONArray(IterableConstants.ITERABLE_IN_APP_BUTTONS); if (buttonJson != null) { verticalLayout.addView(createButtons(context, dialog, buttonJson, messageId, clickCallback)); } dialog.setContentView(verticalLayout); dialog.show(); } /** * Creates and shows a Full Screen InApp Notification; with a click callback handler. * @param context * @param dialogParameters * @param clickCallback */ static void showFullScreenDialog(Context context, JSONObject dialogParameters, String messageId, IterableHelper.IterableActionHandler clickCallback) { Dialog dialog = new Dialog(context, android.R.style.Theme_Light); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); LinearLayout verticalLayout = new LinearLayout(context); verticalLayout.setOrientation(LinearLayout.VERTICAL); verticalLayout.setBackgroundColor(getIntColorFromJson(dialogParameters, IterableConstants.ITERABLE_IN_APP_BACKGROUND_COLOR, Color.WHITE)); LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); verticalLayout.setLayoutParams(linearLayoutParams); LinearLayout.LayoutParams equalParamHeight = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1.0f); equalParamHeight.weight = 1; equalParamHeight.height = 0; Point size = getScreenSize(context); int dialogWidth = size.x; int dialogHeight = size.y; int fontConstant = getFontConstant(size); //Title JSONObject titleJson = dialogParameters.optJSONObject(IterableConstants.ITERABLE_IN_APP_TITLE); if (titleJson != null) { TextView title = new TextView(context); title.setText(titleJson.optString(IterableConstants.ITERABLE_IN_APP_TEXT)); title.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontConstant / 24); title.setGravity(Gravity.CENTER); title.setTextColor(getIntColorFromJson(titleJson, IterableConstants.ITERABLE_IN_APP_COLOR, Color.BLACK)); verticalLayout.addView(title, equalParamHeight); } //Image ImageView imageView = new ImageView(context); verticalLayout.addView(imageView); try { Class picassoClass = Class.forName(IterableConstants.PICASSO_CLASS); if (picassoClass != null) { Picasso. with(context.getApplicationContext()). load(dialogParameters.optString(IterableConstants.ITERABLE_IN_APP_MAIN_IMAGE)). resize(dialogWidth, dialogHeight/2). centerInside(). into(imageView); } } catch (ClassNotFoundException e) { IterableLogger.w(TAG, "ClassNotFoundException: Check that picasso is added " + "to the build dependencies", e); } //Body JSONObject bodyJson = dialogParameters.optJSONObject(IterableConstants.ITERABLE_IN_APP_BODY); if (bodyJson != null) { TextView bodyText = new TextView(context); bodyText.setText(bodyJson.optString(IterableConstants.ITERABLE_IN_APP_TEXT)); bodyText.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontConstant / 36); bodyText.setGravity(Gravity.CENTER); bodyText.setTextColor(getIntColorFromJson(bodyJson, IterableConstants.ITERABLE_IN_APP_COLOR, Color.BLACK)); verticalLayout.addView(bodyText, equalParamHeight); } //Buttons JSONArray buttonJson = dialogParameters.optJSONArray(IterableConstants.ITERABLE_IN_APP_BUTTONS); if (buttonJson != null) { View buttons = createButtons(context, dialog, buttonJson, messageId, clickCallback); LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); buttonParams.height = dialogHeight / 10; verticalLayout.addView(buttons, buttonParams); } dialog.setContentView(verticalLayout); //dialog.setCancelable(false); dialog.show(); } /** * Gets the next message from the payload * @param payload * @return */ public static JSONObject getNextMessageFromPayload(String payload) { JSONObject returnObject = null; if (payload != null && payload != "") { try { JSONObject mainObject = new JSONObject(payload); JSONArray jsonArray = mainObject.optJSONArray(IterableConstants.ITERABLE_IN_APP_MESSAGE); if (jsonArray != null) { returnObject = jsonArray.optJSONObject(0); } } catch (JSONException e) { IterableLogger.e(TAG, e.toString()); } } return returnObject; } /** * Creates the button for an InApp Notification * @param context * @param dialog * @param buttons * @param messageId * @param clickCallback * @return */ private static View createButtons(Context context, Dialog dialog, JSONArray buttons, String messageId, IterableHelper.IterableActionHandler clickCallback) { LinearLayout.LayoutParams equalParamWidth = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1.0f); equalParamWidth.weight = 1; equalParamWidth.width = 0; LinearLayout linearlayout = new LinearLayout(context); linearlayout.setOrientation(LinearLayout.HORIZONTAL); for (int i = 0; i < buttons.length(); i++) { JSONObject buttonJson = buttons.optJSONObject(i); if (buttonJson != null) { final Button button = new Button(context); button.setBackgroundColor(getIntColorFromJson(buttonJson, IterableConstants.ITERABLE_IN_APP_BACKGROUND_COLOR, Color.LTGRAY)); String action = buttonJson.optString(IterableConstants.ITERABLE_IN_APP_BUTTON_ACTION); button.setOnClickListener(new IterableInAppActionListener(dialog, i, action, messageId, clickCallback)); JSONObject textJson = buttonJson.optJSONObject(IterableConstants.ITERABLE_IN_APP_CONTENT); button.setTextColor(getIntColorFromJson(textJson, IterableConstants.ITERABLE_IN_APP_COLOR, Color.BLACK)); button.setText(textJson.optString(IterableConstants.ITERABLE_IN_APP_TEXT)); linearlayout.addView(button, equalParamWidth); } } return linearlayout; } /** * Gets the portrait height of the screen to use as a constant * @param size * @return */ private static int getFontConstant(Point size) { int fontConstant = (size.x > size.y) ? size.x : size.y; return fontConstant; } /** * Gets the dimensions of the device * @param context * @return */ private static Point getScreenSize(Context context) { WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); Point size = new Point(); display.getSize(size); return size; } /** * Gets the int value of the color from the payload * @param payload * @param key * @param defaultColor * @return */ private static int getIntColorFromJson(JSONObject payload, String key, int defaultColor) { int backgroundColor = defaultColor; if (payload != null) { String backgroundColorParam = payload.optString(key); if (!backgroundColorParam.isEmpty()) { backgroundColor = Color.parseColor(backgroundColorParam); } } return backgroundColor; } /** * Returns the gravity for a given displayType location * @param location * @return */ private static int getNotificationLocation(String location){ int locationValue; switch(location.toUpperCase()) { case IterableConstants.ITERABLE_IN_APP_TYPE_BOTTOM: locationValue = Gravity.BOTTOM; break; case IterableConstants.ITERABLE_IN_APP_TYPE_TOP: locationValue = Gravity.TOP; break; case IterableConstants.ITERABLE_IN_APP_TYPE_CENTER: default: locationValue = Gravity.CENTER; } return locationValue; } }
package org.apache.derby.impl.store.access.sort; import java.util.Properties; import org.apache.derby.iapi.services.monitor.ModuleControl; import org.apache.derby.iapi.services.monitor.ModuleSupportable; import org.apache.derby.iapi.services.monitor.Monitor; import org.apache.derby.iapi.services.property.PropertyUtil; import org.apache.derby.iapi.services.sanity.SanityManager; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.store.access.conglomerate.MethodFactory; import org.apache.derby.iapi.store.access.conglomerate.Sort; import org.apache.derby.iapi.store.access.conglomerate.SortFactory; import org.apache.derby.iapi.store.access.SortObserver; import org.apache.derby.iapi.store.access.SortCostController; import org.apache.derby.iapi.store.access.ColumnOrdering; import org.apache.derby.iapi.store.access.TransactionController; import org.apache.derby.iapi.types.DataValueDescriptor; import org.apache.derby.iapi.services.uuid.UUIDFactory; import org.apache.derby.catalog.UUID; public class ExternalSortFactory implements SortFactory, ModuleControl, ModuleSupportable, SortCostController { public static final String copyrightNotice = org.apache.derby.iapi.reference.Copyright.SHORT_1997_2004; private boolean userSpecified; // did the user specify sortBufferMax private int defaultSortBufferMax; private int sortBufferMax; private static final String IMPLEMENTATIONID = "sort external"; private static final String FORMATUUIDSTRING = "D2976090-D9F5-11d0-B54D-00A024BF8879"; private UUID formatUUID = null; private static final int DEFAULT_SORTBUFFERMAX = 1024; private static final int MINIMUM_SORTBUFFERMAX = 4; protected static final int DEFAULT_MEM_USE = 1024*1024; // aim for about 1Meg // how many sort runs to combined into a larger sort run protected static final int DEFAULT_MAX_MERGE_RUN = 1024; // sizeof Node + reference to Node + 12 bytes tax private static final int SORT_ROW_OVERHEAD = 8*4+12; /* ** Methods of MethodFactory */ /** There are no default properties for the external sort.. @see MethodFactory#defaultProperties **/ public Properties defaultProperties() { return new Properties(); } /** @see MethodFactory#supportsImplementation **/ public boolean supportsImplementation(String implementationId) { return implementationId.equals(IMPLEMENTATIONID); } /** @see MethodFactory#primaryImplementationType **/ public String primaryImplementationType() { return IMPLEMENTATIONID; } /** @see MethodFactory#supportsFormat **/ public boolean supportsFormat(UUID formatid) { return formatid.equals(formatUUID); } /** @see MethodFactory#primaryFormat **/ public UUID primaryFormat() { return formatUUID; } /* ** Methods of SortFactory */ /** Create a sort. This method could choose among different sort options, depending on the properties etc., but currently it always returns a merge sort. @see SortFactory#createSort **/ public Sort createSort( TransactionController tran, int segment, Properties implParameters, DataValueDescriptor[] template, ColumnOrdering columnOrdering[], SortObserver sortObserver, boolean alreadyInOrder, long estimatedRows, int estimatedRowSize) throws StandardException { MergeSort sort = new MergeSort(); // RESOLVE - mikem change this to use estimatedRows and // estimatedRowSize to come up with a smarter number for sortBufferMax // than a fixed number of rows. At least 2 possibilities: // 1) add sortBufferMaxMem which would be the amount of memory // the sorter could use, and then just pick the number of // rows as (sortBufferMaxMem / (estimatedRows * estimatedRowSize) // 2) add sortBufferUsePercentFree. This would be how much of // the current free memory can the current sort use. if (!userSpecified) { // derby.storage.sortBufferMax is not specified by the // user, use default or try to figure out a reasonable sort // size. // if we have some idea on row size, set sort approx 1 meg of // memory sort. if (estimatedRowSize > 0) { // for each column, there is a reference from the key array and // the 4 bytes reference to the column object plus 12 bytes // tax on the column object // for each row, SORT_ROW_OVERHEAD is the Node and 4 bytes to // point to the column array and 4 for alignment estimatedRowSize += SORT_ROW_OVERHEAD + (template.length*(4+12)) + 8; sortBufferMax = DEFAULT_MEM_USE/estimatedRowSize; } else { sortBufferMax = defaultSortBufferMax; } // if there are barely more rows than sortBufferMax, use 2 // smaller runs of similar size instead of one larger run // 10% slush is added to estimated Rows to catch the case where // estimated rows underestimate the actual number of rows by 10%. if (estimatedRows > sortBufferMax && (estimatedRows*1.1) < sortBufferMax*2) sortBufferMax = (int)(estimatedRows/2 + estimatedRows/10); // Make sure it is at least the minimum sort buffer size if (sortBufferMax < MINIMUM_SORTBUFFERMAX) sortBufferMax = MINIMUM_SORTBUFFERMAX; } else { // if user specified derby.storage.sortBufferMax, use it. sortBufferMax = defaultSortBufferMax; } if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON("SortTuning")) { SanityManager.DEBUG("SortTuning", "sortBufferMax = " + sortBufferMax + " estimatedRows = " + estimatedRows + " estimatedRowSize = " + estimatedRowSize + " defaultSortBufferMax = " + defaultSortBufferMax); } } sort.initialize( template, columnOrdering, sortObserver, alreadyInOrder, estimatedRows, sortBufferMax); return sort; } /** * Return an open SortCostController. * <p> * Return an open SortCostController which can be used to ask about * the estimated costs of SortController() operations. * <p> * * @return The open SortCostController. * * @exception StandardException Standard exception policy. * * @see SortCostController **/ public SortCostController openSortCostController() throws StandardException { return(this); } /* ** Methods of SortCostController */ public void close() { // nothing to do. } public double getSortCost( DataValueDescriptor[] template, ColumnOrdering columnOrdering[], boolean alreadyInOrder, long estimatedInputRows, long estimatedExportRows, int estimatedRowSize) throws StandardException { /* Avoid taking the log of 0 */ if (estimatedInputRows == 0) return 0.0; // RESOLVE - come up with some real benchmark. For now the cost // of sort is 3 times the cost of scanning the data. if (SanityManager.DEBUG) { SanityManager.ASSERT(estimatedInputRows >= 0); SanityManager.ASSERT(estimatedExportRows >= 0); } double ret_val = 1 + ((0.32) * (estimatedInputRows) * Math.log(estimatedInputRows)); return(ret_val); } /* ** Methods of ModuleControl. */ public boolean canSupport(Properties startParams) { if (startParams == null) return false; String impl = startParams.getProperty("derby.access.Conglomerate.type"); if (impl == null) return false; return supportsImplementation(impl); } public void boot(boolean create, Properties startParams) throws StandardException { // Find the UUID factory. UUIDFactory uuidFactory = Monitor.getMonitor().getUUIDFactory(); // Make a UUID that identifies this sort's format. formatUUID = uuidFactory.recreateUUID(FORMATUUIDSTRING); // See if there's a new maximum sort buffer size. defaultSortBufferMax = PropertyUtil.getSystemInt("derby.storage.sortBufferMax", 0, Integer.MAX_VALUE, 0); // if defaultSortBufferMax is 0, the user did not specify // sortBufferMax, then just set it to DEFAULT_SORTBUFFERMAX. // if defaultSortBufferMax is not 0, the user specified sortBufferMax, // do not override it. if (defaultSortBufferMax == 0) { userSpecified = false; defaultSortBufferMax = DEFAULT_SORTBUFFERMAX; } else { userSpecified = true; if (defaultSortBufferMax < MINIMUM_SORTBUFFERMAX) defaultSortBufferMax = MINIMUM_SORTBUFFERMAX; } } public void stop() { } }
package org.opensha.sha.calc.groundMotionField; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import org.apache.commons.math.linear.BlockRealMatrix; import org.apache.commons.math.linear.CholeskyDecompositionImpl; import org.apache.commons.math.linear.NonSquareMatrixException; import org.apache.commons.math.linear.NotPositiveDefiniteMatrixException; import org.apache.commons.math.linear.NotSymmetricMatrixException; import org.opensha.commons.data.Site; import org.opensha.commons.geo.LocationUtils; import org.opensha.sha.earthquake.EqkRupture; import org.opensha.sha.imr.ScalarIntensityMeasureRelationshipAPI; import org.opensha.sha.imr.param.IntensityMeasureParams.PeriodParam; import org.opensha.sha.imr.param.OtherParams.SigmaTruncLevelParam; import org.opensha.sha.imr.param.OtherParams.SigmaTruncTypeParam; import org.opensha.sha.imr.param.OtherParams.StdDevTypeParam; public class GroundMotionFieldCalculator { /** * Computes mean ground motion for a list of sites. * * @param attenRel * : {@link ScalarIntensityMeasureRelationshipAPI} attenuation * relationship used for ground motion field calculation * @param rup * : {@link EqkRupture} earthquake rupture generating the ground * motion field * @param sites * : array list of {@link Site} where ground motion values have * to be computed * @return : {@link Map} associating sites ({@link Site}) and ground motion * values {@link Double} */ public static Map<Site, Double> getMeanGroundMotionField( ScalarIntensityMeasureRelationshipAPI attenRel, EqkRupture rup, List<Site> sites) { validateInput(attenRel, rup, sites); Map<Site, Double> groundMotionMap = new HashMap<Site, Double>(); double meanGroundMotion = Double.NaN; attenRel.setEqkRupture(rup); for (Site site : sites) { attenRel.setSite(site); meanGroundMotion = attenRel.getMean(); groundMotionMap.put(site, new Double(meanGroundMotion)); } return groundMotionMap; } /** * Compute stochastic ground motion field by adding to the mean ground * motion field Gaussian deviates which takes into account the truncation * level and the truncation type. * * @param attenRel * : {@link ScalarIntensityMeasureRelationshipAPI} attenuation * relationship used for ground motion field calculation * @param rup * : {@link EqkRupture} earthquake rupture generating the ground * motion field * @param sites * : array list of {@link Site} where ground motion values have * to be computed * @param rn * : {@link Random} random number generator for Gaussian deviate * calculation * @return: {@link Map} associating sites ({@link Site}) and ground motion * values {@link Double} */ public static Map<Site, Double> getStochasticGroundMotionField( ScalarIntensityMeasureRelationshipAPI attenRel, EqkRupture rup, List<Site> sites, Random rn) { if (rn == null) throw new IllegalArgumentException( "Random number generator cannot be null"); validateInput(attenRel, rup, sites); Map<Site, Double> groundMotionField = getMeanGroundMotionField(attenRel, rup, sites); attenRel.setEqkRupture(rup); double standardDeviation = Double.NaN; double truncationLevel = (Double) attenRel.getParameter(SigmaTruncLevelParam.NAME) .getValue(); String truncationType = (String) attenRel.getParameter(SigmaTruncTypeParam.NAME) .getValue(); for (Site site : sites) { attenRel.setSite(site); standardDeviation = attenRel.getStdDev(); Double val = groundMotionField.get(site); double deviate = getGaussianDeviate(standardDeviation, truncationLevel, truncationType, rn); val = val + deviate; groundMotionField.put(site, val); } return groundMotionField; } /** * Compute stochastic ground motion field with spatial correlation using * correlation model from Jayamram & Baker (2009): * "Correlation model for spatially distributed ground-motion intensities" * Nirmal Jayaram and Jack W. Baker, Earthquake Engng. Struct. Dyn (2009) * The algorithm is structured according to the following steps: 1) Compute * mean ground motion values, 2) Stochastically generate inter-event * residuals (which follow a univariate normal distribution), 3) * Stochastically generate intra-event residuals (following the proposed * correlation model) 4) Combine the three terms generated in steps 1-3. * * Intra-event residuals are calculated by generating Gaussian deviates from * a multivariate normal distribution using Cholesky factorization * (decompose covariance matrix, take lower triangular and multiply by a * vector of uncorrelated, standard Gaussian variables) * * @param attenRel * : {@link ScalarIntensityMeasureRelationshipAPI} attenuation * relationship used for ground motion field calculation * @param rup * : {@link EqkRupture} earthquake rupture generating the ground * motion field * @param sites * : array list of {@link Site} where ground motion values have * to be computed * @param rn * : {@link Random} random number generator * @param inter_event * : if true compute ground motion field using both inter- and * intra-event residuals, if false use only intra-event residuals * @param Vs30Cluster * : true if Vs30 values show clustering [compute correlation * range according to case 2 of Jayaram&Baker paper], false if * Vs30 values do not show clustering [compute correlation range * according to case 1 of Jayaram&Baker paper] * @return */ public static Map<Site, Double> getStochasticGroundMotionField_JB2009( ScalarIntensityMeasureRelationshipAPI attenRel, EqkRupture rup, List<Site> sites, Random rn, Boolean inter_event, Boolean Vs30Cluster) { validateInput(attenRel, rup, sites); if (rn == null) throw new IllegalArgumentException( "Random number generator cannot be null"); if (inter_event == null) throw new IllegalArgumentException( "Usage of inter event residuals must be specified"); if (Vs30Cluster == null) throw new IllegalArgumentException( "Vs30 cluster option must be specified"); if (inter_event == true && attenRel.getParameter(StdDevTypeParam.NAME).getConstraint() .isAllowed(StdDevTypeParam.STD_DEV_TYPE_INTER) == false) throw new IllegalArgumentException( "The specified attenuation relationship does not provide" + " inter-event standard deviation"); if (attenRel.getParameter(StdDevTypeParam.NAME).getConstraint() .isAllowed(StdDevTypeParam.STD_DEV_TYPE_INTRA) == false) throw new IllegalArgumentException( "The specified attenuation relationship does not provide" + " intra-event standard deviation"); Map<Site, Double> groundMotionField = null; if (inter_event == true) { attenRel.getParameter(StdDevTypeParam.NAME).setValue( StdDevTypeParam.STD_DEV_TYPE_INTER); groundMotionField = getStochasticGroundMotionField(attenRel, rup, sites, rn); } else groundMotionField = getMeanGroundMotionField(attenRel, rup, sites); // compute intra-event residuals, by decomposing the covariance matrix // with cholesky decomposition, and by multiplying the lower triangular // matrix with a vector of univariate Gaussian deviates int numberOfSites = sites.size(); double[] gaussianDeviates = new double[numberOfSites]; for (int i = 0; i < numberOfSites; i++) gaussianDeviates[i] = getGaussianDeviate( 1.0, (Double) attenRel.getParameter( SigmaTruncLevelParam.NAME).getValue(), (String) attenRel.getParameter( SigmaTruncTypeParam.NAME).getValue(), rn); BlockRealMatrix covarianceMatrix = getCovarianceMatrix_JB2009(attenRel, rup, sites, rn, Vs30Cluster); CholeskyDecompositionImpl cholDecomp = null; try { cholDecomp = new CholeskyDecompositionImpl(covarianceMatrix); } catch (NonSquareMatrixException e) { e.printStackTrace(); } catch (NotSymmetricMatrixException e) { e.printStackTrace(); } catch (NotPositiveDefiniteMatrixException e) { e.printStackTrace(); } double[] intraEventResiduals = cholDecomp.getL().operate(gaussianDeviates); int indexSite = 0; for (Site site : sites) { double val = groundMotionField.get(site); groundMotionField.put(site, val + intraEventResiduals[indexSite]); indexSite = indexSite + 1; } return groundMotionField; } /** * Generate Gaussian deviate (mean zero, standard deviation = * standardDeviation) * * @param standardDeviation * : double standard deviation * @param truncationLevel * : double truncation level (in units of standard deviation) * @param truncationType * : String type of truncation defined by the * {@link SigmaTruncTypeParam} * @param rn * : random number generator * @return : double */ private static double getGaussianDeviate(double standardDeviation, double truncationLevel, String truncationType, Random rn) { double dev = rn.nextGaussian(); if (truncationType .equalsIgnoreCase(SigmaTruncTypeParam.SIGMA_TRUNC_TYPE_2SIDED)) { while (dev < -truncationLevel || dev > truncationLevel) { dev = rn.nextGaussian(); } } else if (truncationType .equalsIgnoreCase(SigmaTruncTypeParam.SIGMA_TRUNC_TYPE_1SIDED)) { while (dev > truncationLevel) { dev = rn.nextGaussian(); } } return dev * standardDeviation; } /** * Calculates covariance matrix for intra-event residuals using correlation * model of Jayamram & Baker (2009): * "Correlation model for spatially distributed ground-motion intensities" * Nirmal Jayaram and Jack W. Baker, Earthquake Engng. Struct. Dyn (2009) * * @param attenRel * @param rup * @param sites * @param rn * @param Vs30Cluster * @return */ private static BlockRealMatrix getCovarianceMatrix_JB2009( ScalarIntensityMeasureRelationshipAPI attenRel, EqkRupture rup, List<Site> sites, Random rn, Boolean Vs30Cluster) { int numberOfSites = sites.size(); BlockRealMatrix covarianceMatrix = new BlockRealMatrix(numberOfSites, numberOfSites); attenRel.setEqkRupture(rup); attenRel.getParameter(StdDevTypeParam.NAME).setValue( StdDevTypeParam.STD_DEV_TYPE_INTRA); double period = (Double) attenRel.getParameter(PeriodParam.NAME).getValue(); double correlationRange = Double.NaN; if (period < 1 && Vs30Cluster == false) correlationRange = 8.5 + 17.2 * period; else if (period < 1 && Vs30Cluster == true) correlationRange = 40.7 - 15.0 * period; else if (period >= 1) correlationRange = 22.0 + 3.7 * period; double intraEventStd_i = Double.NaN; double intraEventStd_j = Double.NaN; double distance = Double.NaN; double covarianceValue = Double.NaN; int index_i = 0; for (Site site_i : sites) { attenRel.setSite(site_i); intraEventStd_i = attenRel.getStdDev(); int index_j = 0; for (Site site_j : sites) { attenRel.setSite(site_j); intraEventStd_j = attenRel.getStdDev(); distance = LocationUtils.horzDistance(site_i.getLocation(), site_j.getLocation()); covarianceValue = intraEventStd_i * intraEventStd_j * Math.exp(-3 * (distance / correlationRange)); covarianceMatrix.setEntry(index_i, index_j, covarianceValue); index_j = index_j + 1; } index_i = index_i + 1; } return covarianceMatrix; } private static Boolean validateInput( ScalarIntensityMeasureRelationshipAPI attenRel, EqkRupture rup, List<Site> sites) { if (attenRel == null) { throw new IllegalArgumentException( "Attenuation relationship cannot be null"); } if (rup == null) { throw new IllegalArgumentException( "Earthquake rupture cannot be null"); } if (sites == null) { throw new IllegalArgumentException( "Array list of sites cannot be null"); } if (sites.isEmpty()) { throw new IllegalArgumentException( "Array list of sites must contain at least one site"); } return true; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package model.simulation; /** * * @author woodstock */ import model.*; import model.features.*; import model.encoding.*; import model.neuron.*; import model.competition.*; import model.evaluation.*; import model.utils.*; import model.utils.files.*; import java.io.*; import java.util.*; import model.attention.AbstractAttention; import model.attention.AttentionSalient; import model.utils.files.FileIO; import org.shared.array.RealArray; public class SimulationMNIST_layerF_onOff_loadF_indepLayer extends SimulationMNIST_layerF_onOff{ private boolean m_bload_layer_f = false; public void init(){ super.init(); if(m_bload_layer_f){ DataLoaderWeightSet weightLoader = new DataLoaderWeightSet(); weightLoader.setParams(m_params.getMainOutputDir()); weightLoader.setWeightValueFilename("weights_layerF.csv"); weightLoader.init(); weightLoader.load(); DataLoaderWeightSet biasLoader = new DataLoaderWeightSet(); biasLoader.setParams(m_params.getMainOutputDir()); biasLoader.setWeightValueFilename("biases_layerF.csv"); biasLoader.init(); biasLoader.load(); for(int li=0; li<m_nofLearners_layerF; ++li){ m_arrZNeurons_layerF[li].setWeights( weightLoader.getSample(li) ); m_arrZNeurons_layerF[li].setBias( biasLoader.getSample(li)[0] ); } } } public void learn(){ // predict - compete - update int nofStimuli = m_params.getNofTrainStimuli(); int gap_width_layerF = m_params.getLearnerParams_layerF_Ref().getHistoryLength(); int nof_responses_per_window_y2f = m_params.getEncDurationInMilSec() + gap_width_layerF; int nof_responses_per_stimulus_y2f = m_nofAttentions*nof_responses_per_window_y2f; int gap_width_layerZ = m_params.getLearnerParamsRef().getHistoryLength(); int nof_responses_per_stimulus_f2Z = nof_responses_per_stimulus_y2f + gap_width_layerZ; //int [][] arrResponse = new int [ nofStimuli ][ nof_responses_per_window_y2f ]; int [] arr_response1D_layerZ = new int [ nofStimuli * nof_responses_per_stimulus_f2Z ]; //int [][][] arrResponse_layerF = new int [ nofStimuli ][ m_params.getNofAttentions() ][ nof_responses_per_window_y2f ]; int [] arr_response1D_layerF = new int [ nofStimuli * nof_responses_per_stimulus_y2f ]; // activity mask will be reduced to mask weights of nodes with low activity int[] arrTrainLabelNames = m_dataLoader.determineLabelSet(0,nofStimuli-1); int nofCauses = m_params.getNofCauses(); int nofMasks = nofCauses; // ActivityMask [] arrActivityMask = new ActivityMask[ nofMasks_layerZ ]; // for(int mi=0; mi<nofMasks; mi++){ // arrActivityMask[mi] = new ActivityMask(); // arrActivityMask[mi].setParams( m_nofRows*m_nofCols ); // arrActivityMask[mi].set_lower_threshold_excl( m_params.get_activityMaskLowerThresholdExcl() ); // arrActivityMask[mi].init(); int [] allZeroSpikeTrain = new int [ m_nofLearners_layerF ]; int [] allZeroSpikeTrain_layerF = new int [ m_nofYNeurons ]; // let one aux neuron learn noise DataLoaderNoise dataLoaderNoise = new DataLoaderNoise(); dataLoaderNoise.setParams(m_params.getMainInputDir()); dataLoaderNoise.init(); dataLoaderNoise.load(); // evaluation int predictionStatWindowSize = m_params.get_predictionStatWindowSize(); EvaluationParams evaluation_params = new EvaluationParams(); evaluation_params.set_nofLearners(m_nofLearners_layerF); evaluation_params.set_label_names(arrTrainLabelNames); evaluation_params.set_predictionStats_windowSize(predictionStatWindowSize); PredictionStats predictionStats_perClass_layerF = new PredictionStats(); predictionStats_perClass_layerF.setParams(evaluation_params); predictionStats_perClass_layerF.init(); PredictionStats predictionStats_layerZ = new PredictionStats(); evaluation_params.set_nofLearners(m_nofLearners_layerZ); predictionStats_layerZ.setParams(evaluation_params); predictionStats_layerZ.init(); int [] arr_layerF_names = new int [ m_nofLearners_layerF+1 ]; // +1 for no F fires for(int fi=0; fi<m_nofLearners_layerF; fi++){ arr_layerF_names[fi] = fi; } arr_layerF_names[ m_nofLearners_layerF ] = AbstractCompetition.WTA_NONE; Arrays.sort(arr_layerF_names); EvaluationParams evaluation_params_perAttWin = new EvaluationParams(); evaluation_params_perAttWin.set_nofLearners(1); evaluation_params_perAttWin.set_label_names(arr_layerF_names); evaluation_params_perAttWin.set_predictionStats_windowSize(nof_responses_per_window_y2f); PredictionStats predictionStats_perAttWin_layerF = new PredictionStats(); predictionStats_perAttWin_layerF.setParams(evaluation_params_perAttWin); predictionStats_perAttWin_layerF.init(); int nofWeightsToWatch_layerZ = 0; double [][][] weightWatch_layerZ = new double [ m_nofLearners_layerZ ][ nofWeightsToWatch_layerZ ][ nofStimuli * nof_responses_per_stimulus_f2Z ]; //double [][][] rateWatch = new double [ m_nofLearners_layerZ ][ nofWeightsToWatch_layerZ ][ ]; int [] arrWeightIndicies_layerZ = new int[ nofWeightsToWatch_layerZ ]; //arrWeightIndicies[0] = 3; int nofWeightsToWatch_layerF = 0; double [][][] weightWatch_layerF = new double [ m_nofLearners_layerF ][ nofWeightsToWatch_layerF ][ nofStimuli * nof_responses_per_stimulus_y2f ]; //double [][][] rateWatch_layerF = new double [ m_nofLearners_layerF ][ ]; int [] arrWeightIndicies_layerF = new int[ nofWeightsToWatch_layerF ]; //arrWeightIndicies_layerF[0] = 50; int iteration_layerF = 0; int iteration_layerZ = 0; for(int si=0; si<nofStimuli; si++){ // transform input into set of spike trains m_dataLoader.load(); // load here if DataLoaderImageSetCSV_incremental() int nCurrent_label = m_dataLoader.getLabel(si); if (nCurrent_label == DataLoaderImageSetCSV.INVALID_LABEL){ String message = "Invalid label value " + Integer.toString(nCurrent_label) + "at i=" + Integer.toString(si); System.err.println(message); } double [] stimulus = m_dataLoader.getSample(si); m_attention.setScene(stimulus); int [][] spikes_f_per_stimulus = new int [ m_nofLearners_layerF ][ nof_responses_per_stimulus_y2f ]; for(int ai=0; ai<m_nofAttentions; ai++){ int attention_offset = ai*nof_responses_per_window_y2f; m_attention.attend(null); double [] window_of_attention = m_attention.getWindow(); // for(int li=0; li<nofCauses; li++){ // if(nCurrent_label == arrTrainLabelNames[li]) // arrActivityMask[li].addSample(window_of_ttention); int [][] spikes_y_p1 = m_encoder.encode(window_of_attention); int [][] spikes_y_p2 = m_encoder_onOff.encode(window_of_attention); int [][] spikes_f = new int [ m_nofLearners_layerF ][ nof_responses_per_window_y2f ]; // for each column in all spike trains of layer F // predict - compete - update for(int yt=0; yt<nof_responses_per_window_y2f; yt++){ // create array for spikes of all y neurons at time yt // traverse through columns of spikes_y[][] int [] spikes_atT_in; int [] spikes_atT_out; if(yt < m_params.getEncDurationInMilSec()){ int [] spikes_atT_in_p1 = ModelUtils.extractColumns(spikes_y_p1, yt); int [] spikes_atT_in_p2 = ModelUtils.extractColumns(spikes_y_p2, yt); spikes_atT_in = new int [m_nofYNeurons]; System.arraycopy(spikes_atT_in_p1, 0, spikes_atT_in, 0, m_encoder.getNofEncoderNodes()); System.arraycopy(spikes_atT_in_p2, 0, spikes_atT_in, m_encoder.getNofEncoderNodes(), m_encoder_onOff.getNofEncoderNodes()); } else{ spikes_atT_in = allZeroSpikeTrain_layerF; } // predict F for(int li=0; li<m_nofLearners_layerF; li++){ double membranePotential_layerF = m_arrZNeurons_layerF[li].predict(spikes_atT_in); //System.out.println(membranePotential); } // let F's compete before updating int wta_response = m_wta_layerF.compete(); if(wta_response != AbstractCompetition.WTA_NONE){ int [] arr_wta_response; arr_wta_response = m_wta_layerF.getOutcome(); for(int li=0; li<m_nofLearners_layerF; li++){ m_arrZNeurons_layerF[ li ].letFire(arr_wta_response[ li ]==1); } spikes_atT_out = arr_wta_response; predictionStats_perClass_layerF.addResponse( wta_response, nCurrent_label ); predictionStats_perAttWin_layerF.addResponse( 0, wta_response ); } else{ spikes_atT_out = allZeroSpikeTrain; } // update F for(int li=0; li<m_nofLearners_layerF; li++){ for(int ww=0; ww<nofWeightsToWatch_layerF; ww++){ weightWatch_layerF[ li ][ww][ iteration_layerF ] = m_arrZNeurons_layerF[ li ].getWeights()[ arrWeightIndicies_layerF[ww] ]; } if(!m_bload_layer_f){ m_arrZNeurons_layerF[li].update(); } } ModelUtils.insertColumn(spikes_atT_out, spikes_f, yt); ModelUtils.insertColumn(spikes_atT_out, spikes_f_per_stimulus, attention_offset+yt); arr_response1D_layerF[ iteration_layerF ] = wta_response; iteration_layerF++; //System.out.print(wta_response + " "); } } int [][] spikes_f2z; spikes_f2z = resample_spike_train_layerF(spikes_f_per_stimulus); spikes_f2z = refactor_spike_train_layerF(spikes_f2z); for(int ft=0; ft<nof_responses_per_stimulus_y2f; ++ft){ //arrResponse_layerF[ si ][ ai ][ yt ] = wta_response; //arrResponse1D_layerF[ (si*m_nofAttentions+ai)*nof_responses_per_window_y2f+yt ] = wta_response; // create array for f spikes at time ft // traverse through columns of spikes_f[][] int [] spikes_atT; if(ft < nof_responses_per_stimulus_y2f){ spikes_atT = ModelUtils.extractColumns(spikes_f2z, ft); } else{ spikes_atT = allZeroSpikeTrain_layerF; } // predict Z for(int li=0; li<m_nofLearners_layerZ; ++li){ double membranePotential = m_arrZNeurons[li].predict(spikes_atT); } // let Z's compete before updating int wta_response = m_wta.compete(); if(wta_response != AbstractCompetition.WTA_NONE){ int [] arr_wta_response; arr_wta_response = m_wta.getOutcome(); for(int li=0; li<m_nofLearners_layerZ; ++li){ m_arrZNeurons[ li ].letFire(arr_wta_response[ li ]==1); } predictionStats_layerZ.addResponse( wta_response, nCurrent_label ); } // update Z for(int li=0; li<m_nofLearners_layerZ; ++li){ for(int ww=0; ww<nofWeightsToWatch_layerZ; ++ww){ weightWatch_layerZ[ li ][ww ][ iteration_layerZ ] = m_arrZNeurons[ li ].getWeights()[ arrWeightIndicies_layerZ[ww] ]; } m_arrZNeurons[li].update(); } arr_response1D_layerZ[ iteration_layerZ ] = wta_response; ++iteration_layerZ; } } ModelPredictionTest.saveWeights( new File( m_params.getMainOutputDir(), "weights_layerF.csv" ).getPath(), m_arrZNeurons_layerF); ModelPredictionTest.saveBiases( new File( m_params.getMainOutputDir(), "biases_layerF.csv" ).getPath(), m_arrZNeurons_layerF); ModelPredictionTest.saveWeights( new File( m_params.getMainOutputDir(), "weights.csv" ).getPath(), m_arrZNeurons); ModelPredictionTest.saveBiases( new File( m_params.getMainOutputDir(), "biases.csv" ).getPath(), m_arrZNeurons); FileIO.saveArrayToCSV(arr_response1D_layerF, 1, nofStimuli * m_nofAttentions * nof_responses_per_window_y2f, new File( m_params.getMainOutputDir(), "response1D_layerF_learn.csv").getPath()); FileIO.saveArrayToCSV(arr_response1D_layerZ, 1, nofStimuli * nof_responses_per_stimulus_f2Z, new File( m_params.getMainOutputDir(), "response1D_layerZ_learn.csv").getPath()); // for(int mi=0; mi<nofMasks; mi++){ // arrActivityMask[mi].calc_activity_intensity(); // String strMaskFile = m_params.getMainOutputDir()+"masksClasses.csv"; // ModelPredictionTest.saveMasks(strMaskFile, arrActivityMask); File watch_dir = new File(m_params.getMainOutputDir(), FileIO.DIR_NAME_WATCH); double [] arrAvgCondEntropy; arrAvgCondEntropy = predictionStats_perClass_layerF.get_results_avg_cond_entropy(); FileIO.saveArrayToCSV( arrAvgCondEntropy, 1, arrAvgCondEntropy.length, new File(watch_dir, "watchAvgCondEntropy_perClass_layerF.csv").getPath() ); arrAvgCondEntropy = predictionStats_perAttWin_layerF.get_results_avg_cond_entropy(); FileIO.saveArrayToCSV( arrAvgCondEntropy, 1, arrAvgCondEntropy.length, new File(watch_dir, "watchAvgCondEntropy_perAttWin_layerF.csv").getPath() ); arrAvgCondEntropy = predictionStats_layerZ.get_results_avg_cond_entropy(); FileIO.saveArrayToCSV( arrAvgCondEntropy, 1, arrAvgCondEntropy.length, new File(watch_dir, "watchAvgCondEntropy_layerZ.csv").getPath() ); for(int zi=0; zi<m_nofLearners_layerZ; zi++){ FileIO.saveArrayToCSV(weightWatch_layerZ[zi], new File(watch_dir, "weightWatch"+zi+".csv").getPath()); } for(int fi=0; fi<m_nofLearners_layerF; fi++){ FileIO.saveArrayToCSV(weightWatch_layerF[fi], new File(watch_dir, "weightWatch_layerF"+fi+".csv").getPath()); } } public void test(){ m_wta.refToLearners(m_arrZNeurons); m_wtaAll.refToLearners(m_arrZNeuronsAll); int starti = m_params.getNofTrainStimuli(); int endi = m_totalNofStimuli; int nofStimuli = endi-starti+1; int gap_width_layerF = m_params.getLearnerParams_layerF_Ref().getHistoryLength(); int nof_responses_per_window_y2f = m_params.getEncDurationInMilSec()+gap_width_layerF; int nof_responses_per_stimulus_y2f = m_nofAttentions*nof_responses_per_window_y2f; int gap_width_layerZ = m_params.getLearnerParamsRef().getHistoryLength(); int nof_responses_per_stimulus_f2Z = nof_responses_per_stimulus_y2f + gap_width_layerZ; int[] arrTestLabelNames = m_dataLoader.determineLabelSet(starti, endi); int nofCauses = m_params.getNofCauses(); File dir_activity_layerF = new File(m_params.getMainOutputDir(), FileIO.DIR_NAME_ACTIVITY_LAYER_F); int nofMasks_layerF = m_nofLearners_layerF; ActivityMask [] arrActivityMask_layerF = new ActivityMask[ nofMasks_layerF ]; for(int mi=0; mi<nofMasks_layerF; mi++){ arrActivityMask_layerF[mi] = new ActivityMask(); arrActivityMask_layerF[mi].setParams(m_nofRows*m_nofCols); arrActivityMask_layerF[mi].set_lower_threshold_excl( m_params.get_activityMaskLowerThresholdExcl() ); arrActivityMask_layerF[mi].enable_logging( dir_activity_layerF.getPath(), Integer.toString(mi) ); arrActivityMask_layerF[mi].init(); } int [] scene_dims = m_attention.getSceneDims(); int nof_scene_rows = scene_dims[ FileIO.DIM_INDEX_ROWS ]; int nof_scene_cols = scene_dims[ FileIO.DIM_INDEX_COLS ]; File dir_activity_layerZ = new File(m_params.getMainOutputDir(), FileIO.DIR_NAME_ACTIVITY_LAYER_Z); int nofMasks_layerZ = m_nofLearners_layerZ; ActivityMask [] arr_ActivityMask_layerZ = new ActivityMask[ nofMasks_layerZ ]; for(int mi=0; mi<nofMasks_layerZ; mi++){ arr_ActivityMask_layerZ[mi] = new ActivityMask(); arr_ActivityMask_layerZ[mi].setParams(nof_scene_rows, nof_scene_cols ); arr_ActivityMask_layerZ[mi].set_lower_threshold_excl( m_params.get_activityMaskLowerThresholdExcl() ); arr_ActivityMask_layerZ[mi].enable_logging( dir_activity_layerZ.getPath(), Integer.toString(mi) ); arr_ActivityMask_layerZ[mi].init(); } // membranePotential_layerF : nofZ,nofstimuli,nofAttentios,durationOfSpikeTrain Y for each stimulus per F //double [][][][] arr_membranePotential_layerF = new double [ m_nofLearners_layerF ][ nofStimuli ][ m_nofAttentions ][ nof_responses_per_window_y2f ] ; int [][][] arrResponse_layerF = new int [ nofStimuli ][ m_nofAttentions ][ nof_responses_per_window_y2f ]; // membrane_pot_layerZ : nofZ,nofstimuli,durationOfSpikeTrain F for each stimulus per Z double [][] membrane_pot_layerZ = new double [ m_nofLearners_layerZ ][ nofStimuli*nof_responses_per_stimulus_f2Z ] ; int [][] arrResponse_layerZ = new int [ nofStimuli ][ nof_responses_per_stimulus_f2Z ]; int noWinnerCount_layerF = 0; int noWinnerCount_layerZ = 0; PredictionStats predictionStats_layerF = new PredictionStats(); predictionStats_layerF.setParams(m_nofLearners_layerF, arrTestLabelNames); predictionStats_layerF.init(); PredictionStats predictionStats = new PredictionStats(); predictionStats.setParams(m_nofLearners_layerZ, arrTestLabelNames); predictionStats.init(); int [] arr_layerF_names = new int [ m_nofLearners_layerF+1 ]; // +1 for no F fires for(int fi=0; fi<m_nofLearners_layerF; fi++){ arr_layerF_names[fi] = fi; } arr_layerF_names[ m_nofLearners_layerF ] = AbstractCompetition.WTA_NONE; Arrays.sort(arr_layerF_names); PredictionStats predictionStats_F2Z = new PredictionStats(); predictionStats_F2Z.setParams(m_nofLearners_layerZ, arr_layerF_names); predictionStats_F2Z.init(); int [] allZeroSpikeTrain = new int [ m_nofLearners_layerF ]; // no F neurons firing int [] allZeroSpikeTrain_layerF = new int [ m_nofYNeurons ]; // no Y neurons firing for(int si=starti, relSi=0; si<endi; si++, relSi++){ m_dataLoader.load(); // load here if DataLoaderImageSetCSV_incremental() int nCurrentLabel = m_dataLoader.getLabel(si); if (nCurrentLabel == DataLoaderImageSetCSV.INVALID_LABEL){ String message = "Invalid label value " + Integer.toString(nCurrentLabel) + "at i=" + Integer.toString(si); System.err.println(message); } double [] stimulus = m_dataLoader.getSample(si); m_attention.setScene(stimulus); int [][] spikes_f_per_stimulus = new int [ m_nofLearners_layerF ][ nof_responses_per_stimulus_y2f ]; double [][] arr_window_of_attention = new double[ m_nofAttentions ][ m_nofRows*m_nofCols ]; for(int ai=0; ai<m_nofAttentions; ai++){ int attention_offset = ai*nof_responses_per_window_y2f; m_attention.attend(null); double [] window_of_attention = m_attention.getWindow(); System.arraycopy(window_of_attention, 0, arr_window_of_attention[ai], 0, m_nofRows*m_nofCols); int [][] spikes_y_p1 = m_encoder.encode(window_of_attention); int [][] spikes_y_p2 = m_encoder_onOff.encode(window_of_attention); int [][] spikes_f = new int [ m_nofLearners_layerF ][ nof_responses_per_window_y2f ]; for(int yt=0; yt<nof_responses_per_window_y2f; yt++){ // create array for spikes of all y neurons at time yt // traverse through columns of spikes_y[][] int [] spikes_atT_in; int [] spikes_atT_out; if(yt < m_params.getEncDurationInMilSec()){ int [] spikes_atT_in_p1 = ModelUtils.extractColumns(spikes_y_p1, yt); int [] spikes_atT_in_p2 = ModelUtils.extractColumns(spikes_y_p2, yt); spikes_atT_in = new int [m_nofYNeurons]; System.arraycopy(spikes_atT_in_p1, 0, spikes_atT_in, 0, m_encoder.getNofEncoderNodes()); System.arraycopy(spikes_atT_in_p2, 0, spikes_atT_in, m_encoder.getNofEncoderNodes(), m_encoder_onOff.getNofEncoderNodes()); } else{ spikes_atT_in = allZeroSpikeTrain_layerF; } for(int li=0; li<m_nofLearners_layerF; li++){ double membranePotential_layerF = m_arrZNeurons_layerF[li].predict(spikes_atT_in); //arr_membranePotential_layerF[fi][ relSi ][ai][ yt ] = membranePotential_layerF; } // let F neurons compete int wta_response_layerF = m_wta_layerF.compete(); //System.out.print(wta_response_layerF + " "); if( wta_response_layerF != AbstractCompetition.WTA_NONE ){ int [] arr_wta_response_layerF = m_wta_layerF.getOutcome(); if( wta_response_layerF == AbstractCompetition.WTA_ALL ) wta_response_layerF = PredictionStats.RESPONSE_ALL; predictionStats_layerF.addResponse( wta_response_layerF, nCurrentLabel ); arrActivityMask_layerF[ wta_response_layerF ].addSample( window_of_attention ); spikes_atT_out = arr_wta_response_layerF; } else{ spikes_atT_out = allZeroSpikeTrain; noWinnerCount_layerF++; } ModelUtils.insertColumn(spikes_atT_out, spikes_f, yt); ModelUtils.insertColumn(spikes_atT_out, spikes_f_per_stimulus, attention_offset+yt); arrResponse_layerF[ relSi ][ai][ yt ] = wta_response_layerF; } } int [][] spikes_f2z; spikes_f2z = resample_spike_train_layerF(spikes_f_per_stimulus); spikes_f2z = refactor_spike_train_layerF(spikes_f2z); for(int ft=0; ft<nof_responses_per_stimulus_f2Z; ft++){ // create array for f spikes at time ft // traverse through columns of spikes_f[][] int [] spikes_atT_in; if(ft < nof_responses_per_window_y2f){ spikes_atT_in = ModelUtils.extractColumns(spikes_f2z, ft); // boolean no_fire_layerF = true; // for(int fi=0; fi<m_nofLearners_layerF; fi++){ // if(spikes_atT_in[fi] == 1){ // no_fire_layerF = false; // System.out.print(fi + " "); // if(no_fire_layerF){ // System.out.print(-1 + " "); } else{ spikes_atT_in = allZeroSpikeTrain_layerF; } for(int li=0; li<m_nofLearners_layerZ; li++){ double membranePotential_layerZ = m_arrZNeurons[li].predict( spikes_atT_in ); membrane_pot_layerZ[li][ relSi*nof_responses_per_stimulus_f2Z+ft ] = membranePotential_layerZ; } // let Z neurons compete int wta_response = m_wta.compete(); if(wta_response != AbstractCompetition.WTA_NONE){ if(wta_response == AbstractCompetition.WTA_ALL) wta_response = PredictionStats.RESPONSE_ALL; predictionStats.addResponse( wta_response, nCurrentLabel ); boolean layerF_fired = false; for(int fi=0; fi<m_nofLearners_layerF; fi++){ if(spikes_atT_in[fi] == 1){ predictionStats_F2Z.addResponse(wta_response, fi); layerF_fired = true; } } if( !layerF_fired ){ predictionStats_F2Z.addResponse(wta_response, AbstractCompetition.WTA_NONE); } //arr_ActivityMask[ wta_response ].addSample( stimulus ); //arr_ActivityMask_layerZ[ wta_response ].addSample( window_of_attention, m_attention.getWindowLoc(), m_attention.getWindowDims() ); } else{ noWinnerCount_layerZ++; } arrResponse_layerZ[ relSi ][ ft ] = wta_response; } //System.out.println(); } for(int mi=0; mi<nofMasks_layerF; mi++){ arrActivityMask_layerF[mi].calc_activity_intensity(); } ModelPredictionTest.saveMasks( new File(m_params.getMainOutputDir(), "masksLearners_layerF.csv").getPath(), arrActivityMask_layerF ); for(int mi=0; mi<nofMasks_layerZ; mi++){ arr_ActivityMask_layerZ[mi].calc_activity_intensity(); } ModelPredictionTest.saveMasks( new File(m_params.getMainOutputDir(), "masksLearners_layerZ.csv").getPath(), arr_ActivityMask_layerZ ); //ModelPredictionTest.saveResponses(m_params.getMainOutputDir()+"response_layerF.csv", arrResponse_layerF); ModelPredictionTest.saveResponses(new File(m_params.getMainOutputDir(),"response_layerZ_test.csv").getPath(), arrResponse_layerZ); FileIO.saveArrayToCSV(membrane_pot_layerZ, new File(m_params.getMainOutputDir(),"membrane_pot_layerZ.csv").getPath()); System.out.println("test set size: "+m_params.getNofTestStimuli()); // print prediction stats of layer F int [][] firingCounts = predictionStats_layerF.getFiringCounts(); int [] arr_firingSums = predictionStats_layerF.calcFiringSums(); double [][] arr_firing_probs = predictionStats_layerF.calcFiringProbs(); double [] arr_firingSums_temp = new double[m_nofLearners_layerF]; double [] arrCondEntropy = new double [ m_nofLearners_layerF ]; predictionStats_layerF.calcConditionalEntropy(arrCondEntropy); System.out.println("layer F:"); for(int li=0; li<m_nofLearners_layerF; li++){ for(int ci=0; ci<nofCauses; ci++){ System.out.print(firingCounts[li][ci] + " "); } System.out.print(" \u03A3 " + arr_firingSums[li]); System.out.print(" condEntr " + arrCondEntropy[ li ]); System.out.println(); arr_firingSums_temp[li] = (double)arr_firingSums[li]; } System.out.println("No winner count: "+noWinnerCount_layerF); // average firing sum during testing: RealArray firing_sums = new RealArray(arr_firingSums_temp); System.out.format("Mean firing sum= %.0f%n", firing_sums.aMean()); m_log_results.format("%.0f,", firing_sums.aMean()); // uniformity of firing double firing_uniformity = firing_sums.uMul(1.0/firing_sums.aSum()).aEnt(); System.out.format("Uniformity of firing probs= %.3f%n", firing_uniformity); m_log_results.format("%.3f,", firing_uniformity); ModelPredictionTest.savePredictionStats(new File(m_params.getMainOutputDir(), "predictionStats_layerF.csv").getPath(), arr_firing_probs, arrCondEntropy); // print prediction stats firingCounts = predictionStats.getFiringCounts(); arr_firingSums = predictionStats.calcFiringSums(); arr_firing_probs = predictionStats.calcFiringProbs(); arr_firingSums_temp = new double[m_nofLearners_layerZ]; arrCondEntropy = new double [ m_nofLearners_layerZ ]; predictionStats.calcConditionalEntropy(arrCondEntropy); System.out.println("layer Z:"); for(int li=0; li<m_nofLearners_layerZ; li++){ for(int ci=0; ci<nofCauses; ci++){ System.out.print(firingCounts[li][ci] + " "); } System.out.print(" \u03A3 " + arr_firingSums[li]); System.out.print(" condEntr " + arrCondEntropy[ li ]); System.out.println(); arr_firingSums_temp[li] = (double)arr_firingSums[li]; } System.out.println("No winner: "+noWinnerCount_layerZ); // average firing sum during testing: firing_sums = new RealArray(arr_firingSums_temp); System.out.format("Mean firing sum= %.0f%n", firing_sums.aMean()); m_log_results.format("%.0f,", firing_sums.aMean()); // uniformity of firing firing_uniformity = firing_sums.uMul(1.0/firing_sums.aSum()).aEnt(); System.out.format("Uniformity of firing probs= %.3f%n", firing_uniformity); m_log_results.format("%.3f,", firing_uniformity); ModelPredictionTest.savePredictionStats(new File(m_params.getMainOutputDir(), "predictionStats.csv").getPath(), arr_firing_probs, arrCondEntropy); // print prediction stats F2Z firingCounts = predictionStats_F2Z.getFiringCounts(); arr_firingSums = predictionStats_F2Z.calcFiringSums(); arr_firing_probs = predictionStats_F2Z.calcFiringProbs(); arr_firingSums_temp = new double[ m_nofLearners_layerZ ]; arrCondEntropy = new double [ m_nofLearners_layerZ ]; predictionStats_F2Z.calcConditionalEntropy(arrCondEntropy); System.out.println("layer Z:F2Z"); for(int li=0; li<m_nofLearners_layerZ; li++){ for(int ci=0; ci<m_nofLearners_layerF+1; ci++){// +1 for no F fires System.out.print(firingCounts[li][ci] + " "); } System.out.print(" \u03A3 " + arr_firingSums[li]); System.out.print(" condEntr " + arrCondEntropy[ li ]); System.out.println(); arr_firingSums_temp[li] = (double)arr_firingSums[li]; } // average firing sum during testing: firing_sums = new RealArray(arr_firingSums_temp); System.out.format("Mean firing sum= %.0f.%n", firing_sums.aMean()); m_log_results.format("%.0f,", firing_sums.aMean()); // uniformity of firing firing_uniformity = firing_sums.uMul(1.0/firing_sums.aSum()).aEnt(); System.out.format("Uniformity of firing probs= %.3f%n", firing_uniformity); m_log_results.format("%.3f,", firing_uniformity); ModelPredictionTest.savePredictionStats(new File(m_params.getMainOutputDir(), "predictionStats_F2Z.csv").getPath(), arr_firing_probs, arrCondEntropy); //m_nofLearners -= m_nofLearnersAux; m_log_results.println(); m_log_results.close(); } // resample spikes from layer F private int [][] resample_spike_train_layerF(int[][] par_spike_train){ int n = par_spike_train[0].length; int [][] result = new int[m_nofLearners_layerF][n]; Histogram spiking_hist_layerF = new Histogram(); spiking_hist_layerF.setParams(m_nofLearners_layerF+1); // +1 when no F fires spiking_hist_layerF.init(); for(int ft=0; ft<n; ++ft){ int[] spikes_at_T = ModelUtils.extractColumns(par_spike_train, ft); boolean bno_f_fired = true; for(int i=0; i<m_nofLearners_layerF; ++i){ if(spikes_at_T[i]> 0){ spiking_hist_layerF.increment(i); bno_f_fired = false; } } if(bno_f_fired){ spiking_hist_layerF.increment(m_nofLearners_layerF); } } Distribution1D spiking_distr_layerF = new Distribution1D(); spiking_distr_layerF.setParams(m_nofLearners_layerF); spiking_distr_layerF.init(); spiking_distr_layerF.evalDistr(spiking_hist_layerF.normalize()); int nof_samples_per_to_merge = 1; // produce at least 1 sample for(int ft=0; ft<n; ++ft){ int [] samples = spiking_distr_layerF.sample(nof_samples_per_to_merge); for(int sample_i=0; sample_i<nof_samples_per_to_merge; sample_i++){ int ft_spiking_node = samples[sample_i]; if(ft_spiking_node<m_nofLearners_layerF){ result[ft_spiking_node][ft] = 1; } } } // verify resampled spike train has similar distribution // Histogram spiking_hist_layerF2 = new Histogram(); // spiking_hist_layerF2.setParams(m_nofLearners_layerF+1); // +1 when no F fires // spiking_hist_layerF2.init(); // for(int ft=0; ft<n; ++ft){ // int[] spikes_at_T = ModelUtils.extractColumns(result, ft); // boolean bno_f_fired = true; // for(int i=0; i<m_nofLearners_layerF; ++i){ // if(spikes_at_T[i]> 0){ // spiking_hist_layerF2.increment(i); // bno_f_fired = false; // if(bno_f_fired){ // spiking_hist_layerF2.increment(m_nofLearners_layerF); // double[] x = spiking_hist_layerF.normalize(); // double[] y = spiking_hist_layerF2.normalize(); // double z = 0; // for(int i=0; i<x.length; ++i){ // z += Math.abs(x[i]-y[i]); // System.out.println(z/x.length); // System.out.println(java.util.Arrays.toString(x)); // System.out.println(java.util.Arrays.toString(y)); return result; } // re-invent layer F spike train private int [][] refactor_spike_train_layerF(int[][] par_spike_train){ int n = par_spike_train[0].length; SimplePopulationCode bi_state_pop_code = new SimplePopulationCode(); bi_state_pop_code.init(m_nofLearners_layerF, 2); int [][] result = new int[ m_nofLearners_layerF*2][n]; for(int ft=0; ft<n; ++ft){ int[] spikes_at_T = ModelUtils.extractColumns(par_spike_train, ft); ModelUtils.insertColumn(bi_state_pop_code.calcStateOfNeurons(spikes_at_T), result, ft); } return result; } }