lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
lgpl-2.1
c69ba5922202cf7fa58434673ed70d16c1bcaab7
0
justincc/intermine,joshkh/intermine,justincc/intermine,kimrutherford/intermine,zebrafishmine/intermine,kimrutherford/intermine,elsiklab/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,joshkh/intermine,zebrafishmine/intermine,joshkh/intermine,zebrafishmine/intermine,JoeCarlson/intermine,joshkh/intermine,tomck/intermine,elsiklab/intermine,joshkh/intermine,elsiklab/intermine,tomck/intermine,kimrutherford/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,tomck/intermine,tomck/intermine,kimrutherford/intermine,elsiklab/intermine,kimrutherford/intermine,kimrutherford/intermine,tomck/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,JoeCarlson/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,justincc/intermine,justincc/intermine,joshkh/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,tomck/intermine,joshkh/intermine,JoeCarlson/intermine,zebrafishmine/intermine,justincc/intermine,zebrafishmine/intermine,JoeCarlson/intermine,elsiklab/intermine,justincc/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,zebrafishmine/intermine,JoeCarlson/intermine,tomck/intermine,JoeCarlson/intermine,zebrafishmine/intermine,JoeCarlson/intermine,justincc/intermine,zebrafishmine/intermine,JoeCarlson/intermine,elsiklab/intermine
package org.intermine.bio.dataconversion; /* * Copyright (C) 2002-2013 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.intermine.bio.util.OrganismRepository; import org.intermine.objectstore.ObjectStoreException; import org.intermine.sql.writebatch.Batch; import org.intermine.sql.writebatch.BatchWriterPostgresCopyImpl; import org.intermine.util.Util; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.Item; import org.intermine.xml.full.Reference; import org.intermine.xml.full.ReferenceList; /** * Create items from the modENCODE metadata extensions to the chado schema. * @author Kim Rutherford,sc,rns */ public class ModEncodeMetaDataProcessor extends ChadoProcessor { private static final Logger LOG = Logger.getLogger(ModEncodeMetaDataProcessor.class); private static final String DATA_IDS_TABLE_NAME = "data_ids"; private static final String WIKI_URL = "http://wiki.modencode.org/project/index.php?title="; private static final String FILE_URL = "http://submit.modencode.org/submit/public/get_file/"; private static final String DCC_PREFIX = "modENCODE_"; private static final String NA_PROP = "not applicable"; private static final Set<String> DB_RECORD_TYPES = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList( "GEO_record", "ArrayExpress_record", "TraceArchive_record", "dbEST_record", "ShortReadArchive_project_ID (SRA)", "ShortReadArchive_project_ID_list (SRA)"))); // preferred synonyms private static final String STRAIN = "strain"; private static final String DEVSTAGE = "developmental stage"; // submission maps // --------------- private Map<Integer, String> submissionOrganismMap = new HashMap<Integer, String>(); // maps from chado identifier to lab/project details private Map<Integer, SubmissionDetails> submissionMap = new HashMap<Integer, SubmissionDetails>(); // subId to dcc id private Map<Integer, String> dccIdMap = new HashMap<Integer, String>(); // superseded/deleted subId to dcc id: to be checked in case we need to skip // loading a sub private Map<Integer, String> deletedSubMap = new HashMap<Integer, String>(); // applied_protocol/data/attribute maps // ------------------- // chado submission id to chado data_id private Map<Integer, List<Integer>> submissionDataMap = new HashMap<Integer, List<Integer>>(); // chado data id to chado submission id private Map<Integer, Integer> dataSubmissionMap = new HashMap<Integer, Integer>(); // to store protocol data until we create applied protocols private Map<Integer, Protocol> protocolMap = new HashMap<Integer, Protocol>(); // used when traversing dag of applied protocols private Map<Integer, AppliedProtocol> appliedProtocolMap = new HashMap<Integer, AppliedProtocol>(); // used when traversing dag of applied protocols private Map<Integer, AppliedData> appliedDataMap = new HashMap<Integer, AppliedData>(); // project/lab/experiment/submission maps // -------------------------------------- // for projects, the maps link the project name with the identifiers... private Map<String, Integer> projectIdMap = new HashMap<String, Integer>(); private Map<String, String> projectIdRefMap = new HashMap<String, String>(); // for labs, the maps link the lab name with the identifiers... private Map<String, Integer> labIdMap = new HashMap<String, Integer>(); private Map<String, String> labIdRefMap = new HashMap<String, String>(); // for experiment, the maps link the exp name (description!) with the identifiers... private Map<String, Integer> experimentIdMap = new HashMap<String, Integer>(); private Map<String, String> experimentIdRefMap = new HashMap<String, String>(); private Map<String, List<Integer>> expSubMap = new HashMap<String, List<Integer>>(); // ...we need a further map to link to submission private Map<Integer, String> submissionProjectMap = new HashMap<Integer, String>(); private Map<Integer, String> submissionLabMap = new HashMap<Integer, String>(); // to store the category in experiment private Map<Integer, String> submissionExpCatMap = new HashMap<Integer, String>(); // to check if experiment type is set private Set<Integer> submissionWithExpTypeSet = new HashSet<Integer>(); // submission/applied_protocol/protocol maps // ----------------------------------------- private Map<String, String> protocolsMap = new HashMap<String, String>(); private Map<Integer, String> protocolItemIds = new HashMap<Integer, String>(); private Map<String, Integer> protocolItemToObjectId = new HashMap<String, Integer>(); // submission chado id to item identifier of Protocol used to generate GFF private Map<Integer, String> scoreProtocols = new HashMap<Integer, String>(); private Map<Integer, String> protocolTypesMap = new HashMap<Integer, String>(); private Map<Integer, Integer> appliedProtocolIdMap = new HashMap<Integer, Integer>(); private Map<Integer, String> appliedProtocolIdRefMap = new HashMap<Integer, String>(); // list of firstAppliedProtocols, first level of the DAG linking // the applied protocols through the data (and giving the flow of data) private List<Integer> firstAppliedProtocols = new ArrayList<Integer>(); private Map<Integer, Integer> publicationIdMap = new HashMap<Integer, Integer>(); private Map<Integer, String> publicationIdRefMap = new HashMap<Integer, String>(); // experimental factor maps // ------------------------ // chado submission id to list of top level attributes, e.g. dev stage, organism_part private Map<Integer, ExperimentalFactor> submissionEFMap = new HashMap<Integer, ExperimentalFactor>(); private Map<Integer, List<String[]>> submissionEFactorMap2 = new HashMap<Integer, List<String[]>>(); private Map<String, Integer> eFactorIdMap = new HashMap<String, Integer>(); private Map<String, String> eFactorIdRefMap = new HashMap<String, String>(); private Map<Integer, List<String>> submissionEFactorMap = new HashMap<Integer, List<String>>(); // caches // ------ // cache cv term names by id private Map<String, String> cvtermCache = new HashMap<String, String>(); private Map<String, String> devStageTerms = new HashMap<String, String>(); private Map<String, String> devOntologies = new HashMap<String, String>(); // just for debugging, itemIdentifier, type private Map<String, String> debugMap = new HashMap<String, String>(); private Map<String, Item> nonWikiSubmissionProperties = new HashMap<String, Item>(); private Map<String, Item> subItemsMap = new HashMap<String, Item>(); Map<Integer, List<SubmissionReference>> submissionRefs = null; protected IdResolver rslv; private Map<String, String> geneToItemIdentifier = new HashMap<String, String>(); // DbRecords Integer=objectId String=submission.itemId // the second map is used directly to build the references private Map<DatabaseRecordKey, Integer> dbRecords = new HashMap<DatabaseRecordKey, Integer>(); private Map<Integer, List<String>> dbRecordIdSubItems = new HashMap<Integer, List<String>>(); private static final class SubmissionDetails { // the identifier assigned to Item eg. "0_23" private String itemIdentifier; // the object id of the stored Item private Integer interMineObjectId; // the identifier assigned to lab Item for this object private String labItemIdentifier; private String title; private SubmissionDetails() { // don't instantiate } } /** * AppliedProtocol class to reconstruct the flow of submission data */ private static final class AppliedProtocol { private Integer submissionId; // chado private Integer protocolId; private Integer step; // the level in the dag for the AP // the output data associated to this applied protocol private List<Integer> outputs = new ArrayList<Integer>(); private List<Integer> inputs = new ArrayList<Integer>(); private AppliedProtocol() { // don't instantiate } } /** * Protocol class to store protocol data */ private static final class Protocol { private Integer protocolId; // possibly we don't need this (map) private String name; private String description; private String wikiLink; private Integer version; // the level in the dag for the AP private Protocol() { // don't instantiate } } /** * AppliedData class * to reconstruct the flow of submission data * */ private static final class AppliedData { private String itemIdentifier; private Integer intermineObjectId; private Integer dataId; private String value; private String actualValue; private String type; private String name; private String url; // in particular, it stores the dccid of the related sub needed for // linking to a result file // the list of applied protocols for which this data item is an input private List<Integer> nextAppliedProtocols = new ArrayList<Integer>(); // the list of applied protocols for which this data item is an output private List<Integer> previousAppliedProtocols = new ArrayList<Integer>(); private AppliedData() { // don't instantiate } } /** * Experimental Factor class * to store the couples (type, name/value) of EF * note that in chado sometime the name is given, other times is the value */ private static final class ExperimentalFactor { private Map<String, String> efTypes = new HashMap<String, String>(); private List<String> efNames = new ArrayList<String>(); private ExperimentalFactor() { // don't instantiate } } /** * Create a new ChadoProcessor object * @param chadoDBConverter the converter that created this Processor */ public ModEncodeMetaDataProcessor(ChadoDBConverter chadoDBConverter) { super(chadoDBConverter); } /** * {@inheritDoc} */ @Override public void process(Connection connection) throws Exception { processDeleted(connection); processProjectTable(connection); processLabTable(connection); processSubmissionOrganism(connection); processSubmission(connection); processSubmissionAttributes(connection); processProtocolTable(connection); processAppliedProtocolTable(connection); processProtocolAttributes(connection); processDag(connection); processAppliedData(connection); processAppliedDataAttributes(connection); processExperiment(connection); findScoreProtocols(); processFeatures(connection, submissionMap); // set references setSubmissionRefs(connection); setSubmissionExperimentRefs(connection); setDAGRefs(connection); // create DatabaseRecords where necessary for each submission createDatabaseRecords(connection); // create result files per submission createResultFiles(connection); // for high level attributes and experimental factors (EF) // TODO: clean up processEFactor(connection); // create id resolvers if (rslv == null) { rslv = IdResolverService.getFishIdResolver(); rslv = IdResolverService.getWormIdResolver(); } processSubmissionProperties(connection); createRelatedSubmissions(connection); setSubmissionProtocolsRefs(connection); setSubmissionEFactorsRefs(connection); setSubmissionPublicationRefs(connection); } /** * ========================= * DELETED SUBS in CHADO * ========================= * To build a map of deleted subs (submissionId, dcc) * * @param connection * @throws SQLException * @throws ObjectStoreException */ private void processDeleted(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getDeleted(connection); while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); String value = res.getString("value"); deletedSubMap.put(submissionId, value); } res.close(); LOG.info("found " + deletedSubMap.size() + " deleted submissions to skip in the build."); LOG.info("PROCESS TIME deleted subs: " + (System.currentTimeMillis() - bT) + " ms"); } /** * Return deleted subs in the chado db. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getDeleted(Connection connection) throws SQLException { String query = "SELECT distinct a.experiment_id, a.value " + " FROM experiment_prop a " + " where a.name = 'deleted' "; return doQuery(connection, query, "getDeleted"); } /** * * ============== * FEATURES * ============== * * @param connection * @param submissionMap * @throws Exception */ private void processFeatures(Connection connection, Map<Integer, SubmissionDetails> submissionMap) throws Exception { long bT = System.currentTimeMillis(); // to monitor time spent in the process // keep map of feature to submissions it has been referenced by, some features appear in // more than one submission Map<Integer, List<String>> subCollections = new HashMap<Integer, List<String>>(); // hold features that should only be processed once across all submissions, initialise // processor with this map each time Map<Integer, FeatureData> commonFeaturesMap = new HashMap<Integer, FeatureData>(); for (Map.Entry<Integer, SubmissionDetails> entry: submissionMap.entrySet()) { Integer chadoExperimentId = entry.getKey(); if (deletedSubMap.containsKey(chadoExperimentId)) { continue; } Map<Integer, FeatureData> subFeatureMap = new HashMap<Integer, FeatureData>(); SubmissionDetails submissionDetails = entry.getValue(); String submissionItemIdentifier = submissionDetails.itemIdentifier; String labItemIdentifier = submissionDetails.labItemIdentifier; String submissionTitle = submissionDetails.title; List<Integer> thisSubmissionDataIds = submissionDataMap.get(chadoExperimentId); LOG.info("DATA IDS for " + dccIdMap.get(chadoExperimentId) + ": " + thisSubmissionDataIds.size()); // Create a temporary table with the feature ids related to this submission // based on the data_feature table String dataIdsTempTable = createDataIdsTempTable(connection, chadoExperimentId, thisSubmissionDataIds); ModEncodeFeatureProcessor processor = new ModEncodeFeatureProcessor(getChadoDBConverter(), submissionItemIdentifier, labItemIdentifier, dataIdsTempTable, submissionTitle, scoreProtocols.get(chadoExperimentId)); processor.initialiseCommonFeatures(commonFeaturesMap); processor.process(connection); // all features related to this submission subFeatureMap.putAll(processor.getFeatureMap()); // features common across many submissions commonFeaturesMap.putAll(processor.getCommonFeaturesMap()); LOG.info("COMMON FEATURES: " + commonFeaturesMap.size()); if (subFeatureMap.keySet().size() == 0) { LOG.error("FEATMAP: submission " + chadoExperimentId + " has no featureMap keys."); continue; } LOG.info("FEATMAP: submission " + chadoExperimentId + "|" + "featureMap: " + subFeatureMap.keySet().size()); // Populate map of submissions to features, some features are in multiple submissions processDataFeatureTable(connection, subCollections, subFeatureMap, chadoExperimentId, dataIdsTempTable); dropDataIdsTempTable(connection, dataIdsTempTable); // 1- generate a map of gene-identifiers so we can re-use the same item identifiers // when creating antibody/strain target genes late // 2- fill the 'ChromatinState' state with the secondaryId additionalProcessing(processor, subFeatureMap); } storeSubmissionsCollections(subCollections); LOG.info("PROCESS TIME features: " + (System.currentTimeMillis() - bT) + " ms"); } private void storeSubmissionsCollections(Map<Integer, List<String>> subCollections) throws ObjectStoreException { for (Map.Entry<Integer, List<String>> entry : subCollections.entrySet()) { Integer featureObjectId = entry.getKey(); ReferenceList collection = new ReferenceList("submissions", entry.getValue()); getChadoDBConverter().store(collection, featureObjectId); } } private void additionalProcessing(ModEncodeFeatureProcessor processor, Map<Integer, FeatureData> subFeatureMap) throws ObjectStoreException{ for (FeatureData fData : subFeatureMap.values()) { // 1- generate a map of gene-identifiers so we can re-use the same item identifiers // when creating antibody/strain target genes late if ("Gene".equals(fData.getInterMineType())) { String geneIdentifier = processor.fixIdentifier(fData, fData.getUniqueName()); geneToItemIdentifier.put(geneIdentifier, fData.getItemIdentifier()); } // 2- fill the 'ChromatinState' state with the secondaryId if ("ChromatinState".equals(fData.getInterMineType())) { String state = fData.getChadoFeatureName(); Integer imObjectId = fData.getIntermineObjectId(); setAttribute(imObjectId, "state", state); } } } private void processDataFeatureTable(Connection connection, Map<Integer, List<String>> subCols, Map<Integer, FeatureData> featureMap, Integer chadoExperimentId, String dataIdTable) throws SQLException { long bT = System.currentTimeMillis(); // to monitor time spent in the process String submissionItemId = submissionMap.get(chadoExperimentId).itemIdentifier; bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getDataFeature(connection, dataIdTable); while (res.next()) { Integer dataId = new Integer(res.getInt("data_id")); Integer featureId = new Integer(res.getInt("feature_id")); FeatureData featureData = featureMap.get(featureId); if (featureData == null) { LOG.debug("Check feature type: no data for feature_id: " + featureId + " in processDataFeatureTable(), data_id =" + dataId); continue; } Integer featureObjectId = featureData.getIntermineObjectId(); List<String> subs = subCols.get(featureObjectId); if (subs == null) { subs = new ArrayList<String>(); subCols.put(featureObjectId, subs); } subs.add(submissionItemId); } LOG.info("DATA IDS PROCESS TIME data_feature table: " + (System.currentTimeMillis() - bT)); } private String createDataIdsTempTable(Connection connection, Integer chadoExperimentId, List<Integer> dataIds) throws SQLException { // the batch writer system doesn't like to have duplicate named tables String tableName = DATA_IDS_TABLE_NAME + "_" + chadoExperimentId + "_" + System.currentTimeMillis(); long bT = System.currentTimeMillis(); String query = " CREATE TEMPORARY TABLE " + tableName + " (data_id int)"; Statement stmt = connection.createStatement(); LOG.info("executing: " + query); stmt.execute(query); try { BatchWriterPostgresCopyImpl batchWriter = new BatchWriterPostgresCopyImpl(); Batch batch = new Batch(batchWriter); HashSet<Integer> uniqueDataIds = new HashSet<Integer>(dataIds); String[] colNames = new String[] {"data_id"}; for (Integer dataId : uniqueDataIds) { batch.addRow(connection, tableName, dataId, colNames, new Object[] {dataId}); } batch.flush(connection); batch.close(connection); LOG.info("CREATED DATA IDS TABLE: " + tableName + " with " + uniqueDataIds.size() + " data ids in " + (System.currentTimeMillis() - bT) + "ms"); String idIndexQuery = "CREATE INDEX " + tableName + "_data_id_index ON " + tableName + "(data_id)"; LOG.info("DATA IDS executing: " + idIndexQuery); long bT1 = System.currentTimeMillis(); stmt.execute(idIndexQuery); LOG.info("DATA IDS TIME creating INDEX: " + (System.currentTimeMillis() - bT1) + "ms"); String analyze = "ANALYZE " + tableName; LOG.info("executing: " + analyze); long bT2 = System.currentTimeMillis(); stmt.execute(analyze); LOG.info("DATA IDS TIME analyzing: " + (System.currentTimeMillis() - bT2) + "ms"); } catch (SQLException e) { // the batch writer system doesn't like to have duplicate named tables query = "DROP TABLE " + tableName; stmt.execute(query); throw e; } return tableName; } private void dropDataIdsTempTable(Connection connection, String dataIdsTableName) throws SQLException { long bT = System.currentTimeMillis(); String query = " DROP TABLE " + dataIdsTableName; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); stmt.execute(query); LOG.info("DATA IDS TIME dropping table '" + dataIdsTableName + "': " + (System.currentTimeMillis() - bT)); } private ResultSet getDataFeature(Connection connection, String dataIdTable) throws SQLException { String query = "SELECT df.data_id, df.feature_id" + " FROM data_feature df, " + dataIdTable + " d" + " WHERE df.data_id = d.data_id"; return doQuery(connection, query, "getDataFeature"); } /** * * ==================== * DAG * ==================== * * In chado, Applied protocols in a submission are linked to each other via * the flow of data (output of a parent AP are input to a child AP). * The method process the data from chado to build the objects * (SubmissionDetails, AppliedProtocol, AppliedData) and their * respective maps to chado identifiers needed to traverse the DAG. * It then traverse the DAG, assigning the experiment_id to all data. * * @param connection * @throws SQLException * @throws ObjectStoreException */ private void processDag(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getDAG(connection); AppliedProtocol node = new AppliedProtocol(); AppliedData branch = null; Integer count = new Integer(0); Integer actualSubmissionId = new Integer(0); // to store the experiment id (see below) Integer previousAppliedProtocolId = new Integer(0); boolean isADeletedSub = false; while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); Integer protocolId = new Integer(res.getInt("protocol_id")); Integer appliedProtocolId = new Integer(res.getInt("applied_protocol_id")); Integer dataId = new Integer(res.getInt("data_id")); String direction = res.getString("direction"); LOG.debug("DAG: " + submissionId + " p:" + protocolId + " ap:" + appliedProtocolId + " d:" + dataId + " | " + direction); // the results are ordered, first ap have a subId // if we find a deleted sub, we know that subsequent records with null // subId belongs to the deleted sub // note that while the subId is null in the database, it is = 0 here if (submissionId == 0) { if (isADeletedSub) { LOG.debug("DEL: skipping" + isADeletedSub); continue; } } else { if (deletedSubMap.containsKey(submissionId)) { isADeletedSub = true; LOG.debug("DEL: " + submissionId + " ->" + isADeletedSub); continue; } else { isADeletedSub = false; LOG.debug("DEL: " + submissionId + " ->" + isADeletedSub); } } // build a data node for each iteration if (appliedDataMap.containsKey(dataId)) { branch = appliedDataMap.get(dataId); } else { branch = new AppliedData(); } // could use > (order by apid, apdataid, direction) // NB: using isLast() is expensive if (!appliedProtocolId.equals(previousAppliedProtocolId) || res.isLast()) { // the submissionId != null for the first applied protocol if (submissionId > 0) { firstAppliedProtocols.add(appliedProtocolId); LOG.debug("DAG fap subId:" + submissionId + " apID: " + appliedProtocolId); // set actual submission id // we can either be at a first applied protocol (submissionId > 0).. actualSubmissionId = submissionId; } else { // ..or already down the dag, and we use the stored id. submissionId = actualSubmissionId; } // last one: fill the list of outputs // and add to the general list of data ids for the submission, // used to fetch features if (res.isLast()) { if ("output".equalsIgnoreCase(direction)) { node.outputs.add(dataId); mapSubmissionAndData(submissionId, dataId); } } // if it is not the first iteration, let's store it if (previousAppliedProtocolId > 0) { appliedProtocolMap.put(previousAppliedProtocolId, node); } // new node AppliedProtocol newNode = new AppliedProtocol(); newNode.protocolId = protocolId; newNode.submissionId = submissionId; if (direction.startsWith("in")) { // add this applied protocol to the list of nextAppliedProtocols branch.nextAppliedProtocols.add(appliedProtocolId); // ..and update the map updateAppliedDataMap(branch, dataId); // .. and add the dataId to the list of input Data for this applied protocol newNode.inputs.add(dataId); mapSubmissionAndData(submissionId, dataId); //*** } else if (direction.startsWith("out")) { // add the dataId to the list of output Data for this applied protocol: // it will be used to link to the next set of applied protocols newNode.outputs.add(dataId); if (previousAppliedProtocolId > 0) { branch.previousAppliedProtocols.add(previousAppliedProtocolId); updateAppliedDataMap(branch, dataId); //*** mapSubmissionAndData(submissionId, dataId); //**** } } else { // there is some problem with the strings 'input' or 'output' throw new IllegalArgumentException("Data direction not valid for dataId: " + dataId + "|" + direction + "|"); } // for the new round.. node = newNode; previousAppliedProtocolId = appliedProtocolId; } else { // keep feeding IN et OUT if (direction.startsWith("in")) { node.inputs.add(dataId); if (submissionId > 0) { // initial data mapSubmissionAndData(submissionId, dataId); } // as above branch.nextAppliedProtocols.add(appliedProtocolId); updateAppliedDataMap(branch, dataId); } else if (direction.startsWith("out")) { node.outputs.add(dataId); branch.previousAppliedProtocols.add(appliedProtocolId); updateAppliedDataMap(branch, dataId); //*** } else { throw new IllegalArgumentException("Data direction not valid for dataId: " + dataId + "|" + direction + "|"); } } count++; } LOG.info("created " + appliedProtocolMap.size() + "(" + count + " applied data points) DAG nodes (= applied protocols) in map"); res.close(); // now traverse the DAG, and associate submission with all the applied protocols traverseDag(); // set the dag level as an attribute to applied protocol setAppliedProtocolSteps(connection); LOG.info("PROCESS TIME DAG: " + (System.currentTimeMillis() - bT) + " ms"); } /** * @param newAD * @param dataId */ private void updateAppliedDataMap(AppliedData newAD, Integer dataId) { if (appliedDataMap.containsKey(dataId)) { appliedDataMap.remove(dataId); } appliedDataMap.put(dataId, newAD); } /** * @param newAD the new appliedData * @param dataId the data id * @param intermineObjectId just a flag to do an update of attributes instead of a replecament */ private void updateADMap(AppliedData newAD, Integer dataId, Integer intermineObjectId) { if (appliedDataMap.containsKey(dataId)) { AppliedData datum = appliedDataMap.get(dataId); datum.intermineObjectId = newAD.intermineObjectId; datum.itemIdentifier = newAD.itemIdentifier; datum.value = newAD.value; datum.actualValue = newAD.actualValue; datum.dataId = dataId; datum.type = newAD.type; datum.name = newAD.name; datum.url = newAD.url; } else { appliedDataMap.put(dataId, newAD); } } /** * to set the step attribute for the applied protocols */ private void setAppliedProtocolSteps(Connection connection) throws ObjectStoreException { for (Integer appliedProtocolId : appliedProtocolMap.keySet()) { Integer step = appliedProtocolMap.get(appliedProtocolId).step; if (step != null) { Attribute attr = new Attribute("step", step.toString()); getChadoDBConverter().store(attr, appliedProtocolIdMap.get(appliedProtocolId)); } else { AppliedProtocol ap = appliedProtocolMap.get(appliedProtocolId); LOG.warn("AppliedProtocol.step not set for chado id: " + appliedProtocolId + " sub " + dccIdMap.get(ap.submissionId) + " inputs " + ap.inputs + " outputs " + ap.outputs); } } } // Look for protocols that were used to generated GFF files, these are passed to the feature // processor, if features have a score the protocol is set as the scoreProtocol reference. // NOTE this could equally be done with data, data_feature and applied_protocol_data private void findScoreProtocols() { for (Map.Entry<Integer, AppliedData> entry : appliedDataMap.entrySet()) { Integer dataId = entry.getKey(); AppliedData aData = entry.getValue(); if ("Result File".equals(aData.type) && (aData.value.endsWith(".gff") || aData.value.endsWith("gff3"))) { for (Integer papId : aData.previousAppliedProtocols) { AppliedProtocol aProtocol = appliedProtocolMap.get(papId); String protocolItemId = protocolItemIds.get(aProtocol.protocolId); scoreProtocols.put(dataSubmissionMap.get(dataId), protocolItemId); } } } } /** * Return the rows needed to construct the DAG of the data/protocols. * The reference to the submission is available only for the first set * of applied protocols, hence the outer join. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getDAG(Connection connection) throws SQLException { String query = "SELECT eap.experiment_id, ap.protocol_id, apd.applied_protocol_id" + " , apd.data_id, apd.applied_protocol_data_id, apd.direction" + " FROM applied_protocol ap LEFT JOIN experiment_applied_protocol eap" + " ON (eap.first_applied_protocol_id = ap.applied_protocol_id )" + " , applied_protocol_data apd" + " WHERE apd.applied_protocol_id = ap.applied_protocol_id" + " ORDER By 3,5,6"; return doQuery(connection, query, "getDAG"); } /** * Applies iteratively buildADaglevel * * @throws SQLException * @throws ObjectStoreException */ private void traverseDag() throws ObjectStoreException { List<Integer> currentIterationAP = firstAppliedProtocols; List<Integer> nextIterationAP = new ArrayList<Integer>(); Integer step = 1; // DAG level while (currentIterationAP.size() > 0) { nextIterationAP = buildADagLevel (currentIterationAP, step); currentIterationAP = nextIterationAP; step++; } } /** * This method is given a set of applied protocols (already associated with a submission) * and produces the next set of applied protocols. The latter are the protocols attached to the * output data of the starting set (output data for a applied protocol is the input data for the * next one). * It also fills the map linking directly results ('leaf' output data) with submission * * @param previousAppliedProtocols * @return the next batch of appliedProtocolId * @throws SQLException * @throws ObjectStoreException */ private List<Integer> buildADagLevel(List<Integer> previousAppliedProtocols, Integer step) throws ObjectStoreException { List<Integer> nextIterationProtocols = new ArrayList<Integer>(); Iterator<Integer> pap = previousAppliedProtocols.iterator(); while (pap.hasNext()) { List<Integer> outputs = new ArrayList<Integer>(); List<Integer> inputs = new ArrayList<Integer>(); Integer currentId = pap.next(); // add the DAG level here only if these are the first AP if (step == 1) { appliedProtocolMap.get(currentId).step = step; } outputs.addAll(appliedProtocolMap.get(currentId).outputs); Integer submissionId = appliedProtocolMap.get(currentId).submissionId; Iterator<Integer> od = outputs.iterator(); while (od.hasNext()) { Integer currentOD = od.next(); List<Integer> nextProtocols = new ArrayList<Integer>(); // build map submission-data mapSubmissionAndData(submissionId, currentOD); if (appliedDataMap.containsKey(currentOD)) { // fill the list of next (children) protocols nextProtocols.addAll(appliedDataMap.get(currentOD).nextAppliedProtocols); if (appliedDataMap.get(currentOD).nextAppliedProtocols.isEmpty()) { // this is a leaf!! LOG.debug("DAG leaf: " + submissionId + " dataId: " + currentOD); } } // to fill submission-dataId map // this is needed, otherwise inputs to AP that are not outputs // of a previous protocol are not considered inputs.addAll(appliedProtocolMap.get(currentId).inputs); Iterator<Integer> in = inputs.iterator(); while (in.hasNext()) { Integer currentIn = in.next(); // build map submission-data mapSubmissionAndData(submissionId, currentIn); } // build the list of children applied protocols chado identifiers // as input for the next iteration Iterator<Integer> nap = nextProtocols.iterator(); while (nap.hasNext()) { // and fill the map with the chado experiment_id and the DAG level Integer currentAPId = nap.next(); appliedProtocolMap.get(currentAPId).submissionId = submissionId; appliedProtocolMap.get(currentAPId).step = step + 1; nextIterationProtocols.add(currentAPId); // and set the reference from applied protocol to the submission Reference reference = new Reference(); reference.setName("submission"); reference.setRefId(submissionMap.get(submissionId).itemIdentifier); getChadoDBConverter().store(reference, appliedProtocolIdMap.get(currentAPId)); } } } return nextIterationProtocols; } /** * ============== * ORGANISM * ============== * Organism for a submission is derived from the organism associated with * the protocol of the first applied protocol (of the submission). * it is the name. a request to associate the submission directly with * the taxonid has been made to chado people. * * @param connection * @throws SQLException * @throws ObjectStoreException */ private void processSubmissionOrganism(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getSubmissionOrganism(connection); while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); if (deletedSubMap.containsKey(submissionId)) { continue; } String value = res.getString("value"); submissionOrganismMap.put(submissionId, value); LOG.debug("TAXID " + submissionId + "|" + value); } res.close(); LOG.info("found an organism for " + submissionOrganismMap.size() + " submissions."); LOG.info("PROCESS TIME organisms: " + (System.currentTimeMillis() - bT) + " ms"); } /** * Return the row needed for the organism. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getSubmissionOrganism(Connection connection) throws SQLException { String query = "select distinct eap.experiment_id, a.value " + " from experiment_applied_protocol eap, applied_protocol ap, " + " protocol_attribute pa, attribute a " + " where eap.first_applied_protocol_id = ap.applied_protocol_id " + " and ap.protocol_id=pa.protocol_id " + " and pa.attribute_id=a.attribute_id " + " and a.heading='species' "; return doQuery(connection, query, "getSubmissionOrganism"); } /** * ============== * PROJECT * ============== * Projects are loaded statically. A map is built between submissionId and * project's name and used for the references. 2 maps store intermine * objectId and itemId, with key the project name. * Note: the project name in chado is the surname of the PI * * @param connection * @throws SQLException * @throws ObjectStoreException */ private void processProjectTable(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getProjects(connection); while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); String value = res.getString("value"); if (deletedSubMap.containsKey(submissionId)) { continue; } submissionProjectMap.put(submissionId, value); } res.close(); Set<Integer> exp = submissionProjectMap.keySet(); Iterator<Integer> i = exp.iterator(); while (i.hasNext()) { Integer thisExp = i.next(); String project = submissionProjectMap.get(thisExp); if (projectIdMap.containsKey(project)) { continue; } LOG.debug("PROJECT: " + project); Item pro = getChadoDBConverter().createItem("Project"); pro.setAttribute("surnamePI", project); Integer intermineObjectId = getChadoDBConverter().store(pro); storeInProjectMaps(pro, project, intermineObjectId); } LOG.info("created " + projectIdMap.size() + " project"); LOG.info("PROCESS TIME projects: " + (System.currentTimeMillis() - bT) + " ms"); } /** * Return the project name. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getProjects(Connection connection) throws SQLException { String query = "SELECT distinct a.experiment_id, a.value " + " FROM experiment_prop a " + " where a.name = 'Project' " + " AND rank=0"; return doQuery(connection, query, "getProjects"); } /** * ============== * LAB * ============== * Labs are also loaded statically (affiliation is not given in the chado file). * A map is built between submissionId and * lab's name and used for the references. 2 maps store intermine * objectId and itemId, with key the lab name. * TODO: do project and lab together (1 query, 1 process) * * @param connection * @throws SQLException * @throws ObjectStoreException */ private void processLabTable(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getLabs(connection); while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); String value = res.getString("value"); if (deletedSubMap.containsKey(submissionId)) { continue; } submissionLabMap.put(submissionId, value); } res.close(); Set<Integer> exp = submissionLabMap.keySet(); Iterator<Integer> i = exp.iterator(); while (i.hasNext()) { Integer thisExp = i.next(); String prov = submissionLabMap.get(thisExp); String project = submissionProjectMap.get(thisExp); if (labIdMap.containsKey(prov)) { continue; } LOG.debug("PROV: " + prov); Item lab = getChadoDBConverter().createItem("Lab"); lab.setAttribute("surname", prov); lab.setReference("project", projectIdRefMap.get(project)); Integer intermineObjectId = getChadoDBConverter().store(lab); storeInLabMaps(lab, prov, intermineObjectId); } LOG.info("created " + labIdMap.size() + " labs"); LOG.info("PROCESS TIME labs: " + (System.currentTimeMillis() - bT) + " ms"); } /** * Return the lab name. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getLabs(Connection connection) throws SQLException { String query = "SELECT distinct a.experiment_id, a.name, a.value " + " FROM experiment_prop a " + " where a.name = 'Lab' " + " AND a.rank=0"; return doQuery(connection, query, "getLabs"); } /** * ================ * EXPERIMENT * ================ * Experiment is a collection of submissions. They all share the same description. * It has been added later to the model. * A map is built between submissionId and experiment name. * 2 maps store intermine objectId and itemId, with key the experiment name. * They are probably not needed. * */ private void processExperiment(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getExperimentTitles(connection); Map<String, String> expProMap = new HashMap<String, String>(); while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); if (deletedSubMap.containsKey(submissionId)) { continue; } String name = cleanWikiLinks(res.getString("name")); Util.addToListMap(expSubMap, name, submissionId); expProMap.put(name, submissionProjectMap.get(submissionId)); } res.close(); Set<String> experiment = expSubMap.keySet(); Iterator<String> i = experiment.iterator(); while (i.hasNext()) { String name = i.next(); Item exp = getChadoDBConverter().createItem("Experiment"); exp.setAttribute("name", name); // find experiment category from map (take first available) // use the commented lines to get a report of assignments String category = null; for (Integer ii : expSubMap.get(name)) { // String dccId = dccIdMap.get(ii); category = submissionExpCatMap.get(ii); if (category != null && !category.isEmpty()) { // LOG.info("ECS " + name + "|" + dccId + ": " + category); exp.setAttribute("category", category); break; } //else { //LOG.warn("ECS " + name + "|" + dccId + ": no category"); //} } String project = expProMap.get(name); exp.setReference("project", projectIdRefMap.get(project)); // note: the reference to submission collection is in a separate method Integer intermineObjectId = getChadoDBConverter().store(exp); experimentIdMap .put(name, intermineObjectId); experimentIdRefMap .put(name, exp.getIdentifier()); } LOG.info("created " + expSubMap.size() + " experiments"); LOG.info("PROCESS TIME experiments: " + (System.currentTimeMillis() - bT) + " ms"); } /** * method to clean a wiki reference (url to a named page) in chado * used also for experiment names * @param w the wiki reference */ private String cleanWikiLinks(String w) { String url = "http://wiki.modencode.org/project/index.php?title="; // we are stripping from first ':', maybe we want to include project suffix // e.g.: // original "http://...?title=Gene Model Prediction:SC:1&amp;oldid=12356" // now: Gene Model Prediction // maybe? Gene Model Prediction:SC:1 // (:->&) String w1 = StringUtils.replace(w, url, ""); String s1 = null; if (w1.contains(":")) { s1 = StringUtils.substringBefore(w1, ":"); } else { // for links missing the : char, e.g. // MacAlpine Early Origin of Replication Identification&oldid=10464 s1 = StringUtils.substringBefore(w1, "&"); } String s = s1.replace('"', ' ').trim(); if (s.contains("%E2%80%99")) { // prime: for the Piano experiment String s2 = s.replace("%E2%80%99", "'"); return s2; } if (s.contains("%28A%29%2B")) { // this is (A)+, in // Stranded Cell Line Transcriptional Profiling Using Illumina poly%28A%29%2B RNA-seq String s2 = s.replace("%28A%29%2B", "(A)+"); return s2; } if (s.contains("%2B")) { // +: for Celniker experiment "Tissue-specific Transcriptional Profiling..." String s2 = s.replace("%2B", "+"); return s2; } return s; } /** * Return the rows needed for experiment from the experiment_prop table. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getExperimentTitles(Connection connection) throws SQLException { // TODO use standard SQl and deal with string in java String query = "select e.experiment_id, " + " translate(x.accession, '_', ' ') as name " + " from experiment_prop e, dbxref x " + " where e.dbxref_id = x.dbxref_id " + " and e.name='Experiment Description' "; return doQuery(connection, query, "getExperimentTitles"); } /** * ================ * SUBMISSION * ================ */ private void processSubmission(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getSubmissions(connection); int count = 0; while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); if (deletedSubMap.containsKey(submissionId)) { continue; } String name = res.getString("uniquename"); Item submission = getChadoDBConverter().createItem("Submission"); submission.setAttribute("title", name); String project = submissionProjectMap.get(submissionId); String projectItemIdentifier = projectIdRefMap.get(project); submission.setReference("project", projectItemIdentifier); String labName = submissionLabMap.get(submissionId); String labItemIdentifier = labIdRefMap.get(labName); submission.setReference("lab", labItemIdentifier); String organismName = submissionOrganismMap.get(submissionId); int divPos = organismName.indexOf(' '); String genus = organismName.substring(0, divPos); String species = organismName.substring(divPos + 1); OrganismRepository or = OrganismRepository.getOrganismRepository(); Integer taxId = Integer.valueOf( or.getOrganismDataByGenusSpecies(genus, species).getTaxonId()); LOG.debug("SPECIES: " + organismName + "|" + taxId); String organismItemIdentifier = getChadoDBConverter().getOrganismItem( or.getOrganismDataByGenusSpecies(genus, species).getTaxonId()).getIdentifier(); submission.setReference("organism", organismItemIdentifier); // ..store all Integer intermineObjectId = getChadoDBConverter().store(submission); // ..and fill the SubmissionDetails object SubmissionDetails details = new SubmissionDetails(); details.interMineObjectId = intermineObjectId; details.itemIdentifier = submission.getIdentifier(); details.labItemIdentifier = labItemIdentifier; details.title = name; submissionMap.put(submissionId, details); debugMap .put(details.itemIdentifier, submission.getClassName()); count++; } LOG.info("created " + count + " submissions"); res.close(); LOG.info("PROCESS TIME submissions: " + (System.currentTimeMillis() - bT) + " ms"); } /** * Return the rows needed for the submission table. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getSubmissions(Connection connection) throws SQLException { String query = "SELECT experiment_id, uniquename " + "FROM experiment"; return doQuery(connection, query, "getSubmissions"); } /** * submission attributes (table experiment_prop) * * @param connection * @throws SQLException * @throws ObjectStoreException */ private void processSubmissionAttributes(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getExperimentProperties(connection); int count = 0; while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); if (deletedSubMap.containsKey(submissionId)) { continue; } String heading = res.getString("name"); String value = res.getString("value"); // TODO this is a temporary hack to make sure we get properly matched Experiment.factors // EF are dealt with separately if (heading.startsWith("Experimental Factor")) { continue; } String fieldName = FIELD_NAME_MAP.get(heading); if (fieldName == null) { LOG.error("NOT FOUND in FIELD_NAME_MAP: " + heading + " [experiment]"); continue; } else if (fieldName == NOT_TO_BE_LOADED) { continue; } if ("DCCid".equals(fieldName)) { value = DCC_PREFIX + value; LOG.debug("DCC: " + submissionId + ", " + value); dccIdMap.put(submissionId, value); } if ("category".equals(fieldName)) { // Data Type, stored in experiment submissionExpCatMap.put(submissionId, value); continue; } if (fieldName.endsWith("Read Count")) { // all read counts are considered a collection for submission Item readCount = getChadoDBConverter().createItem("ReadCount"); readCount.setAttribute("name", fieldName); readCount.setAttribute("value", value); // setting references to SubmissionData readCount.setReference("submission", submissionMap.get(submissionId).itemIdentifier); Integer intermineObjectId = getChadoDBConverter().store(readCount); continue; } if ("experimentType".equals(fieldName)) { // Assay Type submissionWithExpTypeSet.add(submissionId); } if ("pubMedId".equals(fieldName)) { // sometime in the form PMID:16938558 if (value.contains(":")) { value = value.substring(value.indexOf(':') + 1); } Item pub = getChadoDBConverter().createItem("Publication"); pub.setAttribute(fieldName, value); Integer intermineObjectId = getChadoDBConverter().store(pub); publicationIdMap.put(submissionId, intermineObjectId); publicationIdRefMap.put(submissionId, pub.getIdentifier()); continue; } setAttribute(submissionMap.get(submissionId).interMineObjectId, fieldName, value); count++; } LOG.info("created " + count + " submissions attributes"); res.close(); LOG.info("PROCESS TIME submissions attributes: " + (System.currentTimeMillis() - bT) + " ms"); } /** * Return the rows needed for submission from the experiment_prop table. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getExperimentProperties(Connection connection) throws SQLException { String query = "SELECT ep.experiment_id, ep.name, ep.value, ep.rank " + "from experiment_prop ep "; return doQuery(connection, query, "getExperimentProperties"); } /** * ========================== * EXPERIMENTAL FACTORS * ========================== */ private void processEFactor(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getEFactors(connection); int count = 0; int prevRank = -1; int prevSub = -1; ExperimentalFactor ef = null; String name = null; while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); if (deletedSubMap.containsKey(submissionId)) { continue; } Integer rank = new Integer(res.getInt("rank")); String value = res.getString("value"); // the data is alternating between EF types and names, in order. if (submissionId != prevSub) { // except for the first record, this is a new EF object if (!res.isFirst()) { submissionEFMap.put(prevSub, ef); LOG.info("EF MAP: " + dccIdMap.get(prevSub) + "|" + ef.efNames); LOG.info("EF MAP types: " + rank + "|" + ef.efTypes); } ef = new ExperimentalFactor(); } if (rank != prevRank || submissionId != prevSub) { // this is a name if (getPreferredSynonym(value) != null) { value = getPreferredSynonym(value); } ef.efNames.add(value); name = value; count++; } else { // this is a type ef.efTypes.put(name, value); name = null; if (res.isLast()) { submissionEFMap.put(submissionId, ef); LOG.debug("EF MAP last: " + submissionId + "|" + rank + "|" + ef.efNames); } } prevRank = rank; prevSub = submissionId; } res.close(); LOG.info("created " + count + " experimental factors"); LOG.info("PROCESS TIME experimental factors: " + (System.currentTimeMillis() - bT) + " ms"); } /** * Return the rows needed for the experimental factors. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getEFactors(Connection connection) throws SQLException { String query = "SELECT ep.experiment_id, ep.name, ep.value, ep.rank " + " FROM experiment_prop ep " + " where ep.name = 'Experimental Factor Name' " + " OR ep.name = 'Experimental Factor Type' " + " ORDER BY 1,4,2"; return doQuery(connection, query, "getEFactors"); } /** * ============== * PROTOCOL * ============== */ private void processProtocolTable(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getProtocols(connection); int count = 0; while (res.next()) { Integer protocolChadoId = new Integer(res.getInt("protocol_id")); String name = res.getString("name"); String description = res.getString("description"); String wikiLink = res.getString("accession"); Integer version = res.getInt("version"); // needed: it breaks otherwise if (description.length() == 0) { description = "N/A"; } Protocol thisProt = new Protocol(); thisProt.protocolId = protocolChadoId; // rm? thisProt.name = name; thisProt.description = description; thisProt.wikiLink = wikiLink; thisProt.version = version; protocolMap.put(protocolChadoId, thisProt); // we'll do it when creating AP //createProtocol(protocolChadoId, name, description, wikiLink, version); count++; } res.close(); LOG.info("found " + count + " protocols"); LOG.info("PROCESS TIME protocols: " + (System.currentTimeMillis() - bT) + " ms"); } // now doing it with applied protocol (to avoid creating it for delete subs) private String createProtocol(Integer chadoId, String name, String description, String wikiLink, Integer version) throws ObjectStoreException { String protocolItemId = protocolsMap.get(wikiLink); // rename? if (protocolItemId == null) { Item protocol = getChadoDBConverter().createItem("Protocol"); protocol.setAttribute("name", name); protocol.setAttribute("description", description); protocol.setAttribute("wikiLink", wikiLink); protocol.setAttribute("version", "" + version); Integer intermineObjectId = getChadoDBConverter().store(protocol); protocolItemId = protocol.getIdentifier(); protocolItemToObjectId.put(protocolItemId, intermineObjectId); protocolsMap.put(wikiLink, protocolItemId); } protocolItemIds.put(chadoId, protocolItemId); return protocolItemId; } private Integer getProtocolInterMineId(Integer chadoId) { return protocolItemToObjectId.get(protocolItemIds.get(chadoId)); } /** * Return the rows needed from the protocol table. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getProtocols(Connection connection) throws SQLException { String query = "SELECT protocol_id, name, protocol.description, accession, protocol.version" + " FROM protocol, dbxref" + " WHERE protocol.dbxref_id = dbxref.dbxref_id"; return doQuery(connection, query, "getProtocols"); } /** * to store protocol attributes */ private void processProtocolAttributes(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getProtocolAttributes(connection); int count = 0; while (res.next()) { Integer protocolId = new Integer(res.getInt("protocol_id")); String heading = res.getString("heading"); String value = res.getString("value"); String fieldName = FIELD_NAME_MAP.get(heading); if (fieldName == null) { LOG.error("NOT FOUND in FIELD_NAME_MAP: " + heading + " [protocol]"); continue; } else if (fieldName == NOT_TO_BE_LOADED) { continue; } if (getProtocolInterMineId(protocolId) != null) { // in case of deleted sub setAttribute(getProtocolInterMineId(protocolId), fieldName, value); if ("type".equals(fieldName)) { protocolTypesMap.put(protocolId, value); } count++; } } LOG.info("created " + count + " protocol attributes"); res.close(); LOG.info("PROCESS TIME protocol attributes: " + (System.currentTimeMillis() - bT) + " ms"); } /** * Return the rows needed for protocols from the attribute table. * This is a protected method so that it can be overridden for testing * @param connection database connection * @return rows needed for protocols from the attribute table * @throws SQLException if something goes wrong. */ protected ResultSet getProtocolAttributes(Connection connection) throws SQLException { String query = "SELECT p.protocol_id, a.heading, a.value " + "from protocol p, attribute a, protocol_attribute pa " + "where pa.attribute_id = a.attribute_id " + "and pa.protocol_id = p.protocol_id "; return doQuery(connection, query, "getProtocolAttributes"); } /** * ====================== * APPLIED PROTOCOL * ====================== */ private void processAppliedProtocolTable(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getAppliedProtocols(connection); int count = 0; boolean isADeletedSub = false; while (res.next()) { Integer appliedProtocolId = new Integer(res.getInt("applied_protocol_id")); Integer protocolId = new Integer(res.getInt("protocol_id")); Integer submissionId = new Integer(res.getInt("experiment_id")); // the results are ordered, first ap have a subId // if we find a deleted sub, we know that subsequent records with null // subId belongs to the deleted sub if (submissionId == 0) { boolean t = true; if (isADeletedSub == t) { continue; } } else { if (deletedSubMap.containsKey(submissionId)) { isADeletedSub = true; continue; } else { isADeletedSub = false; } } Item appliedProtocol = getChadoDBConverter().createItem("AppliedProtocol"); // creating and setting references to protocols // String protocolItemId = protocolItemIds.get(protocolId); if (protocolId != null) { Protocol qq = protocolMap.get(protocolId); String protocolItemId = createProtocol(qq); appliedProtocol.setReference("protocol", protocolItemId); } if (submissionId > 0) { // setting reference to submission // probably to rm (we do it later anyway). TODO: check appliedProtocol.setReference("submission", submissionMap.get(submissionId).itemIdentifier); } // store it and add to maps Integer intermineObjectId = getChadoDBConverter().store(appliedProtocol); appliedProtocolIdMap .put(appliedProtocolId, intermineObjectId); appliedProtocolIdRefMap .put(appliedProtocolId, appliedProtocol.getIdentifier()); count++; } LOG.info("created " + count + " appliedProtocol"); res.close(); LOG.info("PROCESS TIME applied protocols: " + (System.currentTimeMillis() - bT) + " ms"); } private String createProtocol(Protocol p) throws ObjectStoreException { String protocolItemId = protocolsMap.get(p.wikiLink); // rename map? if (protocolItemId == null) { Item protocol = getChadoDBConverter().createItem("Protocol"); protocol.setAttribute("name", p.name); protocol.setAttribute("description", p.description); protocol.setAttribute("wikiLink", p.wikiLink); protocol.setAttribute("version", "" + p.version); Integer intermineObjectId = getChadoDBConverter().store(protocol); protocolItemId = protocol.getIdentifier(); protocolItemToObjectId.put(protocolItemId, intermineObjectId); protocolsMap.put(p.wikiLink, protocolItemId); } protocolItemIds.put(p.protocolId, protocolItemId); return protocolItemId; } /** * Return the rows needed from the appliedProtocol table. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getAppliedProtocols(Connection connection) throws SQLException { String query = "SELECT eap.experiment_id ,ap.applied_protocol_id, ap.protocol_id" + " FROM applied_protocol ap" + " LEFT JOIN experiment_applied_protocol eap" + " ON (eap.first_applied_protocol_id = ap.applied_protocol_id )"; return doQuery(connection, query, "getAppliedProtocols"); } /** * ====================== * APPLIED DATA * ====================== */ private void processAppliedData(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getAppliedData(connection); int count = 0; while (res.next()) { Integer dataId = new Integer(res.getInt("data_id")); // check if not belonging to a deleted sub Integer submissionId = dataSubmissionMap.get(dataId); if (submissionId == null || deletedSubMap.containsKey(submissionId)) { continue; } String name = res.getString("name"); String heading = res.getString("heading"); String value = res.getString("value"); String typeId = res.getString("type_id"); String url = res.getString("url"); // check if this datum has an official name: ResultSet oName = getOfficialName(connection, dataId); String officialName = null; while (oName.next()) { officialName = oName.getString(1); } // if there is one, use it instead of the value String datumType = getCvterm(connection, typeId); name = getCvterm(connection, typeId); if (!StringUtils.isEmpty(officialName) && doReplaceWithOfficialName(heading, datumType)) { value = officialName; } Item submissionData = getChadoDBConverter().createItem("SubmissionData"); if (name != null && !"".equals(name)) { submissionData.setAttribute("name", name); } // if no name for attribute fetch the cvterm of the type if ((name == null || "".equals(name)) && typeId != null) { name = getCvterm(connection, typeId); submissionData.setAttribute("name", name); } if (!StringUtils.isEmpty(value)) { submissionData.setAttribute("value", value); } submissionData.setAttribute("type", heading); // store it and add to object and maps Integer intermineObjectId = getChadoDBConverter().store(submissionData); AppliedData aData = new AppliedData(); aData.intermineObjectId = intermineObjectId; aData.itemIdentifier = submissionData.getIdentifier(); aData.value = value; aData.actualValue = res.getString("value"); aData.dataId = dataId; aData.type = heading; aData.name = name; aData.url = url; updateADMap(aData, dataId, intermineObjectId); //appliedDataMap.put(dataId, aData); count++; } LOG.info("created " + count + " SubmissionData"); res.close(); LOG.info("PROCESS TIME submission data: " + (System.currentTimeMillis() - bT) + " ms"); } // For some data types we don't want to replace with official name - e.g. file names and // database record ids. It looks like the official name shouldn't actually be present. private boolean doReplaceWithOfficialName(String heading, String type) { if ("Result File".equals(heading)) { return false; } if ("Result Value".equals(heading) && DB_RECORD_TYPES.contains(type)) { return false; } return true; } /** * Return the rows needed for data from the applied_protocol_data table. * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getAppliedData(Connection connection) throws SQLException { String query = "SELECT d.data_id," + " d.heading, d.name, d.value, d.type_id, z.url" + " FROM data d" + " LEFT JOIN dbxref as y ON (d.dbxref_id = y.dbxref_id)" + " LEFT JOIN db as z ON (y.db_id = z.db_id)"; return doQuery(connection, query, "getAppliedData"); } /** * Return the rows needed for data from the applied_protocol_data table. * * @param connection the db connection * @param dataId the dataId * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getOfficialName(Connection connection, Integer dataId) throws SQLException { String query = "SELECT a.value " + " from attribute a, data_attribute da " + " where a.attribute_id=da.attribute_id " + " and da.data_id=" + dataId + " and a.heading='official name'"; return doQuery(connection, query); } /** * Fetch a cvterm by id and cache results in cvtermCache. Returns null if the cv terms isn't * found. * @param connection to chado database * @param cvtermId internal chado id for a cvterm * @return the cvterm name or null if not found * @throws SQLException if database access problem */ private String getCvterm(Connection connection, String cvtermId) throws SQLException { String cvTerm = cvtermCache.get(cvtermId); if (cvTerm == null) { String query = "SELECT c.name " + " from cvterm c" + " where c.cvterm_id=" + cvtermId; Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); while (res.next()) { cvTerm = res.getString("name"); } cvtermCache.put(cvtermId, cvTerm); } return cvTerm; } /** * ===================== * DATA ATTRIBUTES * ===================== */ private void processAppliedDataAttributesNEW(Connection connection) throws SQLException, ObjectStoreException { // attempts to collate attributes // TODO check! long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getAppliedDataAttributes(connection); int count = 0; Integer previousDataId = 0; String previousName = null; String value = null; String type = null; while (res.next()) { Integer dataId = new Integer(res.getInt("data_id")); // check if not belonging to a deleted sub // better way? Integer submissionId = dataSubmissionMap.get(dataId); if (submissionId == null || deletedSubMap.containsKey(submissionId)) { continue; } String name = res.getString("heading"); // LOG.info("DA " + dataId + ": " + name); if (previousDataId == 0) { //first pass value = res.getString("value"); type = res.getString("name"); previousDataId = dataId; previousName = name; LOG.info("DA0 " + dataId + ": " + name + "|" + value); continue; } if (dataId > previousDataId) { Item dataAttribute = storeDataAttribute(value, type, previousDataId, previousName); value = res.getString("value"); type = res.getString("name"); count++; previousDataId = dataId; previousName = name; LOG.info("DA1 new: " + previousDataId + ": " + previousName + "|" + value); continue; } if (!name.equalsIgnoreCase(previousName)) { Item dataAttribute = storeDataAttribute(value, type, dataId, previousName); // LOG.info("DA2 store: " + dataId + ": " + previousName + "|" + value); count ++; value = res.getString("value"); previousName = name; LOG.info("DA2 new: " + dataId + ": " + previousName + "|" + value); } else { value = value + ", " + res.getString("value"); } type = res.getString("name"); previousDataId = dataId; if (res.isLast()) { Item dataAttribute = storeDataAttribute(value, type, dataId, name); count++; } } LOG.info("created " + count + " data attributes"); res.close(); LOG.info("PROCESS TIME data attributes: " + (System.currentTimeMillis() - bT) + " ms"); } /** * @param value * @param type * @param dataId * @param name * @return * @throws ObjectStoreException */ private Item storeDataAttribute(String value, String type, Integer dataId, String name) throws ObjectStoreException { Item dataAttribute = getChadoDBConverter().createItem("SubmissionDataAttribute"); if (name != null && !"".equals(name)) { dataAttribute.setAttribute("name", name); } if (!StringUtils.isEmpty(value)) { dataAttribute.setAttribute("value", value); } if (!StringUtils.isEmpty(type)) { dataAttribute.setAttribute("type", type); } // setting references to SubmissionData dataAttribute.setReference("submissionData", appliedDataMap.get(dataId).itemIdentifier); getChadoDBConverter().store(dataAttribute); return dataAttribute; } private void processAppliedDataAttributes(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getAppliedDataAttributes(connection); int count = 0; while (res.next()) { Integer dataId = new Integer(res.getInt("data_id")); // check if not belonging to a deleted sub // better way? Integer submissionId = dataSubmissionMap.get(dataId); if (submissionId == null || deletedSubMap.containsKey(submissionId)) { continue; } String name = res.getString("heading"); String value = res.getString("value"); String type = res.getString("name"); Item dataAttribute = storeDataAttribute(value, type, dataId, name); count++; } LOG.info("created " + count + " data attributes"); res.close(); LOG.info("PROCESS TIME data attributes: " + (System.currentTimeMillis() - bT) + " ms"); } // first value in the list of synonyms is the 'preferred' value private static String[][] synonyms = new String[][]{ new String[] {"developmental stage", "stage", "developmental_stage", "dev stage", "devstage"}, new String[] {"strain", "strain_or_line"}, new String[] {"cell line", "cell_line", "Cell line", "cell id"}, new String[] {"array", "adf"}, new String[] {"compound", "Compound"}, new String[] {"incubation time", "Incubation Time"}, new String[] {"RNAi reagent", "RNAi_reagent", "dsRNA"}, new String[] {"temperature", "temp"} }; private static List<String> makeLookupList(String initialLookup) { for (String[] synonymType : synonyms) { for (String synonym : synonymType) { if (synonym.equals(initialLookup)) { return Arrays.asList(synonymType); } } } return new ArrayList<String>(Collections.singleton(initialLookup)); } private static String getPreferredSynonym(String initialLookup) { return makeLookupList(initialLookup).get(0); } private static Set<String> unifyFactorNames(Collection<String> original) { Set<String> unified = new HashSet<String>(); for (String name : original) { unified.add(getPreferredSynonym(name)); } return unified; } private class SubmissionReference { public SubmissionReference(Integer referencedSubmissionId, String dataValue) { this.referencedSubmissionId = referencedSubmissionId; this.dataValue = dataValue; } private Integer referencedSubmissionId; private String dataValue; } // process new query // get DCC id // add antibody to types private void processSubmissionProperties(Connection connection) throws SQLException, IOException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getAppliedDataAll(connection); final String comma = ","; String reportName = "build/" + getChadoDBConverter().getDatabase().getName() + "_subs_report.csv"; File f = new File(reportName); FileWriter writer = new FileWriter(f); writeHeader(comma, writer); SubmissionProperty buildSubProperty = null; Integer lastDataId = new Integer(-1); Map<String, SubmissionProperty> props = new HashMap<String, SubmissionProperty>(); Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes = new HashMap<Integer, Map<String, List<SubmissionProperty>>>(); submissionRefs = new HashMap<Integer, List<SubmissionReference>>(); while (res.next()) { Integer dataId = new Integer(res.getInt("data_id")); String dataHeading = res.getString("data_heading"); String dataName = res.getString("data_name"); String wikiPageUrl = res.getString("data_value"); String cvTerm = res.getString("cv_term"); String attHeading = res.getString("att_heading"); String attName = res.getString("att_name"); String attValue = res.getString("att_value"); String attDbxref = res.getString("att_dbxref"); int attRank = res.getInt("att_rank"); Integer submissionId = dataSubmissionMap.get(dataId); String dccId = dccIdMap.get(submissionId); writer.write(dccId + comma + dataHeading + comma + dataName + comma + wikiPageUrl + comma + cvTerm + comma + attHeading + comma + attName + comma + attValue + comma + attDbxref + System.getProperty("line.separator")); if (submissionId == null) { LOG.warn("Failed to find a submission id for data id " + dataId + " - this probably" + " means there is a problem with the applied_protocol DAG strucuture."); continue; } // Currently using attValue for referenced submission DCC id, should be dbUrl but seems // to be filled in incorrectly if (attHeading != null && attHeading.startsWith("modENCODE Reference")) { attValue = checkRefSub(wikiPageUrl, attValue, submissionId, dccId); } // we are starting a new data row if (dataId.intValue() != lastDataId.intValue()) { // have we seen this modencodewiki entry before? if (props.containsKey(wikiPageUrl)) { buildSubProperty = null; } else { buildSubProperty = new SubmissionProperty(getPreferredSynonym(dataName), wikiPageUrl); props.put(wikiPageUrl, buildSubProperty); } // submissionId -> [type -> SubmissionProperty] addToSubToTypes(subToTypes, submissionId, props.get(wikiPageUrl)); } if (buildSubProperty != null) { // we are building a new submission attribute, this is the first time we have // seen a data.value that points to modencodewiki buildSubProperty.addDetail(attHeading, attValue, attRank); } lastDataId = dataId; } writer.flush(); writer.close(); // Characteristics are modelled differently to protocol inputs/outputs, read in extra // properties here addSubmissionPropsFromCharacteristics(subToTypes, connection); // some submissions use reagents created in reference submissions, find the properties // of the reagents and add to referencing submission addSubmissionPropsFromReferencedSubmissions(subToTypes, props, submissionRefs); // create and store properties of submission storeSubProperties(subToTypes); LOG.info("PROCESS TIME submission properties: " + (System.currentTimeMillis() - bT) + " ms"); } /** * @param subToTypes * @throws ObjectStoreException */ private void storeSubProperties( Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes) throws ObjectStoreException { for (Integer submissionId : subToTypes.keySet()) { Integer storedSubmissionId = submissionMap.get(submissionId).interMineObjectId; if (deletedSubMap.containsKey(submissionId)) { continue; } Map<String, List<SubmissionProperty>> typeToProp = subToTypes.get(submissionId); String dccId = dccIdMap.get(submissionId); ExperimentalFactor ef = submissionEFMap.get(submissionId); if (ef == null) { LOG.warn("No experimental factors found for submission: " + dccId); continue; } Set<String> exFactorNames = unifyFactorNames(ef.efNames); LOG.info("PROPERTIES " + dccId + " typeToProp keys: " + typeToProp.keySet()); List<Item> allPropertyItems = new ArrayList<Item>(); // DEVELOPMENTAL STAGE List<Item> devStageItems = new ArrayList<Item>(); devStageItems.addAll(createFromWikiPage(dccId, "DevelopmentalStage", typeToProp, makeLookupList("developmental stage"))); if (devStageItems.isEmpty()) { devStageItems.addAll(lookForAttributesInOtherWikiPages(dccId, "DevelopmentalStage", typeToProp, new String[] { "developmental stage.developmental stage", "tissue.developmental stage", "tissue source.developmental stage", "cell line.developmental stage", "cell id.developmental stage" //, "RNA extract.Cell Type" })); } if (!devStageItems.isEmpty() && exFactorNames.contains("developmental stage")) { createExperimentalFactors(submissionId, "developmental stage", devStageItems); exFactorNames.remove("developmental stage"); } if (devStageItems.isEmpty()) { addNotApplicable("DevelopmentalStage", "developmental stage"); } storeSubmissionCollection(storedSubmissionId, "developmentalStages", devStageItems); allPropertyItems.addAll(devStageItems); // STRAIN List<Item> strainItems = new ArrayList<Item>(); strainItems.addAll(createFromWikiPage( dccId, "Strain", typeToProp, makeLookupList("strain"))); if (!strainItems.isEmpty() && exFactorNames.contains("strain")) { createExperimentalFactors(submissionId, "strain", strainItems); exFactorNames.remove("strain"); } if (strainItems.isEmpty()) { addNotApplicable("Strain", "strain"); } storeSubmissionCollection(storedSubmissionId, "strains", strainItems); allPropertyItems.addAll(strainItems); // ARRAY List<Item> arrayItems = new ArrayList<Item>(); arrayItems.addAll(createFromWikiPage( dccId, "Array", typeToProp, makeLookupList("array"))); if (arrayItems.isEmpty()) { arrayItems.addAll(lookForAttributesInOtherWikiPages(dccId, "Array", typeToProp, new String[] {"adf.official name"})); if (!arrayItems.isEmpty()) { LOG.debug("Attribute found in other wiki pages: " + dccId + " ARRAY "); } } if (!arrayItems.isEmpty() && exFactorNames.contains("array")) { createExperimentalFactors(submissionId, "array", arrayItems); exFactorNames.remove("array"); } if (arrayItems.isEmpty()) { addNotApplicable("Array", "array"); } storeSubmissionCollection(storedSubmissionId, "arrays", arrayItems); allPropertyItems.addAll(arrayItems); // CELL LINE List<Item> lineItems = new ArrayList<Item>(); lineItems.addAll(createFromWikiPage(dccId, "CellLine", typeToProp, makeLookupList("cell line"))); if (!lineItems.isEmpty() && exFactorNames.contains("cell line")) { createExperimentalFactors(submissionId, "cell line", lineItems); exFactorNames.remove("cell line"); } if (lineItems.isEmpty()) { addNotApplicable("CellLine", "cell line"); } storeSubmissionCollection(storedSubmissionId, "cellLines", lineItems); allPropertyItems.addAll(lineItems); // RNAi REAGENT List<Item> reagentItems = new ArrayList<Item>(); reagentItems.addAll(createFromWikiPage(dccId, "SubmissionProperty", typeToProp, makeLookupList("dsRNA"))); if (!reagentItems.isEmpty() && exFactorNames.contains("RNAi reagent")) { createExperimentalFactors(submissionId, "RNAi reagent", reagentItems); exFactorNames.remove("RNAi reagent"); } allPropertyItems.addAll(reagentItems); // ANTIBODY List<Item> antibodyItems = new ArrayList<Item>(); antibodyItems.addAll(createFromWikiPage(dccId, "Antibody", typeToProp, makeLookupList("antibody"))); if (antibodyItems.isEmpty()) { LOG.debug("ANTIBODY: " + typeToProp.get("antibody")); antibodyItems.addAll(lookForAttributesInOtherWikiPages(dccId, "Antibody", typeToProp, new String[] {"antibody.official name"})); if (!antibodyItems.isEmpty()) { LOG.debug("Attribute found in other wiki pages: " + dccId + " ANTIBODY "); } } if (!antibodyItems.isEmpty() && exFactorNames.contains("antibody")) { createExperimentalFactors(submissionId, "antibody", antibodyItems); exFactorNames.remove("antibody"); } if (antibodyItems.isEmpty()) { addNotApplicable("Antibody", "antibody"); } storeSubmissionCollection(storedSubmissionId, "antibodies", antibodyItems); allPropertyItems.addAll(antibodyItems); // TISSUE List<Item> tissueItems = new ArrayList<Item>(); tissueItems.addAll(createFromWikiPage( dccId, "Tissue", typeToProp, makeLookupList("tissue"))); if (tissueItems.isEmpty()) { tissueItems.addAll(lookForAttributesInOtherWikiPages(dccId, "Tissue", typeToProp, new String[] {"stage.tissue" , "cell line.tissue" , "cell id.tissue"})); if (!tissueItems.isEmpty()) { LOG.info("Attribute found in other wiki pages: " + dccId + " TISSUE"); } } if (!tissueItems.isEmpty() && exFactorNames.contains("tissue")) { createExperimentalFactors(submissionId, "tissue", tissueItems); exFactorNames.remove("tissue"); } if (tissueItems.isEmpty()) { addNotApplicable("Tissue", "tissue"); } storeSubmissionCollection(storedSubmissionId, "tissues", tissueItems); allPropertyItems.addAll(tissueItems); // There may be some other experimental factors that require SubmissionProperty objects // but don't fall into the categories above. Create them here and set experimental // factors. ArrayList<String> extraPropNames = new ArrayList<String>(exFactorNames); for (String exFactor : extraPropNames) { List<Item> extraPropItems = new ArrayList<Item>(); extraPropItems.addAll(lookForAttributesInOtherWikiPages(dccId, "SubmissionProperty", typeToProp, new String[] {exFactor})); allPropertyItems.addAll(extraPropItems); createExperimentalFactors(submissionId, exFactor, extraPropItems); exFactorNames.remove(exFactor); } // deal with remaining factor names (e.g. the ones for which we did // not find a corresponding attribute for (String exFactor : exFactorNames) { String type = ef.efTypes.get(exFactor); createEFItem(submissionId, type, exFactor, null); } storeSubmissionCollection(storedSubmissionId, "properties", allPropertyItems); } } /** * @param wikiPageUrl * @param attValue * @param submissionId * @param dccId * @return */ private String checkRefSub(String wikiPageUrl, String attValue, Integer submissionId, String dccId) { if (attValue.indexOf(":") > 0) { attValue = attValue.substring(0, attValue.indexOf(":")); } attValue = DCC_PREFIX + attValue; Integer referencedSubId = getSubmissionIdFromDccId(attValue); if (referencedSubId != null) { SubmissionReference subRef = new SubmissionReference(referencedSubId, wikiPageUrl); Util.addToListMap(submissionRefs, submissionId, subRef); LOG.info("Submission " + dccId + " (" + submissionId + ") has reference to " + attValue + " (" + referencedSubId + ")"); } else { LOG.warn("Could not find submission " + attValue + " referenced by " + dccId); } return attValue; } /** * @param comma * @param writer * @throws IOException */ private void writeHeader(final String comma, FileWriter writer) throws IOException { writer.write("submission" + comma); writer.write("data_heading" + comma); writer.write("data_name" + comma); writer.write("data_value" + comma); writer.write("cv_term" + comma); writer.write("att_heading" + comma); writer.write("att_name" + comma); writer.write("att_value" + comma); writer.write(System.getProperty("line.separator")); } // /** // * @param submissionId // * @param exFactorNames // * @param devStageItems // * @param clsName // * @param propName // * @throws ObjectStoreException // */ // private void finishProp(Integer submissionId, Integer storedSubmissionId, // Set<String> exFactorNames, // List<Item> devStageItems, String clsName, String propName) // throws ObjectStoreException { // if (devStageItems.isEmpty()) { // addNotApplicable(devStageItems, clsName, propName); // storeSubmissionCollection(storedSubmissionId, "developmentalStages", devStageItems); // } else { // if (exFactorNames.contains(propName)) { // createExperimentalFactors(submissionId, propName, devStageItems); // exFactorNames.remove(propName); // } // } // } /** * @param clsName the class name of the property (e.g. Strain) * @param propName the property name (e.g. strain) * @throws ObjectStoreException */ private void addNotApplicable(String clsName, String propName) throws ObjectStoreException { Item subProperty = getChadoDBConverter().createItem(clsName); subProperty.setAttribute("type", propName); subProperty.setAttribute("name", NA_PROP); getChadoDBConverter().store(subProperty); } // Traverse DAG following previous applied protocol links to build a list of all AppliedData private void findAppliedProtocolsAndDataFromEarlierInDag(Integer startDataId, List<AppliedData> foundAppliedData, List<AppliedProtocol> foundAppliedProtocols) { AppliedData aData = appliedDataMap.get(startDataId); if (foundAppliedData != null) { foundAppliedData.add(aData); } for (Integer previousAppliedProtocolId : aData.previousAppliedProtocols) { AppliedProtocol ap = appliedProtocolMap.get(previousAppliedProtocolId); if (foundAppliedProtocols != null) { foundAppliedProtocols.add(ap); } for (Integer previousDataId : ap.inputs) { findAppliedProtocolsAndDataFromEarlierInDag(previousDataId, foundAppliedData, foundAppliedProtocols); } } } private void createExperimentalFactors(Integer submissionId, String type, Collection<Item> items) throws ObjectStoreException { for (Item item : items) { createEFItem(submissionId, type, item.getAttribute("name").getValue(), item.getIdentifier()); } } private void createEFItemNEW(Integer current, String type, String efName, String propertyIdentifier) throws ObjectStoreException { // don't create an EF if it is a primer if (type.endsWith("primer")) { return; } String preferredType = getPreferredSynonym(type); String key = efName + preferredType; String [] efTok = {efName,preferredType}; // create the EF, if not there already if (!eFactorIdMap.containsKey(key)) { Item ef = getChadoDBConverter().createItem("ExperimentalFactor"); ef.setAttribute ("type", preferredType); ef.setAttribute ("name", efName); if (propertyIdentifier != null) { ef.setReference("property", propertyIdentifier); } LOG.info("ExFactor created for sub " + dccIdMap.get(current) + ":" + efName + "|" + type); Integer intermineObjectId = getChadoDBConverter().store(ef); eFactorIdMap.put(key, intermineObjectId); eFactorIdRefMap.put(key, ef.getIdentifier()); } // if pertinent to the current sub, add to the map for the references Util.addToListMap(submissionEFactorMap2, current, efTok); } private void createEFItem(Integer current, String type, String efName, String propertyIdentifier) throws ObjectStoreException { // don't create an EF if it is a primer if (type.endsWith("primer")) { return; } // create the EF, if not there already if (!eFactorIdMap.containsKey(efName)) { Item ef = getChadoDBConverter().createItem("ExperimentalFactor"); String preferredType = getPreferredSynonym(type); ef.setAttribute ("type", preferredType); ef.setAttribute ("name", efName); if (propertyIdentifier != null) { ef.setReference("property", propertyIdentifier); } LOG.info("ExFactor created for sub " + current + ":" + efName + "|" + type); Integer intermineObjectId = getChadoDBConverter().store(ef); eFactorIdMap.put(efName, intermineObjectId); eFactorIdRefMap.put(efName, ef.getIdentifier()); } // if pertinent to the current sub, add to the map for the references Util.addToListMap(submissionEFactorMap, current, efName); } private void addToSubToTypes(Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes, Integer submissionId, SubmissionProperty prop) { // submissionId -> [type -> SubmissionProperty] if (submissionId == null) { LOG.error("MISSING SUB: " + prop); return; //throw new RuntimeException("Called addToSubToTypes with a null sub id!"); } Map<String, List<SubmissionProperty>> typeToSubProp = subToTypes.get(submissionId); if (typeToSubProp == null) { typeToSubProp = new HashMap<String, List<SubmissionProperty>>(); subToTypes.put(submissionId, typeToSubProp); } List<SubmissionProperty> subProps = typeToSubProp.get(prop.type); if (subProps == null) { subProps = new ArrayList<SubmissionProperty>(); typeToSubProp.put(prop.type, subProps); } subProps.add(prop); } private void addSubmissionPropsFromCharacteristics( Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes, Connection connection) throws SQLException { ResultSet res = getAppliedDataCharacteristics(connection); Integer lastAttDbXref = new Integer(-1); Integer lastDataId = new Integer(-1); Map<Integer, SubmissionProperty> createdProps = new HashMap<Integer, SubmissionProperty>(); SubmissionProperty buildSubProperty = null; boolean isValidCharacteristic = false; Integer currentSubId = null; // we need those to attach the property to the correct sub Integer previousSubId = null; while (res.next()) { Integer dataId = new Integer(res.getInt("data_id")); String attHeading = res.getString("att_heading"); String attName = res.getString("att_name"); String attValue = res.getString("att_value"); Integer attDbxref = new Integer(res.getInt("att_dbxref")); int attRank = res.getInt("att_rank"); currentSubId = dataSubmissionMap.get(dataId); if (currentSubId == null) { LOG.info("DSM failing dataId: " + dataId + " - " + attHeading + "|" + attName + "|" + attValue); } if (dataId.intValue() != lastDataId.intValue() || attDbxref.intValue() != lastAttDbXref.intValue() || currentSubId != previousSubId) { // store the last build property if created, type is set only if we found an // attHeading of Characteristics // note: dbxref can remain the same in different subs -> or if (buildSubProperty != null && buildSubProperty.type != null) { createdProps.put(lastAttDbXref, buildSubProperty); addToSubToTypes(subToTypes, previousSubId, buildSubProperty); } // set up for next attDbxref if (createdProps.containsKey(attDbxref) && isValidCharacteristic) { // seen this property before so just add for this submission, don't build again buildSubProperty = null; isValidCharacteristic = false; addToSubToTypes(subToTypes, currentSubId, createdProps.get(attDbxref)); } else { buildSubProperty = new SubmissionProperty(); isValidCharacteristic = false; } } if (attHeading.startsWith("Characteristic")) { isValidCharacteristic = true; } // OR // if (buildSubProperty != null) { // if (attHeading.startsWith("Characteristic")) { // buildSubProperty.type = getPreferredSynonym(attName); // buildSubProperty.wikiPageUrl = attValue; // // add detail here as some Characteristics don't reference a wiki page // // but have all information on single row // buildSubProperty.addDetail(attName, attValue, attRank); // } else { // buildSubProperty.addDetail(attHeading, attValue, attRank); // } // } if (buildSubProperty != null) { if (attHeading.startsWith("Characteristic")) { String type = getPreferredSynonym(attName); String wikiUrl = attValue; String wikiType = checkWikiType(type, wikiUrl, currentSubId); buildSubProperty.type = wikiType; buildSubProperty.wikiPageUrl = wikiUrl; // add detail here as some Characteristics don't reference a wiki page // but have all information on single row buildSubProperty.addDetail(wikiType, attValue, attRank); } else { buildSubProperty.addDetail(attHeading, attValue, attRank); } } previousSubId = currentSubId; lastAttDbXref = attDbxref; lastDataId = dataId; } if (buildSubProperty != null && buildSubProperty.type != null) { createdProps.put(lastAttDbXref, buildSubProperty); addToSubToTypes(subToTypes, currentSubId, buildSubProperty); } } private String checkWikiType (String type, String wikiLink, Integer subId) { // for devstages and strain check the type on the wikilink and use it if different // from the declared one. LOG.info("WIKILINK: " + wikiLink + " -- type: " + type); if (wikiLink != null && wikiLink.contains(":")) { String wikiType = wikiLink.substring(0, wikiLink.indexOf(':')); if (type.equals(STRAIN)|| type.equals(DEVSTAGE)){ if (!congruentType(type, wikiType)) { LOG.warn("WIKILINK " + dccIdMap.get(subId) + ": " + type + " but in wiki url: " + wikiType); // not strictly necessary (code would deal with wikiType) if (wikiType.contains("Strain")){ return STRAIN; } if (wikiType.contains("Stage")){ return DEVSTAGE; } } } } return type; } private Boolean congruentType (String type, String wikiType) { // check only strain and devstages if (wikiType.contains("Strain") && !type.equals(STRAIN)){ return false; } if (wikiType.contains("Stage") && !type.equalsIgnoreCase(DEVSTAGE)){ return false; } return true; } // Some submission mention e.g. an RNA Sample but the details of how that sample was created, // stage, strain, etc are in a previous submission. There are references to previous submission // DCC ids where a sample with the corresponding name can be found. We then need to traverse // backwards along the AppliedProtocol DAG to find the stage, strain, etc wiki pages. These // should already have been processed so the properties can just be added to the referencing // submission. private void addSubmissionPropsFromReferencedSubmissions( Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes, Map<String, SubmissionProperty> props, Map<Integer, List<SubmissionReference>> submissionRefs) { for (Map.Entry<Integer, List<SubmissionReference>> entry : submissionRefs.entrySet()) { Integer submissionId = entry.getKey(); List<SubmissionReference> lref = entry.getValue(); Iterator<SubmissionReference> i = lref.iterator(); while (i.hasNext()) { SubmissionReference ref = i.next(); List<AppliedData> refAppliedData = findAppliedDataFromReferencedSubmission(ref); for (AppliedData aData : refAppliedData) { String possibleWikiUrl = aData.actualValue; if (possibleWikiUrl != null && props.containsKey(possibleWikiUrl)) { //LOG.debug("EEFF possible wikiurl: " + possibleWikiUrl); SubmissionProperty propFromReferencedSub = props.get(possibleWikiUrl); if (propFromReferencedSub != null) { addToSubToTypes(subToTypes, submissionId, propFromReferencedSub); LOG.debug("EEFF from referenced sub: " + propFromReferencedSub.type + ": " + propFromReferencedSub.details); } } } } } } private List<AppliedData> findAppliedDataFromReferencedSubmission(SubmissionReference subRef) { List<AppliedData> foundAppliedData = new ArrayList<AppliedData>(); findAppliedProtocolsAndDataFromReferencedSubmission(subRef, foundAppliedData, null); return foundAppliedData; } private List<AppliedProtocol> findAppliedProtocolsFromReferencedSubmission( SubmissionReference subRef) { List<AppliedProtocol> foundAppliedProtocols = new ArrayList<AppliedProtocol>(); findAppliedProtocolsAndDataFromReferencedSubmission(subRef, null, foundAppliedProtocols); return foundAppliedProtocols; } private void findAppliedProtocolsAndDataFromReferencedSubmission( SubmissionReference subRef, List<AppliedData> foundAppliedData, List<AppliedProtocol> foundAppliedProtocols) { String refDataValue = subRef.dataValue; Integer refSubId = subRef.referencedSubmissionId; for (AppliedData aData : appliedDataMap.values()) { String currentDataValue = aData.value; Integer currentDataSubId = dataSubmissionMap.get(aData.dataId); // added check that referenced and referring are not the same. if (refDataValue.equals(currentDataValue) && refSubId.equals(currentDataSubId)) { LOG.info("Found a matching data value: " + currentDataValue + " in referenced sub " + dccIdMap.get(currentDataSubId) + " for value " + aData.actualValue); Integer foundDataId = aData.dataId; findAppliedProtocolsAndDataFromEarlierInDag(foundDataId, foundAppliedData, foundAppliedProtocols); } } } private List<Item> createFromWikiPage(String dccId, String clsName, Map<String, List<SubmissionProperty>> typeToProp, List<String> types) throws ObjectStoreException { List<Item> items = new ArrayList<Item>(); List<SubmissionProperty> props = new ArrayList<SubmissionProperty>(); for (String type : types) { if (typeToProp.containsKey(type)) { props.addAll(typeToProp.get(type)); } } items.addAll(createItemsForSubmissionProperties(dccId, clsName, props)); return items; } private void storeSubmissionCollection(Integer storedSubmissionId, String name, List<Item> items) throws ObjectStoreException { if (!items.isEmpty()) { ReferenceList refList = new ReferenceList(name, getIdentifiersFromItems(items)); getChadoDBConverter().store(refList, storedSubmissionId); } } private List<String> getIdentifiersFromItems(Collection<Item> items) { List<String> ids = new ArrayList<String>(); for (Item item : items) { ids.add(item.getIdentifier()); } return ids; } private List<Item> createItemsForSubmissionProperties(String dccId, String clsName, List<SubmissionProperty> subProps) throws ObjectStoreException { List<Item> items = new ArrayList<Item>(); for (SubmissionProperty subProp : subProps) { Item item = getItemForSubmissionProperty(clsName, subProp, dccId); if (item != null) { items.add(item); } } return items; } private Item getItemForSubmissionProperty(String clsName, SubmissionProperty prop, String dccId) throws ObjectStoreException { Item propItem = subItemsMap.get(prop.wikiPageUrl); if (propItem == null) { if (clsName != null) { List<String> checkOfficialName = prop.details.get("official name"); if (checkOfficialName == null) { LOG.warn("No 'official name', using 'name' instead for: " + prop.wikiPageUrl); checkOfficialName = prop.details.get("name"); } if (checkOfficialName == null) { LOG.info("Official name - missing for property: " + prop.type + ", " + prop.wikiPageUrl); return null; } else if (checkOfficialName.size() != 1) { LOG.info("Official name - multiple times for property: " + prop.type + ", " + prop.wikiPageUrl + ", " + checkOfficialName); } String officialName = getCorrectedOfficialName(prop); propItem = createSubmissionProperty(clsName, officialName); propItem.setAttribute("type", getPreferredSynonym(prop.type)); propItem.setAttribute("wikiLink", WIKI_URL + prop.wikiPageUrl); if ("DevelopmentalStage".equals(clsName)) { setAttributeOnProp(prop, propItem, "sex", "sex"); List<String> devStageValues = prop.details.get("developmental stage"); if (devStageValues != null) { for (String devStageValue : devStageValues) { propItem.addToCollection("ontologyTerms", getDevStageTerm(devStageValue, dccId)); } } else { LOG.error("METADATA FAIL on " + dccId + ": no 'developmental stage' values for wiki page: " + prop.wikiPageUrl); } } else if ("Antibody".equals(clsName)) { setAttributeOnProp(prop, propItem, "antigen", "antigen"); setAttributeOnProp(prop, propItem, "host", "hostOrganism"); setAttributeOnProp(prop, propItem, "target name", "targetName"); setGeneItem(dccId, prop, propItem, "Antibody"); } else if ("Array".equals(clsName)) { setAttributeOnProp(prop, propItem, "platform", "platform"); setAttributeOnProp(prop, propItem, "resolution", "resolution"); setAttributeOnProp(prop, propItem, "genome", "genome"); } else if ("CellLine".equals(clsName)) { setAttributeOnProp(prop, propItem, "sex", "sex"); setAttributeOnProp(prop, propItem, "short description", "description"); setAttributeOnProp(prop, propItem, "species", "species"); setAttributeOnProp(prop, propItem, "tissue", "tissue"); setAttributeOnProp(prop, propItem, "cell type", "cellType"); setAttributeOnProp(prop, propItem, "target name", "targetName"); setGeneItem(dccId, prop, propItem, "CellLine"); } else if ("Strain".equals(clsName)) { setAttributeOnProp(prop, propItem, "species", "species"); setAttributeOnProp(prop, propItem, "source", "source"); // the following 2 should be mutually exclusive setAttributeOnProp(prop, propItem, "Description", "description"); setAttributeOnProp(prop, propItem, "details", "description"); setAttributeOnProp(prop, propItem, "aliases", "name"); setAttributeOnProp(prop, propItem, "reference", "reference"); setAttributeOnProp(prop, propItem, "target name", "targetName"); setGeneItem(dccId, prop, propItem, "Strain"); } else if ("Tissue".equals(clsName)) { setAttributeOnProp(prop, propItem, "species", "species"); setAttributeOnProp(prop, propItem, "sex", "sex"); setAttributeOnProp(prop, propItem, "organismPart", "organismPart"); } getChadoDBConverter().store(propItem); } subItemsMap.put(prop.wikiPageUrl, propItem); } return propItem; } private void setGeneItem(String dccId, SubmissionProperty prop, Item propItem, String source) throws ObjectStoreException { String targetText = null; String[] possibleTypes = new String[] {"target id"}; boolean tooMany = false; for (String targetType : possibleTypes) { if (prop.details.containsKey(targetType)) { if (prop.details.get(targetType).size() != 1) { // we used to complain if multiple values, now only // if they don't have the same value if (sameTargetValue(prop, source, targetType)) { tooMany = true; break; } } if (!tooMany) { targetText = prop.details.get(targetType).get(0); } break; } } if (targetText != null) { // if no target name was found use the target id if (!propItem.hasAttribute("targetName")) { propItem.setAttribute("targetName", targetText); } String geneItemId = getTargetGeneItemIdentfier(targetText, dccId); if (geneItemId != null) { propItem.setReference("target", geneItemId); } } } private boolean sameTargetValue(SubmissionProperty prop, String source, String targetType) { String value = prop.details.get(targetType).get(0); for (int i = 1; i < prop.details.get(targetType).size(); i++) { String newValue = prop.details.get(targetType).get(i); if (!newValue.equals(value)) { LOG.error(source + " (" + prop.wikiPageUrl + ") has more than 1 value for '" + targetType + "' field: " + prop.details.get(targetType)); //throw new RuntimeException(source + " should only have one value for '" // + targetType + "' field: " + prop.details.get(targetType)); return true; } } return false; } private void setAttributeOnProp(SubmissionProperty subProp, Item item, String metadataName, String attributeName) { if (subProp.details.containsKey(metadataName)) { if ("aliases".equalsIgnoreCase(metadataName)) { for (String s :subProp.details.get(metadataName)) { if ("yellow cinnabar brown speck".equalsIgnoreCase(s)) { // swapping name with fullName String full = item.getAttribute("name").getValue(); item.setAttribute("fullName", full); item.setAttribute(attributeName, s); break; } } } else if ("description".equalsIgnoreCase(metadataName) || "details".equalsIgnoreCase(metadataName)) { // description is often split in more than 1 line, details should be correct order StringBuffer sb = new StringBuffer(); for (String desc : subProp.details.get(metadataName)) { sb.append(desc); } if (sb.length() > 0) { item.setAttribute(attributeName, sb.toString()); } } else { String value = subProp.details.get(metadataName).get(0); item.setAttribute(attributeName, value); } } } private String getTargetGeneItemIdentfier(String geneTargetIdText, String dccId) throws ObjectStoreException { // TODO check: why not using only the else? String taxonId = ""; String originalId = null; String flyPrefix = "fly_genes:"; String wormPrefix = "worm_genes:"; if (geneTargetIdText.startsWith(flyPrefix)) { originalId = geneTargetIdText.substring(flyPrefix.length()); taxonId = "7227"; } else if (geneTargetIdText.startsWith(wormPrefix)) { originalId = geneTargetIdText.substring(wormPrefix.length()); taxonId = "6239"; } else { // attempt to work out the organism from the submission taxonId = getTaxonIdForSubmission(dccId); originalId = geneTargetIdText; LOG.debug("RESOLVER: found taxon " + taxonId + " for submission " + dccId); } if (!"7227".equals(taxonId) && !"6239".equals(taxonId)) { LOG.info("RESOLVER: unable to work out organism for target id text: " + geneTargetIdText + " in submission " + dccId); } String geneItemId = null; String primaryIdentifier = resolveGene(originalId, taxonId); if (primaryIdentifier != null) { geneItemId = geneToItemIdentifier.get(primaryIdentifier); if (geneItemId == null) { Item gene = getChadoDBConverter().createItem("Gene"); geneItemId = gene.getIdentifier(); gene.setAttribute("primaryIdentifier", primaryIdentifier); getChadoDBConverter().store(gene); geneToItemIdentifier.put(primaryIdentifier, geneItemId); } else { LOG.info("RESOLVER fetched gene from cache: " + primaryIdentifier); } } return geneItemId; } private String resolveGene(String originalId, String taxonId) { String primaryIdentifier = null; int resCount = rslv.countResolutions(taxonId, originalId); if (resCount != 1) { LOG.info("RESOLVER: failed to resolve gene to one identifier, ignoring " + "gene: " + originalId + " for organism " + taxonId + " count: " + resCount + " found ids: " + rslv.resolveId(taxonId, originalId) + "."); } else { primaryIdentifier = rslv.resolveId(taxonId, originalId).iterator().next(); LOG.info("RESOLVER found gene " + primaryIdentifier + " for original id: " + originalId); } return primaryIdentifier; } private List<Item> lookForAttributesInOtherWikiPages(String dccId, String clsName, Map<String, List<SubmissionProperty>> typeToProp, String[] lookFor) throws ObjectStoreException { List<Item> items = new ArrayList<Item>(); for (String typeProp : lookFor) { if (typeProp.indexOf(".") > 0) { String[] bits = StringUtils.split(typeProp, '.'); String type = bits[0]; String propName = bits[1]; if (typeToProp.containsKey(type)) { for (SubmissionProperty subProp : typeToProp.get(type)) { if (subProp.details.containsKey(propName)) { for (String value : subProp.details.get(propName)) { items.add(createNonWikiSubmissionPropertyItem(dccId, clsName, getPreferredSynonym(propName), correctAttrValue(value))); } } } if (!items.isEmpty()) { break; } } } else { // no attribute type given so use the data.value (SubmissionProperty.wikiPageUrl) // which probably won't be a wiki page if (typeToProp.containsKey(typeProp)) { for (SubmissionProperty subProp : typeToProp.get(typeProp)) { String value = subProp.wikiPageUrl; // This is an ugly special case to deal with 'exposure time/24 hours' if (subProp.details.containsKey("Unit")) { String unit = subProp.details.get("Unit").get(0); value = value + " " + unit + (unit.endsWith("s") ? "" : "s"); } items.add(createNonWikiSubmissionPropertyItem(dccId, clsName, subProp.type, correctAttrValue(value))); } } } } return items; } private String correctAttrValue(String value) { if (value == null) { return null; } value = value.replace("–", "-"); return value; } private Item createNonWikiSubmissionPropertyItem(String dccId, String clsName, String type, String name) throws ObjectStoreException { if ("DevelopmentalStage".equals(clsName)) { name = correctDevStageTerm(name); } Item item = nonWikiSubmissionProperties.get(name); if (item == null) { item = createSubmissionProperty(clsName, name); item.setAttribute("type", getPreferredSynonym(type)); if ("DevelopmentalStage".equals(clsName)) { String ontologyTermId = getDevStageTerm(name, dccId); item.addToCollection("ontologyTerms", ontologyTermId); } getChadoDBConverter().store(item); nonWikiSubmissionProperties.put(name, item); } return item; } private Item createSubmissionProperty(String clsName, String name) { Item subProp = getChadoDBConverter().createItem(clsName); if (name != null) { subProp.setAttribute("name", name); } return subProp; } private String getCorrectedOfficialName(SubmissionProperty prop) { String preferredType = getPreferredSynonym(prop.type); String name = null; if (prop.details.containsKey("official name")) { name = prop.details.get("official name").get(0); } else if (prop.details.containsKey("name")) { name = prop.details.get("name").get(0); } else { // no official name so maybe there is a key that matches the type - sometimes the // setup for Characteristics for (String lookup : makeLookupList(prop.type)) { if (prop.details.containsKey(lookup)) { name = prop.details.get(lookup).get(0); } } } return correctOfficialName(name, preferredType); } /** * Unify variations on similar official names. * @param name the original 'official name' value * @param type the treatment depends on the type * @return a unified official name */ protected String correctOfficialName(String name, String type) { if (name == null) { return null; } if ("developmental stage".equals(type)) { name = name.replace("_", " "); name = name.replaceFirst("embryo", "Embryo"); name = name.replaceFirst("Embyro", "Embryo"); if (name.matches("E\\d.*")) { name = name.replaceFirst("^E", "Embryo "); } if (name.matches("Embryo.*\\d")) { name = name + " h"; } if (name.matches(".*hr")) { name = name.replace("hr", "h"); } if (name.matches("Embryo.*\\dh")) { name = name.replaceFirst("h", " h"); } if (name.startsWith("DevStage:")) { name = name.replaceFirst("DevStage:", "").trim(); } if (name.matches("L\\d")) { name = name + " stage larvae"; } if (name.matches(".*L\\d")) { name = name + " stage larvae"; } if (name.matches("WPP.*")) { name = name.replaceFirst("WPP", "White prepupae (WPP)"); } } return name; } private String getDevStageTerm(String value, String dccId) throws ObjectStoreException { value = correctDevStageTerm(value); // there may be duplicate terms for fly and worm, include taxon in key String taxonId = getTaxonIdForSubmission(dccId); OrganismRepository or = OrganismRepository.getOrganismRepository(); String genus = or.getOrganismDataByTaxon(Integer.parseInt(taxonId)).getGenus(); String key = value + "_" + genus; String identifier = devStageTerms.get(key); if (identifier == null) { Item term = getChadoDBConverter().createItem("OntologyTerm"); term.setAttribute("name", value); String ontologyRef = getDevelopmentOntologyByTaxon(taxonId); if (ontologyRef != null) { term.setReference("ontology", ontologyRef); } getChadoDBConverter().store(term); devStageTerms.put(key, term.getIdentifier()); identifier = term.getIdentifier(); } return identifier; } private String correctDevStageTerm(String value) { // some terms are prefixed with ontology namespace String prefix = "FlyBase development CV:"; if (value.startsWith(prefix)) { value = value.substring(prefix.length()); } return value; } private String getTaxonIdForSubmission(String dccId) { Integer subChadoId = getSubmissionIdFromDccId(dccId); String organism = submissionOrganismMap.get(subChadoId); OrganismRepository or = OrganismRepository.getOrganismRepository(); return "" + or.getOrganismDataByFullName(organism).getTaxonId(); } private String getDevelopmentOntologyByTaxon(String taxonId) throws ObjectStoreException { if (taxonId == null) { return null; } String ontologyName = null; OrganismRepository or = OrganismRepository.getOrganismRepository(); String genus = or.getOrganismDataByTaxon(Integer.parseInt(taxonId)).getGenus(); if ("Drosophila".equals(genus)) { ontologyName = "Fly Development"; } else { ontologyName = "Worm Development"; } String ontologyId = devOntologies.get(ontologyName); if (ontologyId == null) { Item ontology = getChadoDBConverter().createItem("Ontology"); ontology.setAttribute("name", ontologyName); getChadoDBConverter().store(ontology); ontologyId = ontology.getIdentifier(); devOntologies.put(ontologyName, ontologyId); } return ontologyId; } private Integer getSubmissionIdFromDccId(String dccId) { for (Map.Entry<Integer, String> entry : dccIdMap.entrySet()) { if (entry.getValue().equals(dccId)) { return entry.getKey(); } } return null; } /** * Return the rows needed for data from the applied_protocol_data table. * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getAppliedDataAll(Connection connection) throws SQLException { String sraAcc = "SRA acc"; String query = "SELECT d.data_id, d.heading as data_heading," + " d.name as data_name, d.value as data_value," + " c.name as cv_term," + " a.attribute_id, a.heading as att_heading, a.name as att_name," + " a.value as att_value," + " a.dbxref_id as att_dbxref, a.rank as att_rank" + " FROM data d" + " LEFT JOIN data_attribute da ON (d.data_id = da.data_id)" + " LEFT JOIN attribute a ON (da.attribute_id = a.attribute_id)" + " LEFT JOIN cvterm c ON (d.type_id = c.cvterm_id)" + " LEFT JOIN dbxref as x ON (a.dbxref_id = x.dbxref_id)" + " WHERE d.name != '" + sraAcc + "'" + " AND d.value != '' " + " ORDER BY d.data_id"; return doQuery(connection, query, "getAppliedDataAll"); } /** * Return the rows needed for data from the applied_protocol_data table. * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getAppliedDataCharacteristics(Connection connection) throws SQLException { String query = "select d.data_id, d.heading as data_heading," + " d.name as data_name, d.value as data_value," + " a.attribute_id, a.heading as att_heading, a.name as att_name," + " a.value as att_value," + " a.dbxref_id as att_dbxref, a.rank as att_rank" + " FROM data d, data_attribute da, attribute a, dbxref ax, db" + " WHERE d.data_id = da.data_id" + " AND da.attribute_id = a.attribute_id" + " AND a.dbxref_id = ax.dbxref_id" + " AND ax.db_id = db.db_id" + " ORDER BY d.data_id, a.dbxref_id "; return doQuery(connection, query, "getAppliedDataCharacteristics"); } private class SubmissionProperty { protected String type; protected String wikiPageUrl; protected Map<String, List<String>> details; protected SubmissionProperty() { details = new HashMap<String, List<String>>(); } public SubmissionProperty(String type, String wikiPageUrl) { this.type = type; this.wikiPageUrl = wikiPageUrl; details = new HashMap<String, List<String>>(); } public void addDetail(String type, String value, int rank) { List<String> values = details.get(type); if (values == null) { values = new ArrayList<String>(); details.put(type, values); } while (values.size() <= rank) { values.add(null); } values.set(rank, value); } public String toString() { return this.type + ": " + this.wikiPageUrl + this.details.entrySet(); } } private final class DatabaseRecordConfig { private String dbName; private String dbDescrition; private String dbURL; private Set<String> types = new HashSet<String>(); private DatabaseRecordConfig() { // don't } } private Set<DatabaseRecordConfig> initDatabaseRecordConfigs() { Set<DatabaseRecordConfig> configs = new HashSet<DatabaseRecordConfig>(); DatabaseRecordConfig geo = new DatabaseRecordConfig(); geo.dbName = "GEO"; geo.dbDescrition = "Gene Expression Omnibus (NCBI)"; geo.dbURL = "http://www.ncbi.nlm.nih.gov/projects/geo/query/acc.cgi?acc="; geo.types.add("GEO_record"); configs.add(geo); DatabaseRecordConfig ae = new DatabaseRecordConfig(); ae.dbName = "ArrayExpress"; ae.dbDescrition = "ArrayExpress (EMBL-EBI)"; ae.dbURL = "http://www.ebi.ac.uk/microarray-as/ae/browse.html?keywords="; ae.types.add("ArrayExpress_record"); configs.add(ae); DatabaseRecordConfig sra = new DatabaseRecordConfig(); sra.dbName = "SRA"; sra.dbDescrition = "Sequence Read Archive (NCBI)"; sra.dbURL = "http://www.ncbi.nlm.nih.gov/Traces/sra/sra.cgi?cmd=viewer&m=data&s=viewer&run="; sra.types.add("ShortReadArchive_project_ID_list (SRA)"); sra.types.add("ShortReadArchive_project_ID (SRA)"); configs.add(sra); DatabaseRecordConfig ta = new DatabaseRecordConfig(); ta.dbName = "Trace Archive"; ta.dbDescrition = "Trace Archive (NCBI)"; ta.dbURL = "http://www.ncbi.nlm.nih.gov/Traces/trace.cgi?&cmd=retrieve&val="; ta.types.add("TraceArchive_record"); configs.add(ta); DatabaseRecordConfig de = new DatabaseRecordConfig(); de.dbName = "dbEST"; de.dbDescrition = "Expressed Sequence Tags database (NCBI)"; de.dbURL = "http://www.ncbi.nlm.nih.gov/nucest/"; de.types.add("dbEST_record"); configs.add(de); return configs; } /** * Query to get data attributes. * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getAppliedDataAttributes(Connection connection) throws SQLException { String query = "select da.data_id, a.heading, a.value, a.name " + " from data_attribute da, attribute a" + " where da.attribute_id = a.attribute_id"; return doQuery(connection, query, "getAppliedDataAttributes"); } /** * ================ * REFERENCES * ================ * to store references between submission and submissionData * (1 to many) */ private void setSubmissionRefs(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process // note: the map should contain only live submissions for (Integer submissionId : submissionDataMap.keySet()) { for (Integer dataId : submissionDataMap.get(submissionId)) { LOG.debug("DAG subRef subid: " + submissionId + " dataId: " + dataId); if (appliedDataMap.get(dataId).intermineObjectId == null) { continue; } Reference reference = new Reference(); reference.setName("submission"); reference.setRefId(submissionMap.get(submissionId).itemIdentifier); getChadoDBConverter().store(reference, appliedDataMap.get(dataId).intermineObjectId); } } LOG.info("TIME setting submission-data references: " + (System.currentTimeMillis() - bT) + " ms"); } /** * ===================== * DATABASE RECORDS * ===================== */ private void createDatabaseRecords(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process Set<DatabaseRecordConfig> configs = initDatabaseRecordConfigs(); for (Integer submissionId : submissionDataMap.keySet()) { LOG.info("DB RECORD for sub " + dccIdMap.get(submissionId) + "..."); List<Integer> submissionDbRecords = new ArrayList<Integer>(); for (Integer dataId : submissionDataMap.get(submissionId)) { AppliedData ad = appliedDataMap.get(dataId); if (ad.type.equalsIgnoreCase("Result Value")) { for (DatabaseRecordConfig conf : configs) { for (String type : conf.types) { if (ad.name.equals(type)) { submissionDbRecords.addAll(createDatabaseRecords(ad.value, conf)); } } } } // prepare map for setting references if (!submissionDbRecords.isEmpty()) { for (Integer dbRecord : submissionDbRecords) { addToMap(dbRecordIdSubItems, dbRecord, submissionMap.get(submissionId).itemIdentifier); } } } } LOG.info("TIME creating DatabaseRecord objects: " + (System.currentTimeMillis() - bT) + " ms"); bT = System.currentTimeMillis(); // set references // NB: we are setting them from dbRecord to submissions because more efficient // (a few subs have a big collection of dbRecords) for (Integer dbRecordId : dbRecordIdSubItems.keySet()) { ReferenceList col = new ReferenceList("submissions", dbRecordIdSubItems.get(dbRecordId)); getChadoDBConverter().store(col, dbRecordId); } LOG.info("TIME creating refs DatabaseRecord objects: " + (System.currentTimeMillis() - bT) + " ms"); } private List<Integer> createDatabaseRecords(String accession, DatabaseRecordConfig config) throws ObjectStoreException { List<Integer> dbRecordIds = new ArrayList<Integer>(); String defaultURL = config.dbURL; Set<String> cleanAccessions = new HashSet<String>(); // NOTE - this is a special case to deal with a very strange SRA accession format in some // Celniker submissions. The 'accession' is provided as e.g. // SRR013492.225322.1;SRR013492.462158.1;... // We just want the unique SRR ids if ("SRA".equals(config.dbName) && (accession.indexOf(';') != -1 || accession.indexOf('.') != -1)) { for (String part : accession.split(";")) { if (part.indexOf('.') != -1) { cleanAccessions.add(part.substring(0, part.indexOf('.'))); } else { cleanAccessions.add(part); } } } else if ("SRA".equals(config.dbName) && (accession.startsWith("SRX"))) { config.dbURL = "http://www.ncbi.nlm.nih.gov/sra/"; dbRecordIds.add(createDatabaseRecord(accession, config)); config.dbURL = defaultURL; } else { cleanAccessions.add(accession); } for (String cleanAccession : cleanAccessions) { dbRecordIds.add(createDatabaseRecord(cleanAccession, config)); } return dbRecordIds; } private Integer createDatabaseRecord(String accession, DatabaseRecordConfig config) throws ObjectStoreException { DatabaseRecordKey key = new DatabaseRecordKey(config.dbName, accession); Integer dbRecordId = dbRecords.get(key); if (dbRecordId == null) { Item dbRecord = getChadoDBConverter().createItem("DatabaseRecord"); dbRecord.setAttribute("database", config.dbName); dbRecord.setAttribute("description", config.dbDescrition); if (StringUtils.isEmpty(accession)) { dbRecord.setAttribute("accession", "To be confirmed"); } else { dbRecord.setAttribute("url", config.dbURL + accession); dbRecord.setAttribute("accession", accession); } dbRecordId = getChadoDBConverter().store(dbRecord); dbRecords.put(key, dbRecordId); } return dbRecordId; } private class DatabaseRecordKey { private String db; private String accession; /** * Construct with the database and accession * @param db database name * @param accession id in database */ public DatabaseRecordKey(String db, String accession) { this.db = db; this.accession = accession; } /** * {@inheritDoc} */ public boolean equals(Object o) { if (o instanceof DatabaseRecordKey) { DatabaseRecordKey otherKey = (DatabaseRecordKey) o; if (StringUtils.isNotEmpty(accession) && StringUtils.isNotEmpty(otherKey.accession)) { return this.db.equals(otherKey.db) && this.accession.equals(otherKey.accession); } } return false; } /** * {@inheritDoc} */ public int hashCode() { return db.hashCode() + 3 * accession.hashCode(); } } /** * ===================== * RESULT FILES * ===================== */ private void createResultFiles(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process for (Integer submissionId : submissionDataMap.keySet()) { // the applied data is repeated for each protocol // so we want to uniquefy the created object Set<String> subFiles = new HashSet<String>(); for (Integer dataId : submissionDataMap.get(submissionId)) { AppliedData ad = appliedDataMap.get(dataId); // now checking only for 'file', not 'result file' if (StringUtils.containsIgnoreCase(ad.type, "file")) { if (!StringUtils.isBlank(ad.value) && !subFiles.contains(ad.value)) { String direction = null; if (StringUtils.containsIgnoreCase(ad.type, "result")) { direction = "result"; } else { direction = "input"; } createResultFile(ad.value, ad.name, ad.url, direction, submissionId); subFiles.add(ad.value); } } } } LOG.info("TIME creating ResultFile objects: " + (System.currentTimeMillis() - bT) + " ms"); } private void createResultFile(String fileName, String type, String relDccId, String direction, Integer submissionId) throws ObjectStoreException { Item resultFile = getChadoDBConverter().createItem("ResultFile"); resultFile.setAttribute("name", unversionName(fileName)); String url = null; if (fileName.startsWith("http") || fileName.startsWith("ftp")) { url = fileName; } else { if (relDccId != null) { // the file actually belongs to a related sub url = FILE_URL + relDccId + "/extracted/" + unversionName(fileName); } else { // note: on ftp site submission directories are named with the digits only String dccId = dccIdMap.get(submissionId).substring(DCC_PREFIX.length()); url = FILE_URL + dccId + "/extracted/" + unversionName(fileName); } } resultFile.setAttribute("url", url); resultFile.setAttribute("type", type); resultFile.setAttribute("direction", direction); resultFile.setReference("submission", submissionMap.get(submissionId).itemIdentifier); getChadoDBConverter().store(resultFile); } /** * @param fileName */ private String unversionName(String fileName) { // String versionRegex = "\\.*_*[WS|ws]+\\d\\d\\d+"; String versionRegex = "\\.*_*[Ww][Ss]+\\d\\d\\d+"; LOG.debug("FFFF: " + fileName + "--->>" + "====>" + fileName.replaceAll(versionRegex, "")); return fileName.replaceAll(versionRegex, ""); } private void createRelatedSubmissions(Connection connection) throws ObjectStoreException { Map<Integer, Set<String>> relatedSubs = new HashMap<Integer, Set<String>>(); for (Map.Entry<Integer, List<SubmissionReference>> entry : submissionRefs.entrySet()) { Integer submissionId = entry.getKey(); List<SubmissionReference> lref = entry.getValue(); Iterator<SubmissionReference> i = lref.iterator(); while (i.hasNext()) { SubmissionReference ref = i.next(); addRelatedSubmissions(relatedSubs, submissionId, ref.referencedSubmissionId); addRelatedSubmissions(relatedSubs, ref.referencedSubmissionId, submissionId); } LOG.debug("RRSS11 " + relatedSubs.size() + "|" + relatedSubs.keySet() + "|" + relatedSubs.values()); } for (Map.Entry<Integer, Set<String>> entry : relatedSubs.entrySet()) { ReferenceList related = new ReferenceList("relatedSubmissions", new ArrayList<String>(entry.getValue())); getChadoDBConverter().store(related, entry.getKey()); } } private void addRelatedSubmissions(Map<Integer, Set<String>> relatedSubs, Integer subId, Integer relatedId) { Integer subIdObjectId = submissionMap.get(subId).interMineObjectId; Set<String> itemIds = relatedSubs.get(subIdObjectId); if (itemIds == null) { itemIds = new HashSet<String>(); relatedSubs.put(submissionMap.get(subId).interMineObjectId, itemIds); } itemIds.add(submissionMap.get(relatedId).itemIdentifier); } //sub -> prot private void setSubmissionProtocolsRefs(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process Map<Integer, List<Integer>> submissionProtocolMap = new HashMap<Integer, List<Integer>>(); Iterator<Integer> apId = appliedProtocolMap.keySet().iterator(); while (apId.hasNext()) { Integer thisAP = apId.next(); AppliedProtocol ap = appliedProtocolMap.get(thisAP); Util.addToListMap(submissionProtocolMap, ap.submissionId, ap.protocolId); } Iterator<Integer> subs = submissionProtocolMap.keySet().iterator(); while (subs.hasNext()) { Integer thisSubmissionId = subs.next(); List<Integer> protocolChadoIds = submissionProtocolMap.get(thisSubmissionId); ReferenceList collection = new ReferenceList(); collection.setName("protocols"); for (Integer protocolChadoId : protocolChadoIds) { collection.addRefId(protocolItemIds.get(protocolChadoId)); } Integer storedSubmissionId = submissionMap.get(thisSubmissionId).interMineObjectId; getChadoDBConverter().store(collection, storedSubmissionId); // TODO use Item? // if the experiment type is not set in the db, check protocols if (!submissionWithExpTypeSet.contains(thisSubmissionId)) { LOG.warn("EXPERIMENT TYPE NOT SET in chado for submission: " + dccIdMap.get(thisSubmissionId)); // may need protocols from referenced submissions to work out experiment type List<Integer> relatedSubsProtocolIds = new ArrayList<Integer>( findProtocolIdsFromReferencedSubmissions(thisSubmissionId)); if (relatedSubsProtocolIds != null) { protocolChadoIds.addAll(relatedSubsProtocolIds); } String piName = submissionProjectMap.get(thisSubmissionId); setSubmissionExperimentType(storedSubmissionId, protocolChadoIds, piName); } } LOG.info("TIME setting submission-protocol references: " + (System.currentTimeMillis() - bT) + " ms"); } // store Submission.experimentType if it can be inferred from protocols private void setSubmissionExperimentType(Integer storedSubId, List<Integer> protocolIds, String piName) throws ObjectStoreException { Set<String> protocolTypes = new HashSet<String>(); for (Integer protocolId : protocolIds) { protocolTypes.add(protocolTypesMap.get(protocolId).trim()); } String experimentType = inferExperimentType(protocolTypes, piName); if (experimentType != null) { Attribute expTypeAtt = new Attribute("experimentType", experimentType); getChadoDBConverter().store(expTypeAtt, storedSubId); } } // Fetch protocols used to create reagents that are inputs to this submission, these are // found in referenced submissions private List<Integer> findProtocolIdsFromReferencedSubmissions(Integer submissionId) { List<Integer> protocolIds = new ArrayList<Integer>(); if (submissionRefs == null) { throw new RuntimeException("Attempting to access submissionRefs before it has been" + " populated, this method needs to be called after" + " processSubmissionProperties"); } List<SubmissionReference> refs = submissionRefs.get(submissionId); if (refs == null) { return protocolIds; } for (SubmissionReference subRef : refs) { LOG.info("RRSSprot: " + subRef.referencedSubmissionId + "|" + subRef.dataValue); for (AppliedProtocol aProtocol : findAppliedProtocolsFromReferencedSubmission(subRef)) { LOG.info("RRSSprotId: " + aProtocol.protocolId); protocolIds.add(aProtocol.protocolId); } } return protocolIds; } /** * Work out an experiment type give the combination of protocols used for the * submission. e.g. *immunoprecipitation + hybridization = chIP-chip * @param protocolTypes the protocol types * @param piName name of PI * @return a short experiment type */ protected String inferExperimentType(Set<String> protocolTypes, String piName) { // extraction + sequencing + reverse transcription - ChIP = RTPCR // extraction + sequencing - reverse transcription - ChIP = RNA-seq if (containsMatch(protocolTypes, "nucleic_acid_extraction|RNA extraction") && containsMatch(protocolTypes, "sequencing(_protocol)?") && !containsMatch(protocolTypes, "chromatin_immunoprecipitation")) { if (containsMatch(protocolTypes, "reverse_transcription")) { return "RTPCR"; } else { return "RNA-seq"; } } // reverse transcription + PCR + RACE = RACE // reverse transcription + PCR - RACE = RTPCR if (containsMatch(protocolTypes, "reverse_transcription") && containsMatch(protocolTypes, "PCR(_amplification)?")) { if (containsMatch(protocolTypes, "RACE")) { return "RACE"; } else { return "RTPCR"; } } // ChIP + hybridization = ChIP-chip // ChIP - hybridization = ChIP-seq if (containsMatch(protocolTypes, "(.*)?immunoprecipitation")) { if (containsMatch(protocolTypes, "hybridization")) { return "ChIP-chip"; } else { return "ChIP-seq"; } } // hybridization - ChIP = // Celniker: RNA tiling array // Henikoff: Chromatin-chip // otherwise: Tiling array if (containsMatch(protocolTypes, "hybridization") && !containsMatch(protocolTypes, "immunoprecipitation")) { if ("Celniker".equals(piName)) { return "RNA tiling array"; } else if ("Henikoff".equals(piName)) { return "Chromatin-chip"; } else { return "Tiling array"; } } // annotation = Computational annotation if (containsMatch(protocolTypes, "annotation")) { return "Computational annotation"; } // If we haven't found a type yet, and there is a growth protocol, then // this is probably an RNA sample creation experiment from Celniker if (containsMatch(protocolTypes, "grow")) { return "RNA sample creation"; } return null; } // utility method for looking up in a set by regular expression private boolean containsMatch(Set<String> testSet, String regex) { boolean matches = false; Pattern p = Pattern.compile(regex); for (String test : testSet) { Matcher m = p.matcher(test); if (m.matches()) { matches = true; } } return matches; } //sub -> exp private void setSubmissionExperimentRefs(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process // the map should contain only live submissions Iterator<String> exp = expSubMap.keySet().iterator(); while (exp.hasNext()) { String thisExp = exp.next(); List<Integer> subs = expSubMap.get(thisExp); Iterator<Integer> s = subs.iterator(); while (s.hasNext()) { Integer thisSubId = s.next(); Reference reference = new Reference(); reference.setName("experiment"); reference.setRefId(experimentIdRefMap.get(thisExp)); getChadoDBConverter().store(reference, submissionMap.get(thisSubId).interMineObjectId); } } LOG.info("TIME setting submission-experiment references: " + (System.currentTimeMillis() - bT) + " ms"); } //sub -> ef private void setSubmissionEFactorsRefsNEW(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process Iterator<Integer> subs = submissionEFactorMap2.keySet().iterator(); while (subs.hasNext()) { Integer thisSubmissionId = subs.next(); List<String[]> eFactors = submissionEFactorMap2.get(thisSubmissionId); LOG.info("EF REFS: " + thisSubmissionId + " (" + eFactors.get(0) + ")"); Iterator<String[]> ef = eFactors.iterator(); ReferenceList collection = new ReferenceList(); collection.setName("experimentalFactors"); while (ef.hasNext()) { String [] thisEF = ef.next(); String efName = thisEF[0]; String efType = thisEF[1]; String key = efName + efType; collection.addRefId(eFactorIdRefMap.get(efName + efType)); LOG.info("EF REFS!!: ->" + efName + " ref: " + eFactorIdRefMap.get(key)); } if (!collection.equals(null)) { LOG.info("EF REFS: ->" + thisSubmissionId + "|" + submissionMap.get(thisSubmissionId).interMineObjectId); getChadoDBConverter().store(collection, submissionMap.get(thisSubmissionId).interMineObjectId); } } LOG.info("TIME setting submission-exFactors references: " + (System.currentTimeMillis() - bT) + " ms"); } //sub -> ef private void setSubmissionEFactorsRefs(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process Iterator<Integer> subs = submissionEFactorMap.keySet().iterator(); while (subs.hasNext()) { Integer thisSubmissionId = subs.next(); List<String> eFactors = submissionEFactorMap.get(thisSubmissionId); LOG.info("EF REFS: " + thisSubmissionId + " (" + eFactors + ")"); Iterator<String> ef = eFactors.iterator(); ReferenceList collection = new ReferenceList(); collection.setName("experimentalFactors"); while (ef.hasNext()) { String currentEF = ef.next(); collection.addRefId(eFactorIdRefMap.get(currentEF)); LOG.debug("EF REFS: ->" + currentEF + " ref: " + eFactorIdRefMap.get(currentEF)); } if (!collection.equals(null)) { LOG.info("EF REFS: ->" + thisSubmissionId + "|" + submissionMap.get(thisSubmissionId).interMineObjectId); getChadoDBConverter().store(collection, submissionMap.get(thisSubmissionId).interMineObjectId); } } LOG.info("TIME setting submission-exFactors references: " + (System.currentTimeMillis() - bT) + " ms"); } //sub -> publication private void setSubmissionPublicationRefs(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process Iterator<Integer> subs = publicationIdMap.keySet().iterator(); while (subs.hasNext()) { Integer thisSubmissionId = subs.next(); Reference reference = new Reference(); reference.setName("publication"); reference.setRefId(publicationIdRefMap.get(thisSubmissionId)); getChadoDBConverter().store(reference, submissionMap.get(thisSubmissionId).interMineObjectId); } LOG.info("TIME setting submission-publication references: " + (System.currentTimeMillis() - bT) + " ms"); } /** * to store references between applied protocols and their input data * reverse reference: data -> next appliedProtocols * and between applied protocols and their output data * reverse reference: data -> previous appliedProtocols * (many to many) */ private void setDAGRefs(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process for (Integer thisAP : appliedProtocolMap.keySet()) { AppliedProtocol ap = appliedProtocolMap.get(thisAP); if (!ap.inputs.isEmpty()) { ReferenceList collection = new ReferenceList("inputs"); for (Integer inputId : ap.inputs) { collection.addRefId(appliedDataMap.get(inputId).itemIdentifier); //if (collection.getRefIds().contains(null)) { // LOG.info("Applied Protocol " + thisAP + " of protocol " + ap.protocolId // + " and inputs " + ap.inputs ); // } } if (collection.getRefIds().contains(null)) { LOG.warn("Applied Protocol " + thisAP + " has only inputs not corresponding" + " to any output in previous protocol" + " and cannot be linked in the DAG."); continue; } getChadoDBConverter().store(collection, appliedProtocolIdMap.get(thisAP)); } if (!ap.outputs.isEmpty()) { ReferenceList collection = new ReferenceList("outputs"); for (Integer outputId : ap.outputs) { collection.addRefId(appliedDataMap.get(outputId).itemIdentifier); } if (collection.getRefIds().contains(null)) { LOG.warn("Applied Protocol " + thisAP + " has null AD.itemidentifiers"); continue; } getChadoDBConverter().store(collection, appliedProtocolIdMap.get(thisAP)); } } LOG.info("TIME setting DAG references: " + (System.currentTimeMillis() - bT) + " ms"); } /** * maps from chado field names to ours. * * TODO: check if up to date * * if a field is not needed it is marked with NOT_TO_BE_LOADED * a check is performed and fields unaccounted for are logged. */ private static final Map<String, String> FIELD_NAME_MAP = new HashMap<String, String>(); private static final String NOT_TO_BE_LOADED = "this is ; illegal - anyway"; static { // experiment // swapping back to uniquename in experiment table // FIELD_NAME_MAP.put("Investigation Title", "title"); FIELD_NAME_MAP.put("Investigation Title", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Project", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Project URL", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Lab", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Experiment Description", "description"); FIELD_NAME_MAP.put("Experimental Design", "design"); FIELD_NAME_MAP.put("Experimental Factor Type", "factorType"); FIELD_NAME_MAP.put("Experimental Factor Name", "factorName"); FIELD_NAME_MAP.put("Quality Control Type", "qualityControl"); FIELD_NAME_MAP.put("Replicate Type", "replicate"); FIELD_NAME_MAP.put("Date of Experiment", "experimentDate"); FIELD_NAME_MAP.put("Public Release Date", "publicReleaseDate"); FIELD_NAME_MAP.put("Embargo Date", "embargoDate"); FIELD_NAME_MAP.put("dcc_id", "DCCid"); FIELD_NAME_MAP.put("replaces", "replacesSubmission"); FIELD_NAME_MAP.put("PubMed ID", "pubMedId"); FIELD_NAME_MAP.put("Person First Name", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Person Mid Initials", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Person Last Name", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Person Affiliation", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Person Address", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Person Phone", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Person Email", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Person Roles", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Data Type", "category"); FIELD_NAME_MAP.put("Assay Type", "experimentType"); FIELD_NAME_MAP.put("Release Reservations", "notice"); FIELD_NAME_MAP.put("RNAsize", "RNAsize"); // these are names in name/value couples for ReadCount FIELD_NAME_MAP.put("Total Read Count", "totalReadCount"); FIELD_NAME_MAP.put("Total Mapped Read Count", "totalMappedReadCount"); FIELD_NAME_MAP.put("Multiply Mapped Read Count", "multiplyMappedReadCount"); FIELD_NAME_MAP.put("Uniquely Mapped Read Count", "uniquelyMappedReadCount"); // data: parameter values FIELD_NAME_MAP.put("Array Data File", "arrayDataFile"); FIELD_NAME_MAP.put("Array Design REF", "arrayDesignRef"); FIELD_NAME_MAP.put("Derived Array Data File", "derivedArrayDataFile"); FIELD_NAME_MAP.put("Result File", "resultFile"); // protocol FIELD_NAME_MAP.put("Protocol Type", "type"); FIELD_NAME_MAP.put("url protocol", "url"); FIELD_NAME_MAP.put("Characteristics", "characteristics"); FIELD_NAME_MAP.put("species", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("references", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("lab", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Comment", NOT_TO_BE_LOADED); } /** * to store identifiers in project maps. * @param i * @param chadoId * @param intermineObjectId * @throws ObjectStoreException */ private void storeInProjectMaps(Item i, String surnamePI, Integer intermineObjectId) throws ObjectStoreException { if ("Project".equals(i.getClassName())) { projectIdMap .put(surnamePI, intermineObjectId); projectIdRefMap .put(surnamePI, i.getIdentifier()); } else { throw new IllegalArgumentException( "Type mismatch: expecting Project, getting " + i.getClassName().substring(37) + " with intermineObjectId = " + intermineObjectId + ", project = " + surnamePI); } debugMap .put(i.getIdentifier(), i.getClassName()); } /** * to store identifiers in lab maps. * @param i * @param chadoId * @param intermineObjectId * @throws ObjectStoreException */ private void storeInLabMaps(Item i, String labName, Integer intermineObjectId) throws ObjectStoreException { if ("Lab".equals(i.getClassName())) { labIdMap .put(labName, intermineObjectId); labIdRefMap .put(labName, i.getIdentifier()); } else { throw new IllegalArgumentException( "Type mismatch: expecting Lab, getting " + i.getClassName().substring(37) + " with intermineObjectId = " + intermineObjectId + ", lab = " + labName); } debugMap .put(i.getIdentifier(), i.getClassName()); } private void mapSubmissionAndData(Integer submissionId, Integer dataId) { Util.addToListMap(submissionDataMap, submissionId, dataId); dataSubmissionMap.put(dataId, submissionId); } /** * ===================== * UTILITY METHODS * ===================== */ /** * method to wrap the execution of a query, without log info * @param connection * @param query * @return the result set * @throws SQLException */ private ResultSet doQuery(Connection connection, String query) throws SQLException { Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * method to wrap the execution of a query with log info) * @param connection * @param query * @param comment for not logging * @return the result set * @throws SQLException */ private ResultSet doQuery(Connection connection, String query, String comment) throws SQLException { // we could avoid passing comment if we trace the calling method // new Throwable().fillInStackTrace().getStackTrace()[1].getMethodName() LOG.info("executing: " + query); long bT = System.currentTimeMillis(); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); LOG.info("QUERY TIME " + comment + ": " + (System.currentTimeMillis() - bT) + " ms"); return res; } /** * adds an element to a list which is the value of a map * @param m the map (<Integer, List<String>>) * @param key the key for the map * @param value the list */ private static void addToMap(Map<Integer, List<String>> m, Integer key, String value) { List<String> ids = new ArrayList<String>(); if (m.containsKey(key)) { ids = m.get(key); } if (!ids.contains(value)) { ids.add(value); m.put(key, ids); } } }
bio/sources/chado-db/main/src/org/intermine/bio/dataconversion/ModEncodeMetaDataProcessor.java
package org.intermine.bio.dataconversion; /* * Copyright (C) 2002-2013 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.intermine.bio.util.OrganismRepository; import org.intermine.objectstore.ObjectStoreException; import org.intermine.sql.writebatch.Batch; import org.intermine.sql.writebatch.BatchWriterPostgresCopyImpl; import org.intermine.util.Util; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.Item; import org.intermine.xml.full.Reference; import org.intermine.xml.full.ReferenceList; /** * Create items from the modENCODE metadata extensions to the chado schema. * @author Kim Rutherford,sc,rns */ public class ModEncodeMetaDataProcessor extends ChadoProcessor { private static final Logger LOG = Logger.getLogger(ModEncodeMetaDataProcessor.class); private static final String DATA_IDS_TABLE_NAME = "data_ids"; private static final String WIKI_URL = "http://wiki.modencode.org/project/index.php?title="; private static final String FILE_URL = "http://submit.modencode.org/submit/public/get_file/"; private static final String DCC_PREFIX = "modENCODE_"; private static final String NA_PROP = "not applicable"; private static final Set<String> DB_RECORD_TYPES = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList( "GEO_record", "ArrayExpress_record", "TraceArchive_record", "dbEST_record", "ShortReadArchive_project_ID (SRA)", "ShortReadArchive_project_ID_list (SRA)"))); // preferred synonyms private static final String STRAIN = "strain"; private static final String DEVSTAGE = "developmental stage"; // submission maps // --------------- private Map<Integer, String> submissionOrganismMap = new HashMap<Integer, String>(); // maps from chado identifier to lab/project details private Map<Integer, SubmissionDetails> submissionMap = new HashMap<Integer, SubmissionDetails>(); // subId to dcc id private Map<Integer, String> dccIdMap = new HashMap<Integer, String>(); // superseded/deleted subId to dcc id: to be checked in case we need to skip // loading a sub private Map<Integer, String> deletedSubMap = new HashMap<Integer, String>(); // applied_protocol/data/attribute maps // ------------------- // chado submission id to chado data_id private Map<Integer, List<Integer>> submissionDataMap = new HashMap<Integer, List<Integer>>(); // chado data id to chado submission id private Map<Integer, Integer> dataSubmissionMap = new HashMap<Integer, Integer>(); // to store protocol data until we create applied protocols private Map<Integer, Protocol> protocolMap = new HashMap<Integer, Protocol>(); // used when traversing dag of applied protocols private Map<Integer, AppliedProtocol> appliedProtocolMap = new HashMap<Integer, AppliedProtocol>(); // used when traversing dag of applied protocols private Map<Integer, AppliedData> appliedDataMap = new HashMap<Integer, AppliedData>(); // project/lab/experiment/submission maps // -------------------------------------- // for projects, the maps link the project name with the identifiers... private Map<String, Integer> projectIdMap = new HashMap<String, Integer>(); private Map<String, String> projectIdRefMap = new HashMap<String, String>(); // for labs, the maps link the lab name with the identifiers... private Map<String, Integer> labIdMap = new HashMap<String, Integer>(); private Map<String, String> labIdRefMap = new HashMap<String, String>(); // for experiment, the maps link the exp name (description!) with the identifiers... private Map<String, Integer> experimentIdMap = new HashMap<String, Integer>(); private Map<String, String> experimentIdRefMap = new HashMap<String, String>(); private Map<String, List<Integer>> expSubMap = new HashMap<String, List<Integer>>(); // ...we need a further map to link to submission private Map<Integer, String> submissionProjectMap = new HashMap<Integer, String>(); private Map<Integer, String> submissionLabMap = new HashMap<Integer, String>(); // to store the category in experiment private Map<Integer, String> submissionExpCatMap = new HashMap<Integer, String>(); // to check if experiment type is set private Set<Integer> submissionWithExpTypeSet = new HashSet<Integer>(); // submission/applied_protocol/protocol maps // ----------------------------------------- private Map<String, String> protocolsMap = new HashMap<String, String>(); private Map<Integer, String> protocolItemIds = new HashMap<Integer, String>(); private Map<String, Integer> protocolItemToObjectId = new HashMap<String, Integer>(); // submission chado id to item identifier of Protocol used to generate GFF private Map<Integer, String> scoreProtocols = new HashMap<Integer, String>(); private Map<Integer, String> protocolTypesMap = new HashMap<Integer, String>(); private Map<Integer, Integer> appliedProtocolIdMap = new HashMap<Integer, Integer>(); private Map<Integer, String> appliedProtocolIdRefMap = new HashMap<Integer, String>(); // list of firstAppliedProtocols, first level of the DAG linking // the applied protocols through the data (and giving the flow of data) private List<Integer> firstAppliedProtocols = new ArrayList<Integer>(); private Map<Integer, Integer> publicationIdMap = new HashMap<Integer, Integer>(); private Map<Integer, String> publicationIdRefMap = new HashMap<Integer, String>(); // experimental factor maps // ------------------------ // chado submission id to list of top level attributes, e.g. dev stage, organism_part private Map<Integer, ExperimentalFactor> submissionEFMap = new HashMap<Integer, ExperimentalFactor>(); private Map<Integer, List<String[]>> submissionEFactorMap2 = new HashMap<Integer, List<String[]>>(); private Map<String, Integer> eFactorIdMap = new HashMap<String, Integer>(); private Map<String, String> eFactorIdRefMap = new HashMap<String, String>(); private Map<Integer, List<String>> submissionEFactorMap = new HashMap<Integer, List<String>>(); // caches // ------ // cache cv term names by id private Map<String, String> cvtermCache = new HashMap<String, String>(); private Map<String, String> devStageTerms = new HashMap<String, String>(); private Map<String, String> devOntologies = new HashMap<String, String>(); // just for debugging, itemIdentifier, type private Map<String, String> debugMap = new HashMap<String, String>(); private Map<String, Item> nonWikiSubmissionProperties = new HashMap<String, Item>(); private Map<String, Item> subItemsMap = new HashMap<String, Item>(); Map<Integer, List<SubmissionReference>> submissionRefs = null; private IdResolverFactory flyResolverFactory = null; private IdResolverFactory wormResolverFactory = null; private Map<String, String> geneToItemIdentifier = new HashMap<String, String>(); // DbRecords Integer=objectId String=submission.itemId // the second map is used directly to build the references private Map<DatabaseRecordKey, Integer> dbRecords = new HashMap<DatabaseRecordKey, Integer>(); private Map<Integer, List<String>> dbRecordIdSubItems = new HashMap<Integer, List<String>>(); private static final class SubmissionDetails { // the identifier assigned to Item eg. "0_23" private String itemIdentifier; // the object id of the stored Item private Integer interMineObjectId; // the identifier assigned to lab Item for this object private String labItemIdentifier; private String title; private SubmissionDetails() { // don't instantiate } } /** * AppliedProtocol class to reconstruct the flow of submission data */ private static final class AppliedProtocol { private Integer submissionId; // chado private Integer protocolId; private Integer step; // the level in the dag for the AP // the output data associated to this applied protocol private List<Integer> outputs = new ArrayList<Integer>(); private List<Integer> inputs = new ArrayList<Integer>(); private AppliedProtocol() { // don't instantiate } } /** * Protocol class to store protocol data */ private static final class Protocol { private Integer protocolId; // possibly we don't need this (map) private String name; private String description; private String wikiLink; private Integer version; // the level in the dag for the AP private Protocol() { // don't instantiate } } /** * AppliedData class * to reconstruct the flow of submission data * */ private static final class AppliedData { private String itemIdentifier; private Integer intermineObjectId; private Integer dataId; private String value; private String actualValue; private String type; private String name; private String url; // in particular, it stores the dccid of the related sub needed for // linking to a result file // the list of applied protocols for which this data item is an input private List<Integer> nextAppliedProtocols = new ArrayList<Integer>(); // the list of applied protocols for which this data item is an output private List<Integer> previousAppliedProtocols = new ArrayList<Integer>(); private AppliedData() { // don't instantiate } } /** * Experimental Factor class * to store the couples (type, name/value) of EF * note that in chado sometime the name is given, other times is the value */ private static final class ExperimentalFactor { private Map<String, String> efTypes = new HashMap<String, String>(); private List<String> efNames = new ArrayList<String>(); private ExperimentalFactor() { // don't instantiate } } /** * Create a new ChadoProcessor object * @param chadoDBConverter the converter that created this Processor */ public ModEncodeMetaDataProcessor(ChadoDBConverter chadoDBConverter) { super(chadoDBConverter); } /** * {@inheritDoc} */ @Override public void process(Connection connection) throws Exception { processDeleted(connection); processProjectTable(connection); processLabTable(connection); processSubmissionOrganism(connection); processSubmission(connection); processSubmissionAttributes(connection); processProtocolTable(connection); processAppliedProtocolTable(connection); processProtocolAttributes(connection); processDag(connection); processAppliedData(connection); processAppliedDataAttributes(connection); processExperiment(connection); findScoreProtocols(); processFeatures(connection, submissionMap); // set references setSubmissionRefs(connection); setSubmissionExperimentRefs(connection); setDAGRefs(connection); // create DatabaseRecords where necessary for each submission createDatabaseRecords(connection); // create result files per submission createResultFiles(connection); // for high level attributes and experimental factors (EF) // TODO: clean up processEFactor(connection); flyResolverFactory = new FlyBaseIdResolverFactory("gene"); wormResolverFactory = new WormBaseIdResolverFactory("gene"); processSubmissionProperties(connection); createRelatedSubmissions(connection); setSubmissionProtocolsRefs(connection); setSubmissionEFactorsRefs(connection); setSubmissionPublicationRefs(connection); } /** * ========================= * DELETED SUBS in CHADO * ========================= * To build a map of deleted subs (submissionId, dcc) * * @param connection * @throws SQLException * @throws ObjectStoreException */ private void processDeleted(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getDeleted(connection); while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); String value = res.getString("value"); deletedSubMap.put(submissionId, value); } res.close(); LOG.info("found " + deletedSubMap.size() + " deleted submissions to skip in the build."); LOG.info("PROCESS TIME deleted subs: " + (System.currentTimeMillis() - bT) + " ms"); } /** * Return deleted subs in the chado db. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getDeleted(Connection connection) throws SQLException { String query = "SELECT distinct a.experiment_id, a.value " + " FROM experiment_prop a " + " where a.name = 'deleted' "; return doQuery(connection, query, "getDeleted"); } /** * * ============== * FEATURES * ============== * * @param connection * @param submissionMap * @throws Exception */ private void processFeatures(Connection connection, Map<Integer, SubmissionDetails> submissionMap) throws Exception { long bT = System.currentTimeMillis(); // to monitor time spent in the process // keep map of feature to submissions it has been referenced by, some features appear in // more than one submission Map<Integer, List<String>> subCollections = new HashMap<Integer, List<String>>(); // hold features that should only be processed once across all submissions, initialise // processor with this map each time Map<Integer, FeatureData> commonFeaturesMap = new HashMap<Integer, FeatureData>(); for (Map.Entry<Integer, SubmissionDetails> entry: submissionMap.entrySet()) { Integer chadoExperimentId = entry.getKey(); if (deletedSubMap.containsKey(chadoExperimentId)) { continue; } Map<Integer, FeatureData> subFeatureMap = new HashMap<Integer, FeatureData>(); SubmissionDetails submissionDetails = entry.getValue(); String submissionItemIdentifier = submissionDetails.itemIdentifier; String labItemIdentifier = submissionDetails.labItemIdentifier; String submissionTitle = submissionDetails.title; List<Integer> thisSubmissionDataIds = submissionDataMap.get(chadoExperimentId); LOG.info("DATA IDS for " + dccIdMap.get(chadoExperimentId) + ": " + thisSubmissionDataIds.size()); // Create a temporary table with the feature ids related to this submission // based on the data_feature table String dataIdsTempTable = createDataIdsTempTable(connection, chadoExperimentId, thisSubmissionDataIds); ModEncodeFeatureProcessor processor = new ModEncodeFeatureProcessor(getChadoDBConverter(), submissionItemIdentifier, labItemIdentifier, dataIdsTempTable, submissionTitle, scoreProtocols.get(chadoExperimentId)); processor.initialiseCommonFeatures(commonFeaturesMap); processor.process(connection); // all features related to this submission subFeatureMap.putAll(processor.getFeatureMap()); // features common across many submissions commonFeaturesMap.putAll(processor.getCommonFeaturesMap()); LOG.info("COMMON FEATURES: " + commonFeaturesMap.size()); if (subFeatureMap.keySet().size() == 0) { LOG.error("FEATMAP: submission " + chadoExperimentId + " has no featureMap keys."); continue; } LOG.info("FEATMAP: submission " + chadoExperimentId + "|" + "featureMap: " + subFeatureMap.keySet().size()); // Populate map of submissions to features, some features are in multiple submissions processDataFeatureTable(connection, subCollections, subFeatureMap, chadoExperimentId, dataIdsTempTable); dropDataIdsTempTable(connection, dataIdsTempTable); // 1- generate a map of gene-identifiers so we can re-use the same item identifiers // when creating antibody/strain target genes late // 2- fill the 'ChromatinState' state with the secondaryId additionalProcessing(processor, subFeatureMap); } storeSubmissionsCollections(subCollections); LOG.info("PROCESS TIME features: " + (System.currentTimeMillis() - bT) + " ms"); } private void storeSubmissionsCollections(Map<Integer, List<String>> subCollections) throws ObjectStoreException { for (Map.Entry<Integer, List<String>> entry : subCollections.entrySet()) { Integer featureObjectId = entry.getKey(); ReferenceList collection = new ReferenceList("submissions", entry.getValue()); getChadoDBConverter().store(collection, featureObjectId); } } private void additionalProcessing(ModEncodeFeatureProcessor processor, Map<Integer, FeatureData> subFeatureMap) throws ObjectStoreException{ for (FeatureData fData : subFeatureMap.values()) { // 1- generate a map of gene-identifiers so we can re-use the same item identifiers // when creating antibody/strain target genes late if ("Gene".equals(fData.getInterMineType())) { String geneIdentifier = processor.fixIdentifier(fData, fData.getUniqueName()); geneToItemIdentifier.put(geneIdentifier, fData.getItemIdentifier()); } // 2- fill the 'ChromatinState' state with the secondaryId if ("ChromatinState".equals(fData.getInterMineType())) { String state = fData.getChadoFeatureName(); Integer imObjectId = fData.getIntermineObjectId(); setAttribute(imObjectId, "state", state); } } } private void processDataFeatureTable(Connection connection, Map<Integer, List<String>> subCols, Map<Integer, FeatureData> featureMap, Integer chadoExperimentId, String dataIdTable) throws SQLException { long bT = System.currentTimeMillis(); // to monitor time spent in the process String submissionItemId = submissionMap.get(chadoExperimentId).itemIdentifier; bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getDataFeature(connection, dataIdTable); while (res.next()) { Integer dataId = new Integer(res.getInt("data_id")); Integer featureId = new Integer(res.getInt("feature_id")); FeatureData featureData = featureMap.get(featureId); if (featureData == null) { LOG.debug("Check feature type: no data for feature_id: " + featureId + " in processDataFeatureTable(), data_id =" + dataId); continue; } Integer featureObjectId = featureData.getIntermineObjectId(); List<String> subs = subCols.get(featureObjectId); if (subs == null) { subs = new ArrayList<String>(); subCols.put(featureObjectId, subs); } subs.add(submissionItemId); } LOG.info("DATA IDS PROCESS TIME data_feature table: " + (System.currentTimeMillis() - bT)); } private String createDataIdsTempTable(Connection connection, Integer chadoExperimentId, List<Integer> dataIds) throws SQLException { // the batch writer system doesn't like to have duplicate named tables String tableName = DATA_IDS_TABLE_NAME + "_" + chadoExperimentId + "_" + System.currentTimeMillis(); long bT = System.currentTimeMillis(); String query = " CREATE TEMPORARY TABLE " + tableName + " (data_id int)"; Statement stmt = connection.createStatement(); LOG.info("executing: " + query); stmt.execute(query); try { BatchWriterPostgresCopyImpl batchWriter = new BatchWriterPostgresCopyImpl(); Batch batch = new Batch(batchWriter); HashSet<Integer> uniqueDataIds = new HashSet<Integer>(dataIds); String[] colNames = new String[] {"data_id"}; for (Integer dataId : uniqueDataIds) { batch.addRow(connection, tableName, dataId, colNames, new Object[] {dataId}); } batch.flush(connection); batch.close(connection); LOG.info("CREATED DATA IDS TABLE: " + tableName + " with " + uniqueDataIds.size() + " data ids in " + (System.currentTimeMillis() - bT) + "ms"); String idIndexQuery = "CREATE INDEX " + tableName + "_data_id_index ON " + tableName + "(data_id)"; LOG.info("DATA IDS executing: " + idIndexQuery); long bT1 = System.currentTimeMillis(); stmt.execute(idIndexQuery); LOG.info("DATA IDS TIME creating INDEX: " + (System.currentTimeMillis() - bT1) + "ms"); String analyze = "ANALYZE " + tableName; LOG.info("executing: " + analyze); long bT2 = System.currentTimeMillis(); stmt.execute(analyze); LOG.info("DATA IDS TIME analyzing: " + (System.currentTimeMillis() - bT2) + "ms"); } catch (SQLException e) { // the batch writer system doesn't like to have duplicate named tables query = "DROP TABLE " + tableName; stmt.execute(query); throw e; } return tableName; } private void dropDataIdsTempTable(Connection connection, String dataIdsTableName) throws SQLException { long bT = System.currentTimeMillis(); String query = " DROP TABLE " + dataIdsTableName; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); stmt.execute(query); LOG.info("DATA IDS TIME dropping table '" + dataIdsTableName + "': " + (System.currentTimeMillis() - bT)); } private ResultSet getDataFeature(Connection connection, String dataIdTable) throws SQLException { String query = "SELECT df.data_id, df.feature_id" + " FROM data_feature df, " + dataIdTable + " d" + " WHERE df.data_id = d.data_id"; return doQuery(connection, query, "getDataFeature"); } /** * * ==================== * DAG * ==================== * * In chado, Applied protocols in a submission are linked to each other via * the flow of data (output of a parent AP are input to a child AP). * The method process the data from chado to build the objects * (SubmissionDetails, AppliedProtocol, AppliedData) and their * respective maps to chado identifiers needed to traverse the DAG. * It then traverse the DAG, assigning the experiment_id to all data. * * @param connection * @throws SQLException * @throws ObjectStoreException */ private void processDag(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getDAG(connection); AppliedProtocol node = new AppliedProtocol(); AppliedData branch = null; Integer count = new Integer(0); Integer actualSubmissionId = new Integer(0); // to store the experiment id (see below) Integer previousAppliedProtocolId = new Integer(0); boolean isADeletedSub = false; while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); Integer protocolId = new Integer(res.getInt("protocol_id")); Integer appliedProtocolId = new Integer(res.getInt("applied_protocol_id")); Integer dataId = new Integer(res.getInt("data_id")); String direction = res.getString("direction"); LOG.debug("DAG: " + submissionId + " p:" + protocolId + " ap:" + appliedProtocolId + " d:" + dataId + " | " + direction); // the results are ordered, first ap have a subId // if we find a deleted sub, we know that subsequent records with null // subId belongs to the deleted sub // note that while the subId is null in the database, it is = 0 here if (submissionId == 0) { if (isADeletedSub) { LOG.debug("DEL: skipping" + isADeletedSub); continue; } } else { if (deletedSubMap.containsKey(submissionId)) { isADeletedSub = true; LOG.debug("DEL: " + submissionId + " ->" + isADeletedSub); continue; } else { isADeletedSub = false; LOG.debug("DEL: " + submissionId + " ->" + isADeletedSub); } } // build a data node for each iteration if (appliedDataMap.containsKey(dataId)) { branch = appliedDataMap.get(dataId); } else { branch = new AppliedData(); } // could use > (order by apid, apdataid, direction) // NB: using isLast() is expensive if (!appliedProtocolId.equals(previousAppliedProtocolId) || res.isLast()) { // the submissionId != null for the first applied protocol if (submissionId > 0) { firstAppliedProtocols.add(appliedProtocolId); LOG.debug("DAG fap subId:" + submissionId + " apID: " + appliedProtocolId); // set actual submission id // we can either be at a first applied protocol (submissionId > 0).. actualSubmissionId = submissionId; } else { // ..or already down the dag, and we use the stored id. submissionId = actualSubmissionId; } // last one: fill the list of outputs // and add to the general list of data ids for the submission, // used to fetch features if (res.isLast()) { if ("output".equalsIgnoreCase(direction)) { node.outputs.add(dataId); mapSubmissionAndData(submissionId, dataId); } } // if it is not the first iteration, let's store it if (previousAppliedProtocolId > 0) { appliedProtocolMap.put(previousAppliedProtocolId, node); } // new node AppliedProtocol newNode = new AppliedProtocol(); newNode.protocolId = protocolId; newNode.submissionId = submissionId; if (direction.startsWith("in")) { // add this applied protocol to the list of nextAppliedProtocols branch.nextAppliedProtocols.add(appliedProtocolId); // ..and update the map updateAppliedDataMap(branch, dataId); // .. and add the dataId to the list of input Data for this applied protocol newNode.inputs.add(dataId); mapSubmissionAndData(submissionId, dataId); //*** } else if (direction.startsWith("out")) { // add the dataId to the list of output Data for this applied protocol: // it will be used to link to the next set of applied protocols newNode.outputs.add(dataId); if (previousAppliedProtocolId > 0) { branch.previousAppliedProtocols.add(previousAppliedProtocolId); updateAppliedDataMap(branch, dataId); //*** mapSubmissionAndData(submissionId, dataId); //**** } } else { // there is some problem with the strings 'input' or 'output' throw new IllegalArgumentException("Data direction not valid for dataId: " + dataId + "|" + direction + "|"); } // for the new round.. node = newNode; previousAppliedProtocolId = appliedProtocolId; } else { // keep feeding IN et OUT if (direction.startsWith("in")) { node.inputs.add(dataId); if (submissionId > 0) { // initial data mapSubmissionAndData(submissionId, dataId); } // as above branch.nextAppliedProtocols.add(appliedProtocolId); updateAppliedDataMap(branch, dataId); } else if (direction.startsWith("out")) { node.outputs.add(dataId); branch.previousAppliedProtocols.add(appliedProtocolId); updateAppliedDataMap(branch, dataId); //*** } else { throw new IllegalArgumentException("Data direction not valid for dataId: " + dataId + "|" + direction + "|"); } } count++; } LOG.info("created " + appliedProtocolMap.size() + "(" + count + " applied data points) DAG nodes (= applied protocols) in map"); res.close(); // now traverse the DAG, and associate submission with all the applied protocols traverseDag(); // set the dag level as an attribute to applied protocol setAppliedProtocolSteps(connection); LOG.info("PROCESS TIME DAG: " + (System.currentTimeMillis() - bT) + " ms"); } /** * @param newAD * @param dataId */ private void updateAppliedDataMap(AppliedData newAD, Integer dataId) { if (appliedDataMap.containsKey(dataId)) { appliedDataMap.remove(dataId); } appliedDataMap.put(dataId, newAD); } /** * @param newAD the new appliedData * @param dataId the data id * @param intermineObjectId just a flag to do an update of attributes instead of a replecament */ private void updateADMap(AppliedData newAD, Integer dataId, Integer intermineObjectId) { if (appliedDataMap.containsKey(dataId)) { AppliedData datum = appliedDataMap.get(dataId); datum.intermineObjectId = newAD.intermineObjectId; datum.itemIdentifier = newAD.itemIdentifier; datum.value = newAD.value; datum.actualValue = newAD.actualValue; datum.dataId = dataId; datum.type = newAD.type; datum.name = newAD.name; datum.url = newAD.url; } else { appliedDataMap.put(dataId, newAD); } } /** * to set the step attribute for the applied protocols */ private void setAppliedProtocolSteps(Connection connection) throws ObjectStoreException { for (Integer appliedProtocolId : appliedProtocolMap.keySet()) { Integer step = appliedProtocolMap.get(appliedProtocolId).step; if (step != null) { Attribute attr = new Attribute("step", step.toString()); getChadoDBConverter().store(attr, appliedProtocolIdMap.get(appliedProtocolId)); } else { AppliedProtocol ap = appliedProtocolMap.get(appliedProtocolId); LOG.warn("AppliedProtocol.step not set for chado id: " + appliedProtocolId + " sub " + dccIdMap.get(ap.submissionId) + " inputs " + ap.inputs + " outputs " + ap.outputs); } } } // Look for protocols that were used to generated GFF files, these are passed to the feature // processor, if features have a score the protocol is set as the scoreProtocol reference. // NOTE this could equally be done with data, data_feature and applied_protocol_data private void findScoreProtocols() { for (Map.Entry<Integer, AppliedData> entry : appliedDataMap.entrySet()) { Integer dataId = entry.getKey(); AppliedData aData = entry.getValue(); if ("Result File".equals(aData.type) && (aData.value.endsWith(".gff") || aData.value.endsWith("gff3"))) { for (Integer papId : aData.previousAppliedProtocols) { AppliedProtocol aProtocol = appliedProtocolMap.get(papId); String protocolItemId = protocolItemIds.get(aProtocol.protocolId); scoreProtocols.put(dataSubmissionMap.get(dataId), protocolItemId); } } } } /** * Return the rows needed to construct the DAG of the data/protocols. * The reference to the submission is available only for the first set * of applied protocols, hence the outer join. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getDAG(Connection connection) throws SQLException { String query = "SELECT eap.experiment_id, ap.protocol_id, apd.applied_protocol_id" + " , apd.data_id, apd.applied_protocol_data_id, apd.direction" + " FROM applied_protocol ap LEFT JOIN experiment_applied_protocol eap" + " ON (eap.first_applied_protocol_id = ap.applied_protocol_id )" + " , applied_protocol_data apd" + " WHERE apd.applied_protocol_id = ap.applied_protocol_id" + " ORDER By 3,5,6"; return doQuery(connection, query, "getDAG"); } /** * Applies iteratively buildADaglevel * * @throws SQLException * @throws ObjectStoreException */ private void traverseDag() throws ObjectStoreException { List<Integer> currentIterationAP = firstAppliedProtocols; List<Integer> nextIterationAP = new ArrayList<Integer>(); Integer step = 1; // DAG level while (currentIterationAP.size() > 0) { nextIterationAP = buildADagLevel (currentIterationAP, step); currentIterationAP = nextIterationAP; step++; } } /** * This method is given a set of applied protocols (already associated with a submission) * and produces the next set of applied protocols. The latter are the protocols attached to the * output data of the starting set (output data for a applied protocol is the input data for the * next one). * It also fills the map linking directly results ('leaf' output data) with submission * * @param previousAppliedProtocols * @return the next batch of appliedProtocolId * @throws SQLException * @throws ObjectStoreException */ private List<Integer> buildADagLevel(List<Integer> previousAppliedProtocols, Integer step) throws ObjectStoreException { List<Integer> nextIterationProtocols = new ArrayList<Integer>(); Iterator<Integer> pap = previousAppliedProtocols.iterator(); while (pap.hasNext()) { List<Integer> outputs = new ArrayList<Integer>(); List<Integer> inputs = new ArrayList<Integer>(); Integer currentId = pap.next(); // add the DAG level here only if these are the first AP if (step == 1) { appliedProtocolMap.get(currentId).step = step; } outputs.addAll(appliedProtocolMap.get(currentId).outputs); Integer submissionId = appliedProtocolMap.get(currentId).submissionId; Iterator<Integer> od = outputs.iterator(); while (od.hasNext()) { Integer currentOD = od.next(); List<Integer> nextProtocols = new ArrayList<Integer>(); // build map submission-data mapSubmissionAndData(submissionId, currentOD); if (appliedDataMap.containsKey(currentOD)) { // fill the list of next (children) protocols nextProtocols.addAll(appliedDataMap.get(currentOD).nextAppliedProtocols); if (appliedDataMap.get(currentOD).nextAppliedProtocols.isEmpty()) { // this is a leaf!! LOG.debug("DAG leaf: " + submissionId + " dataId: " + currentOD); } } // to fill submission-dataId map // this is needed, otherwise inputs to AP that are not outputs // of a previous protocol are not considered inputs.addAll(appliedProtocolMap.get(currentId).inputs); Iterator<Integer> in = inputs.iterator(); while (in.hasNext()) { Integer currentIn = in.next(); // build map submission-data mapSubmissionAndData(submissionId, currentIn); } // build the list of children applied protocols chado identifiers // as input for the next iteration Iterator<Integer> nap = nextProtocols.iterator(); while (nap.hasNext()) { // and fill the map with the chado experiment_id and the DAG level Integer currentAPId = nap.next(); appliedProtocolMap.get(currentAPId).submissionId = submissionId; appliedProtocolMap.get(currentAPId).step = step + 1; nextIterationProtocols.add(currentAPId); // and set the reference from applied protocol to the submission Reference reference = new Reference(); reference.setName("submission"); reference.setRefId(submissionMap.get(submissionId).itemIdentifier); getChadoDBConverter().store(reference, appliedProtocolIdMap.get(currentAPId)); } } } return nextIterationProtocols; } /** * ============== * ORGANISM * ============== * Organism for a submission is derived from the organism associated with * the protocol of the first applied protocol (of the submission). * it is the name. a request to associate the submission directly with * the taxonid has been made to chado people. * * @param connection * @throws SQLException * @throws ObjectStoreException */ private void processSubmissionOrganism(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getSubmissionOrganism(connection); while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); if (deletedSubMap.containsKey(submissionId)) { continue; } String value = res.getString("value"); submissionOrganismMap.put(submissionId, value); LOG.debug("TAXID " + submissionId + "|" + value); } res.close(); LOG.info("found an organism for " + submissionOrganismMap.size() + " submissions."); LOG.info("PROCESS TIME organisms: " + (System.currentTimeMillis() - bT) + " ms"); } /** * Return the row needed for the organism. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getSubmissionOrganism(Connection connection) throws SQLException { String query = "select distinct eap.experiment_id, a.value " + " from experiment_applied_protocol eap, applied_protocol ap, " + " protocol_attribute pa, attribute a " + " where eap.first_applied_protocol_id = ap.applied_protocol_id " + " and ap.protocol_id=pa.protocol_id " + " and pa.attribute_id=a.attribute_id " + " and a.heading='species' "; return doQuery(connection, query, "getSubmissionOrganism"); } /** * ============== * PROJECT * ============== * Projects are loaded statically. A map is built between submissionId and * project's name and used for the references. 2 maps store intermine * objectId and itemId, with key the project name. * Note: the project name in chado is the surname of the PI * * @param connection * @throws SQLException * @throws ObjectStoreException */ private void processProjectTable(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getProjects(connection); while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); String value = res.getString("value"); if (deletedSubMap.containsKey(submissionId)) { continue; } submissionProjectMap.put(submissionId, value); } res.close(); Set<Integer> exp = submissionProjectMap.keySet(); Iterator<Integer> i = exp.iterator(); while (i.hasNext()) { Integer thisExp = i.next(); String project = submissionProjectMap.get(thisExp); if (projectIdMap.containsKey(project)) { continue; } LOG.debug("PROJECT: " + project); Item pro = getChadoDBConverter().createItem("Project"); pro.setAttribute("surnamePI", project); Integer intermineObjectId = getChadoDBConverter().store(pro); storeInProjectMaps(pro, project, intermineObjectId); } LOG.info("created " + projectIdMap.size() + " project"); LOG.info("PROCESS TIME projects: " + (System.currentTimeMillis() - bT) + " ms"); } /** * Return the project name. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getProjects(Connection connection) throws SQLException { String query = "SELECT distinct a.experiment_id, a.value " + " FROM experiment_prop a " + " where a.name = 'Project' " + " AND rank=0"; return doQuery(connection, query, "getProjects"); } /** * ============== * LAB * ============== * Labs are also loaded statically (affiliation is not given in the chado file). * A map is built between submissionId and * lab's name and used for the references. 2 maps store intermine * objectId and itemId, with key the lab name. * TODO: do project and lab together (1 query, 1 process) * * @param connection * @throws SQLException * @throws ObjectStoreException */ private void processLabTable(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getLabs(connection); while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); String value = res.getString("value"); if (deletedSubMap.containsKey(submissionId)) { continue; } submissionLabMap.put(submissionId, value); } res.close(); Set<Integer> exp = submissionLabMap.keySet(); Iterator<Integer> i = exp.iterator(); while (i.hasNext()) { Integer thisExp = i.next(); String prov = submissionLabMap.get(thisExp); String project = submissionProjectMap.get(thisExp); if (labIdMap.containsKey(prov)) { continue; } LOG.debug("PROV: " + prov); Item lab = getChadoDBConverter().createItem("Lab"); lab.setAttribute("surname", prov); lab.setReference("project", projectIdRefMap.get(project)); Integer intermineObjectId = getChadoDBConverter().store(lab); storeInLabMaps(lab, prov, intermineObjectId); } LOG.info("created " + labIdMap.size() + " labs"); LOG.info("PROCESS TIME labs: " + (System.currentTimeMillis() - bT) + " ms"); } /** * Return the lab name. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getLabs(Connection connection) throws SQLException { String query = "SELECT distinct a.experiment_id, a.name, a.value " + " FROM experiment_prop a " + " where a.name = 'Lab' " + " AND a.rank=0"; return doQuery(connection, query, "getLabs"); } /** * ================ * EXPERIMENT * ================ * Experiment is a collection of submissions. They all share the same description. * It has been added later to the model. * A map is built between submissionId and experiment name. * 2 maps store intermine objectId and itemId, with key the experiment name. * They are probably not needed. * */ private void processExperiment(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getExperimentTitles(connection); Map<String, String> expProMap = new HashMap<String, String>(); while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); if (deletedSubMap.containsKey(submissionId)) { continue; } String name = cleanWikiLinks(res.getString("name")); Util.addToListMap(expSubMap, name, submissionId); expProMap.put(name, submissionProjectMap.get(submissionId)); } res.close(); Set<String> experiment = expSubMap.keySet(); Iterator<String> i = experiment.iterator(); while (i.hasNext()) { String name = i.next(); Item exp = getChadoDBConverter().createItem("Experiment"); exp.setAttribute("name", name); // find experiment category from map (take first available) // use the commented lines to get a report of assignments String category = null; for (Integer ii : expSubMap.get(name)) { // String dccId = dccIdMap.get(ii); category = submissionExpCatMap.get(ii); if (category != null && !category.isEmpty()) { // LOG.info("ECS " + name + "|" + dccId + ": " + category); exp.setAttribute("category", category); break; } //else { //LOG.warn("ECS " + name + "|" + dccId + ": no category"); //} } String project = expProMap.get(name); exp.setReference("project", projectIdRefMap.get(project)); // note: the reference to submission collection is in a separate method Integer intermineObjectId = getChadoDBConverter().store(exp); experimentIdMap .put(name, intermineObjectId); experimentIdRefMap .put(name, exp.getIdentifier()); } LOG.info("created " + expSubMap.size() + " experiments"); LOG.info("PROCESS TIME experiments: " + (System.currentTimeMillis() - bT) + " ms"); } /** * method to clean a wiki reference (url to a named page) in chado * used also for experiment names * @param w the wiki reference */ private String cleanWikiLinks(String w) { String url = "http://wiki.modencode.org/project/index.php?title="; // we are stripping from first ':', maybe we want to include project suffix // e.g.: // original "http://...?title=Gene Model Prediction:SC:1&amp;oldid=12356" // now: Gene Model Prediction // maybe? Gene Model Prediction:SC:1 // (:->&) String w1 = StringUtils.replace(w, url, ""); String s1 = null; if (w1.contains(":")) { s1 = StringUtils.substringBefore(w1, ":"); } else { // for links missing the : char, e.g. // MacAlpine Early Origin of Replication Identification&oldid=10464 s1 = StringUtils.substringBefore(w1, "&"); } String s = s1.replace('"', ' ').trim(); if (s.contains("%E2%80%99")) { // prime: for the Piano experiment String s2 = s.replace("%E2%80%99", "'"); return s2; } if (s.contains("%28A%29%2B")) { // this is (A)+, in // Stranded Cell Line Transcriptional Profiling Using Illumina poly%28A%29%2B RNA-seq String s2 = s.replace("%28A%29%2B", "(A)+"); return s2; } if (s.contains("%2B")) { // +: for Celniker experiment "Tissue-specific Transcriptional Profiling..." String s2 = s.replace("%2B", "+"); return s2; } return s; } /** * Return the rows needed for experiment from the experiment_prop table. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getExperimentTitles(Connection connection) throws SQLException { // TODO use standard SQl and deal with string in java String query = "select e.experiment_id, " + " translate(x.accession, '_', ' ') as name " + " from experiment_prop e, dbxref x " + " where e.dbxref_id = x.dbxref_id " + " and e.name='Experiment Description' "; return doQuery(connection, query, "getExperimentTitles"); } /** * ================ * SUBMISSION * ================ */ private void processSubmission(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getSubmissions(connection); int count = 0; while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); if (deletedSubMap.containsKey(submissionId)) { continue; } String name = res.getString("uniquename"); Item submission = getChadoDBConverter().createItem("Submission"); submission.setAttribute("title", name); String project = submissionProjectMap.get(submissionId); String projectItemIdentifier = projectIdRefMap.get(project); submission.setReference("project", projectItemIdentifier); String labName = submissionLabMap.get(submissionId); String labItemIdentifier = labIdRefMap.get(labName); submission.setReference("lab", labItemIdentifier); String organismName = submissionOrganismMap.get(submissionId); int divPos = organismName.indexOf(' '); String genus = organismName.substring(0, divPos); String species = organismName.substring(divPos + 1); OrganismRepository or = OrganismRepository.getOrganismRepository(); Integer taxId = Integer.valueOf( or.getOrganismDataByGenusSpecies(genus, species).getTaxonId()); LOG.debug("SPECIES: " + organismName + "|" + taxId); String organismItemIdentifier = getChadoDBConverter().getOrganismItem( or.getOrganismDataByGenusSpecies(genus, species).getTaxonId()).getIdentifier(); submission.setReference("organism", organismItemIdentifier); // ..store all Integer intermineObjectId = getChadoDBConverter().store(submission); // ..and fill the SubmissionDetails object SubmissionDetails details = new SubmissionDetails(); details.interMineObjectId = intermineObjectId; details.itemIdentifier = submission.getIdentifier(); details.labItemIdentifier = labItemIdentifier; details.title = name; submissionMap.put(submissionId, details); debugMap .put(details.itemIdentifier, submission.getClassName()); count++; } LOG.info("created " + count + " submissions"); res.close(); LOG.info("PROCESS TIME submissions: " + (System.currentTimeMillis() - bT) + " ms"); } /** * Return the rows needed for the submission table. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getSubmissions(Connection connection) throws SQLException { String query = "SELECT experiment_id, uniquename " + "FROM experiment"; return doQuery(connection, query, "getSubmissions"); } /** * submission attributes (table experiment_prop) * * @param connection * @throws SQLException * @throws ObjectStoreException */ private void processSubmissionAttributes(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getExperimentProperties(connection); int count = 0; while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); if (deletedSubMap.containsKey(submissionId)) { continue; } String heading = res.getString("name"); String value = res.getString("value"); // TODO this is a temporary hack to make sure we get properly matched Experiment.factors // EF are dealt with separately if (heading.startsWith("Experimental Factor")) { continue; } String fieldName = FIELD_NAME_MAP.get(heading); if (fieldName == null) { LOG.error("NOT FOUND in FIELD_NAME_MAP: " + heading + " [experiment]"); continue; } else if (fieldName == NOT_TO_BE_LOADED) { continue; } if ("DCCid".equals(fieldName)) { value = DCC_PREFIX + value; LOG.debug("DCC: " + submissionId + ", " + value); dccIdMap.put(submissionId, value); } if ("category".equals(fieldName)) { // Data Type, stored in experiment submissionExpCatMap.put(submissionId, value); continue; } if (fieldName.endsWith("Read Count")) { // all read counts are considered a collection for submission Item readCount = getChadoDBConverter().createItem("ReadCount"); readCount.setAttribute("name", fieldName); readCount.setAttribute("value", value); // setting references to SubmissionData readCount.setReference("submission", submissionMap.get(submissionId).itemIdentifier); Integer intermineObjectId = getChadoDBConverter().store(readCount); continue; } if ("experimentType".equals(fieldName)) { // Assay Type submissionWithExpTypeSet.add(submissionId); } if ("pubMedId".equals(fieldName)) { // sometime in the form PMID:16938558 if (value.contains(":")) { value = value.substring(value.indexOf(':') + 1); } Item pub = getChadoDBConverter().createItem("Publication"); pub.setAttribute(fieldName, value); Integer intermineObjectId = getChadoDBConverter().store(pub); publicationIdMap.put(submissionId, intermineObjectId); publicationIdRefMap.put(submissionId, pub.getIdentifier()); continue; } setAttribute(submissionMap.get(submissionId).interMineObjectId, fieldName, value); count++; } LOG.info("created " + count + " submissions attributes"); res.close(); LOG.info("PROCESS TIME submissions attributes: " + (System.currentTimeMillis() - bT) + " ms"); } /** * Return the rows needed for submission from the experiment_prop table. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getExperimentProperties(Connection connection) throws SQLException { String query = "SELECT ep.experiment_id, ep.name, ep.value, ep.rank " + "from experiment_prop ep "; return doQuery(connection, query, "getExperimentProperties"); } /** * ========================== * EXPERIMENTAL FACTORS * ========================== */ private void processEFactor(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getEFactors(connection); int count = 0; int prevRank = -1; int prevSub = -1; ExperimentalFactor ef = null; String name = null; while (res.next()) { Integer submissionId = new Integer(res.getInt("experiment_id")); if (deletedSubMap.containsKey(submissionId)) { continue; } Integer rank = new Integer(res.getInt("rank")); String value = res.getString("value"); // the data is alternating between EF types and names, in order. if (submissionId != prevSub) { // except for the first record, this is a new EF object if (!res.isFirst()) { submissionEFMap.put(prevSub, ef); LOG.info("EF MAP: " + dccIdMap.get(prevSub) + "|" + ef.efNames); LOG.info("EF MAP types: " + rank + "|" + ef.efTypes); } ef = new ExperimentalFactor(); } if (rank != prevRank || submissionId != prevSub) { // this is a name if (getPreferredSynonym(value) != null) { value = getPreferredSynonym(value); } ef.efNames.add(value); name = value; count++; } else { // this is a type ef.efTypes.put(name, value); name = null; if (res.isLast()) { submissionEFMap.put(submissionId, ef); LOG.debug("EF MAP last: " + submissionId + "|" + rank + "|" + ef.efNames); } } prevRank = rank; prevSub = submissionId; } res.close(); LOG.info("created " + count + " experimental factors"); LOG.info("PROCESS TIME experimental factors: " + (System.currentTimeMillis() - bT) + " ms"); } /** * Return the rows needed for the experimental factors. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getEFactors(Connection connection) throws SQLException { String query = "SELECT ep.experiment_id, ep.name, ep.value, ep.rank " + " FROM experiment_prop ep " + " where ep.name = 'Experimental Factor Name' " + " OR ep.name = 'Experimental Factor Type' " + " ORDER BY 1,4,2"; return doQuery(connection, query, "getEFactors"); } /** * ============== * PROTOCOL * ============== */ private void processProtocolTable(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getProtocols(connection); int count = 0; while (res.next()) { Integer protocolChadoId = new Integer(res.getInt("protocol_id")); String name = res.getString("name"); String description = res.getString("description"); String wikiLink = res.getString("accession"); Integer version = res.getInt("version"); // needed: it breaks otherwise if (description.length() == 0) { description = "N/A"; } Protocol thisProt = new Protocol(); thisProt.protocolId = protocolChadoId; // rm? thisProt.name = name; thisProt.description = description; thisProt.wikiLink = wikiLink; thisProt.version = version; protocolMap.put(protocolChadoId, thisProt); // we'll do it when creating AP //createProtocol(protocolChadoId, name, description, wikiLink, version); count++; } res.close(); LOG.info("found " + count + " protocols"); LOG.info("PROCESS TIME protocols: " + (System.currentTimeMillis() - bT) + " ms"); } // now doing it with applied protocol (to avoid creating it for delete subs) private String createProtocol(Integer chadoId, String name, String description, String wikiLink, Integer version) throws ObjectStoreException { String protocolItemId = protocolsMap.get(wikiLink); // rename? if (protocolItemId == null) { Item protocol = getChadoDBConverter().createItem("Protocol"); protocol.setAttribute("name", name); protocol.setAttribute("description", description); protocol.setAttribute("wikiLink", wikiLink); protocol.setAttribute("version", "" + version); Integer intermineObjectId = getChadoDBConverter().store(protocol); protocolItemId = protocol.getIdentifier(); protocolItemToObjectId.put(protocolItemId, intermineObjectId); protocolsMap.put(wikiLink, protocolItemId); } protocolItemIds.put(chadoId, protocolItemId); return protocolItemId; } private Integer getProtocolInterMineId(Integer chadoId) { return protocolItemToObjectId.get(protocolItemIds.get(chadoId)); } /** * Return the rows needed from the protocol table. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getProtocols(Connection connection) throws SQLException { String query = "SELECT protocol_id, name, protocol.description, accession, protocol.version" + " FROM protocol, dbxref" + " WHERE protocol.dbxref_id = dbxref.dbxref_id"; return doQuery(connection, query, "getProtocols"); } /** * to store protocol attributes */ private void processProtocolAttributes(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getProtocolAttributes(connection); int count = 0; while (res.next()) { Integer protocolId = new Integer(res.getInt("protocol_id")); String heading = res.getString("heading"); String value = res.getString("value"); String fieldName = FIELD_NAME_MAP.get(heading); if (fieldName == null) { LOG.error("NOT FOUND in FIELD_NAME_MAP: " + heading + " [protocol]"); continue; } else if (fieldName == NOT_TO_BE_LOADED) { continue; } if (getProtocolInterMineId(protocolId) != null) { // in case of deleted sub setAttribute(getProtocolInterMineId(protocolId), fieldName, value); if ("type".equals(fieldName)) { protocolTypesMap.put(protocolId, value); } count++; } } LOG.info("created " + count + " protocol attributes"); res.close(); LOG.info("PROCESS TIME protocol attributes: " + (System.currentTimeMillis() - bT) + " ms"); } /** * Return the rows needed for protocols from the attribute table. * This is a protected method so that it can be overridden for testing * @param connection database connection * @return rows needed for protocols from the attribute table * @throws SQLException if something goes wrong. */ protected ResultSet getProtocolAttributes(Connection connection) throws SQLException { String query = "SELECT p.protocol_id, a.heading, a.value " + "from protocol p, attribute a, protocol_attribute pa " + "where pa.attribute_id = a.attribute_id " + "and pa.protocol_id = p.protocol_id "; return doQuery(connection, query, "getProtocolAttributes"); } /** * ====================== * APPLIED PROTOCOL * ====================== */ private void processAppliedProtocolTable(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getAppliedProtocols(connection); int count = 0; boolean isADeletedSub = false; while (res.next()) { Integer appliedProtocolId = new Integer(res.getInt("applied_protocol_id")); Integer protocolId = new Integer(res.getInt("protocol_id")); Integer submissionId = new Integer(res.getInt("experiment_id")); // the results are ordered, first ap have a subId // if we find a deleted sub, we know that subsequent records with null // subId belongs to the deleted sub if (submissionId == 0) { boolean t = true; if (isADeletedSub == t) { continue; } } else { if (deletedSubMap.containsKey(submissionId)) { isADeletedSub = true; continue; } else { isADeletedSub = false; } } Item appliedProtocol = getChadoDBConverter().createItem("AppliedProtocol"); // creating and setting references to protocols // String protocolItemId = protocolItemIds.get(protocolId); if (protocolId != null) { Protocol qq = protocolMap.get(protocolId); String protocolItemId = createProtocol(qq); appliedProtocol.setReference("protocol", protocolItemId); } if (submissionId > 0) { // setting reference to submission // probably to rm (we do it later anyway). TODO: check appliedProtocol.setReference("submission", submissionMap.get(submissionId).itemIdentifier); } // store it and add to maps Integer intermineObjectId = getChadoDBConverter().store(appliedProtocol); appliedProtocolIdMap .put(appliedProtocolId, intermineObjectId); appliedProtocolIdRefMap .put(appliedProtocolId, appliedProtocol.getIdentifier()); count++; } LOG.info("created " + count + " appliedProtocol"); res.close(); LOG.info("PROCESS TIME applied protocols: " + (System.currentTimeMillis() - bT) + " ms"); } private String createProtocol(Protocol p) throws ObjectStoreException { String protocolItemId = protocolsMap.get(p.wikiLink); // rename map? if (protocolItemId == null) { Item protocol = getChadoDBConverter().createItem("Protocol"); protocol.setAttribute("name", p.name); protocol.setAttribute("description", p.description); protocol.setAttribute("wikiLink", p.wikiLink); protocol.setAttribute("version", "" + p.version); Integer intermineObjectId = getChadoDBConverter().store(protocol); protocolItemId = protocol.getIdentifier(); protocolItemToObjectId.put(protocolItemId, intermineObjectId); protocolsMap.put(p.wikiLink, protocolItemId); } protocolItemIds.put(p.protocolId, protocolItemId); return protocolItemId; } /** * Return the rows needed from the appliedProtocol table. * This is a protected method so that it can be overridden for testing * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getAppliedProtocols(Connection connection) throws SQLException { String query = "SELECT eap.experiment_id ,ap.applied_protocol_id, ap.protocol_id" + " FROM applied_protocol ap" + " LEFT JOIN experiment_applied_protocol eap" + " ON (eap.first_applied_protocol_id = ap.applied_protocol_id )"; return doQuery(connection, query, "getAppliedProtocols"); } /** * ====================== * APPLIED DATA * ====================== */ private void processAppliedData(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getAppliedData(connection); int count = 0; while (res.next()) { Integer dataId = new Integer(res.getInt("data_id")); // check if not belonging to a deleted sub Integer submissionId = dataSubmissionMap.get(dataId); if (submissionId == null || deletedSubMap.containsKey(submissionId)) { continue; } String name = res.getString("name"); String heading = res.getString("heading"); String value = res.getString("value"); String typeId = res.getString("type_id"); String url = res.getString("url"); // check if this datum has an official name: ResultSet oName = getOfficialName(connection, dataId); String officialName = null; while (oName.next()) { officialName = oName.getString(1); } // if there is one, use it instead of the value String datumType = getCvterm(connection, typeId); name = getCvterm(connection, typeId); if (!StringUtils.isEmpty(officialName) && doReplaceWithOfficialName(heading, datumType)) { value = officialName; } Item submissionData = getChadoDBConverter().createItem("SubmissionData"); if (name != null && !"".equals(name)) { submissionData.setAttribute("name", name); } // if no name for attribute fetch the cvterm of the type if ((name == null || "".equals(name)) && typeId != null) { name = getCvterm(connection, typeId); submissionData.setAttribute("name", name); } if (!StringUtils.isEmpty(value)) { submissionData.setAttribute("value", value); } submissionData.setAttribute("type", heading); // store it and add to object and maps Integer intermineObjectId = getChadoDBConverter().store(submissionData); AppliedData aData = new AppliedData(); aData.intermineObjectId = intermineObjectId; aData.itemIdentifier = submissionData.getIdentifier(); aData.value = value; aData.actualValue = res.getString("value"); aData.dataId = dataId; aData.type = heading; aData.name = name; aData.url = url; updateADMap(aData, dataId, intermineObjectId); //appliedDataMap.put(dataId, aData); count++; } LOG.info("created " + count + " SubmissionData"); res.close(); LOG.info("PROCESS TIME submission data: " + (System.currentTimeMillis() - bT) + " ms"); } // For some data types we don't want to replace with official name - e.g. file names and // database record ids. It looks like the official name shouldn't actually be present. private boolean doReplaceWithOfficialName(String heading, String type) { if ("Result File".equals(heading)) { return false; } if ("Result Value".equals(heading) && DB_RECORD_TYPES.contains(type)) { return false; } return true; } /** * Return the rows needed for data from the applied_protocol_data table. * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getAppliedData(Connection connection) throws SQLException { String query = "SELECT d.data_id," + " d.heading, d.name, d.value, d.type_id, z.url" + " FROM data d" + " LEFT JOIN dbxref as y ON (d.dbxref_id = y.dbxref_id)" + " LEFT JOIN db as z ON (y.db_id = z.db_id)"; return doQuery(connection, query, "getAppliedData"); } /** * Return the rows needed for data from the applied_protocol_data table. * * @param connection the db connection * @param dataId the dataId * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getOfficialName(Connection connection, Integer dataId) throws SQLException { String query = "SELECT a.value " + " from attribute a, data_attribute da " + " where a.attribute_id=da.attribute_id " + " and da.data_id=" + dataId + " and a.heading='official name'"; return doQuery(connection, query); } /** * Fetch a cvterm by id and cache results in cvtermCache. Returns null if the cv terms isn't * found. * @param connection to chado database * @param cvtermId internal chado id for a cvterm * @return the cvterm name or null if not found * @throws SQLException if database access problem */ private String getCvterm(Connection connection, String cvtermId) throws SQLException { String cvTerm = cvtermCache.get(cvtermId); if (cvTerm == null) { String query = "SELECT c.name " + " from cvterm c" + " where c.cvterm_id=" + cvtermId; Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); while (res.next()) { cvTerm = res.getString("name"); } cvtermCache.put(cvtermId, cvTerm); } return cvTerm; } /** * ===================== * DATA ATTRIBUTES * ===================== */ private void processAppliedDataAttributesNEW(Connection connection) throws SQLException, ObjectStoreException { // attempts to collate attributes // TODO check! long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getAppliedDataAttributes(connection); int count = 0; Integer previousDataId = 0; String previousName = null; String value = null; String type = null; while (res.next()) { Integer dataId = new Integer(res.getInt("data_id")); // check if not belonging to a deleted sub // better way? Integer submissionId = dataSubmissionMap.get(dataId); if (submissionId == null || deletedSubMap.containsKey(submissionId)) { continue; } String name = res.getString("heading"); // LOG.info("DA " + dataId + ": " + name); if (previousDataId == 0) { //first pass value = res.getString("value"); type = res.getString("name"); previousDataId = dataId; previousName = name; LOG.info("DA0 " + dataId + ": " + name + "|" + value); continue; } if (dataId > previousDataId) { Item dataAttribute = storeDataAttribute(value, type, previousDataId, previousName); value = res.getString("value"); type = res.getString("name"); count++; previousDataId = dataId; previousName = name; LOG.info("DA1 new: " + previousDataId + ": " + previousName + "|" + value); continue; } if (!name.equalsIgnoreCase(previousName)) { Item dataAttribute = storeDataAttribute(value, type, dataId, previousName); // LOG.info("DA2 store: " + dataId + ": " + previousName + "|" + value); count ++; value = res.getString("value"); previousName = name; LOG.info("DA2 new: " + dataId + ": " + previousName + "|" + value); } else { value = value + ", " + res.getString("value"); } type = res.getString("name"); previousDataId = dataId; if (res.isLast()) { Item dataAttribute = storeDataAttribute(value, type, dataId, name); count++; } } LOG.info("created " + count + " data attributes"); res.close(); LOG.info("PROCESS TIME data attributes: " + (System.currentTimeMillis() - bT) + " ms"); } /** * @param value * @param type * @param dataId * @param name * @return * @throws ObjectStoreException */ private Item storeDataAttribute(String value, String type, Integer dataId, String name) throws ObjectStoreException { Item dataAttribute = getChadoDBConverter().createItem("SubmissionDataAttribute"); if (name != null && !"".equals(name)) { dataAttribute.setAttribute("name", name); } if (!StringUtils.isEmpty(value)) { dataAttribute.setAttribute("value", value); } if (!StringUtils.isEmpty(type)) { dataAttribute.setAttribute("type", type); } // setting references to SubmissionData dataAttribute.setReference("submissionData", appliedDataMap.get(dataId).itemIdentifier); getChadoDBConverter().store(dataAttribute); return dataAttribute; } private void processAppliedDataAttributes(Connection connection) throws SQLException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getAppliedDataAttributes(connection); int count = 0; while (res.next()) { Integer dataId = new Integer(res.getInt("data_id")); // check if not belonging to a deleted sub // better way? Integer submissionId = dataSubmissionMap.get(dataId); if (submissionId == null || deletedSubMap.containsKey(submissionId)) { continue; } String name = res.getString("heading"); String value = res.getString("value"); String type = res.getString("name"); Item dataAttribute = storeDataAttribute(value, type, dataId, name); count++; } LOG.info("created " + count + " data attributes"); res.close(); LOG.info("PROCESS TIME data attributes: " + (System.currentTimeMillis() - bT) + " ms"); } // first value in the list of synonyms is the 'preferred' value private static String[][] synonyms = new String[][]{ new String[] {"developmental stage", "stage", "developmental_stage", "dev stage", "devstage"}, new String[] {"strain", "strain_or_line"}, new String[] {"cell line", "cell_line", "Cell line", "cell id"}, new String[] {"array", "adf"}, new String[] {"compound", "Compound"}, new String[] {"incubation time", "Incubation Time"}, new String[] {"RNAi reagent", "RNAi_reagent", "dsRNA"}, new String[] {"temperature", "temp"} }; private static List<String> makeLookupList(String initialLookup) { for (String[] synonymType : synonyms) { for (String synonym : synonymType) { if (synonym.equals(initialLookup)) { return Arrays.asList(synonymType); } } } return new ArrayList<String>(Collections.singleton(initialLookup)); } private static String getPreferredSynonym(String initialLookup) { return makeLookupList(initialLookup).get(0); } private static Set<String> unifyFactorNames(Collection<String> original) { Set<String> unified = new HashSet<String>(); for (String name : original) { unified.add(getPreferredSynonym(name)); } return unified; } private class SubmissionReference { public SubmissionReference(Integer referencedSubmissionId, String dataValue) { this.referencedSubmissionId = referencedSubmissionId; this.dataValue = dataValue; } private Integer referencedSubmissionId; private String dataValue; } // process new query // get DCC id // add antibody to types private void processSubmissionProperties(Connection connection) throws SQLException, IOException, ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process ResultSet res = getAppliedDataAll(connection); final String comma = ","; String reportName = "build/" + getChadoDBConverter().getDatabase().getName() + "_subs_report.csv"; File f = new File(reportName); FileWriter writer = new FileWriter(f); writeHeader(comma, writer); SubmissionProperty buildSubProperty = null; Integer lastDataId = new Integer(-1); Map<String, SubmissionProperty> props = new HashMap<String, SubmissionProperty>(); Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes = new HashMap<Integer, Map<String, List<SubmissionProperty>>>(); submissionRefs = new HashMap<Integer, List<SubmissionReference>>(); while (res.next()) { Integer dataId = new Integer(res.getInt("data_id")); String dataHeading = res.getString("data_heading"); String dataName = res.getString("data_name"); String wikiPageUrl = res.getString("data_value"); String cvTerm = res.getString("cv_term"); String attHeading = res.getString("att_heading"); String attName = res.getString("att_name"); String attValue = res.getString("att_value"); String attDbxref = res.getString("att_dbxref"); int attRank = res.getInt("att_rank"); Integer submissionId = dataSubmissionMap.get(dataId); String dccId = dccIdMap.get(submissionId); writer.write(dccId + comma + dataHeading + comma + dataName + comma + wikiPageUrl + comma + cvTerm + comma + attHeading + comma + attName + comma + attValue + comma + attDbxref + System.getProperty("line.separator")); if (submissionId == null) { LOG.warn("Failed to find a submission id for data id " + dataId + " - this probably" + " means there is a problem with the applied_protocol DAG strucuture."); continue; } // Currently using attValue for referenced submission DCC id, should be dbUrl but seems // to be filled in incorrectly if (attHeading != null && attHeading.startsWith("modENCODE Reference")) { attValue = checkRefSub(wikiPageUrl, attValue, submissionId, dccId); } // we are starting a new data row if (dataId.intValue() != lastDataId.intValue()) { // have we seen this modencodewiki entry before? if (props.containsKey(wikiPageUrl)) { buildSubProperty = null; } else { buildSubProperty = new SubmissionProperty(getPreferredSynonym(dataName), wikiPageUrl); props.put(wikiPageUrl, buildSubProperty); } // submissionId -> [type -> SubmissionProperty] addToSubToTypes(subToTypes, submissionId, props.get(wikiPageUrl)); } if (buildSubProperty != null) { // we are building a new submission attribute, this is the first time we have // seen a data.value that points to modencodewiki buildSubProperty.addDetail(attHeading, attValue, attRank); } lastDataId = dataId; } writer.flush(); writer.close(); // Characteristics are modelled differently to protocol inputs/outputs, read in extra // properties here addSubmissionPropsFromCharacteristics(subToTypes, connection); // some submissions use reagents created in reference submissions, find the properties // of the reagents and add to referencing submission addSubmissionPropsFromReferencedSubmissions(subToTypes, props, submissionRefs); // create and store properties of submission storeSubProperties(subToTypes); LOG.info("PROCESS TIME submission properties: " + (System.currentTimeMillis() - bT) + " ms"); } /** * @param subToTypes * @throws ObjectStoreException */ private void storeSubProperties( Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes) throws ObjectStoreException { for (Integer submissionId : subToTypes.keySet()) { Integer storedSubmissionId = submissionMap.get(submissionId).interMineObjectId; if (deletedSubMap.containsKey(submissionId)) { continue; } Map<String, List<SubmissionProperty>> typeToProp = subToTypes.get(submissionId); String dccId = dccIdMap.get(submissionId); ExperimentalFactor ef = submissionEFMap.get(submissionId); if (ef == null) { LOG.warn("No experimental factors found for submission: " + dccId); continue; } Set<String> exFactorNames = unifyFactorNames(ef.efNames); LOG.info("PROPERTIES " + dccId + " typeToProp keys: " + typeToProp.keySet()); List<Item> allPropertyItems = new ArrayList<Item>(); // DEVELOPMENTAL STAGE List<Item> devStageItems = new ArrayList<Item>(); devStageItems.addAll(createFromWikiPage(dccId, "DevelopmentalStage", typeToProp, makeLookupList("developmental stage"))); if (devStageItems.isEmpty()) { devStageItems.addAll(lookForAttributesInOtherWikiPages(dccId, "DevelopmentalStage", typeToProp, new String[] { "developmental stage.developmental stage", "tissue.developmental stage", "tissue source.developmental stage", "cell line.developmental stage", "cell id.developmental stage" //, "RNA extract.Cell Type" })); } if (!devStageItems.isEmpty() && exFactorNames.contains("developmental stage")) { createExperimentalFactors(submissionId, "developmental stage", devStageItems); exFactorNames.remove("developmental stage"); } if (devStageItems.isEmpty()) { addNotApplicable("DevelopmentalStage", "developmental stage"); } storeSubmissionCollection(storedSubmissionId, "developmentalStages", devStageItems); allPropertyItems.addAll(devStageItems); // STRAIN List<Item> strainItems = new ArrayList<Item>(); strainItems.addAll(createFromWikiPage( dccId, "Strain", typeToProp, makeLookupList("strain"))); if (!strainItems.isEmpty() && exFactorNames.contains("strain")) { createExperimentalFactors(submissionId, "strain", strainItems); exFactorNames.remove("strain"); } if (strainItems.isEmpty()) { addNotApplicable("Strain", "strain"); } storeSubmissionCollection(storedSubmissionId, "strains", strainItems); allPropertyItems.addAll(strainItems); // ARRAY List<Item> arrayItems = new ArrayList<Item>(); arrayItems.addAll(createFromWikiPage( dccId, "Array", typeToProp, makeLookupList("array"))); if (arrayItems.isEmpty()) { arrayItems.addAll(lookForAttributesInOtherWikiPages(dccId, "Array", typeToProp, new String[] {"adf.official name"})); if (!arrayItems.isEmpty()) { LOG.debug("Attribute found in other wiki pages: " + dccId + " ARRAY "); } } if (!arrayItems.isEmpty() && exFactorNames.contains("array")) { createExperimentalFactors(submissionId, "array", arrayItems); exFactorNames.remove("array"); } if (arrayItems.isEmpty()) { addNotApplicable("Array", "array"); } storeSubmissionCollection(storedSubmissionId, "arrays", arrayItems); allPropertyItems.addAll(arrayItems); // CELL LINE List<Item> lineItems = new ArrayList<Item>(); lineItems.addAll(createFromWikiPage(dccId, "CellLine", typeToProp, makeLookupList("cell line"))); if (!lineItems.isEmpty() && exFactorNames.contains("cell line")) { createExperimentalFactors(submissionId, "cell line", lineItems); exFactorNames.remove("cell line"); } if (lineItems.isEmpty()) { addNotApplicable("CellLine", "cell line"); } storeSubmissionCollection(storedSubmissionId, "cellLines", lineItems); allPropertyItems.addAll(lineItems); // RNAi REAGENT List<Item> reagentItems = new ArrayList<Item>(); reagentItems.addAll(createFromWikiPage(dccId, "SubmissionProperty", typeToProp, makeLookupList("dsRNA"))); if (!reagentItems.isEmpty() && exFactorNames.contains("RNAi reagent")) { createExperimentalFactors(submissionId, "RNAi reagent", reagentItems); exFactorNames.remove("RNAi reagent"); } allPropertyItems.addAll(reagentItems); // ANTIBODY List<Item> antibodyItems = new ArrayList<Item>(); antibodyItems.addAll(createFromWikiPage(dccId, "Antibody", typeToProp, makeLookupList("antibody"))); if (antibodyItems.isEmpty()) { LOG.debug("ANTIBODY: " + typeToProp.get("antibody")); antibodyItems.addAll(lookForAttributesInOtherWikiPages(dccId, "Antibody", typeToProp, new String[] {"antibody.official name"})); if (!antibodyItems.isEmpty()) { LOG.debug("Attribute found in other wiki pages: " + dccId + " ANTIBODY "); } } if (!antibodyItems.isEmpty() && exFactorNames.contains("antibody")) { createExperimentalFactors(submissionId, "antibody", antibodyItems); exFactorNames.remove("antibody"); } if (antibodyItems.isEmpty()) { addNotApplicable("Antibody", "antibody"); } storeSubmissionCollection(storedSubmissionId, "antibodies", antibodyItems); allPropertyItems.addAll(antibodyItems); // TISSUE List<Item> tissueItems = new ArrayList<Item>(); tissueItems.addAll(createFromWikiPage( dccId, "Tissue", typeToProp, makeLookupList("tissue"))); if (tissueItems.isEmpty()) { tissueItems.addAll(lookForAttributesInOtherWikiPages(dccId, "Tissue", typeToProp, new String[] {"stage.tissue" , "cell line.tissue" , "cell id.tissue"})); if (!tissueItems.isEmpty()) { LOG.info("Attribute found in other wiki pages: " + dccId + " TISSUE"); } } if (!tissueItems.isEmpty() && exFactorNames.contains("tissue")) { createExperimentalFactors(submissionId, "tissue", tissueItems); exFactorNames.remove("tissue"); } if (tissueItems.isEmpty()) { addNotApplicable("Tissue", "tissue"); } storeSubmissionCollection(storedSubmissionId, "tissues", tissueItems); allPropertyItems.addAll(tissueItems); // There may be some other experimental factors that require SubmissionProperty objects // but don't fall into the categories above. Create them here and set experimental // factors. ArrayList<String> extraPropNames = new ArrayList<String>(exFactorNames); for (String exFactor : extraPropNames) { List<Item> extraPropItems = new ArrayList<Item>(); extraPropItems.addAll(lookForAttributesInOtherWikiPages(dccId, "SubmissionProperty", typeToProp, new String[] {exFactor})); allPropertyItems.addAll(extraPropItems); createExperimentalFactors(submissionId, exFactor, extraPropItems); exFactorNames.remove(exFactor); } // deal with remaining factor names (e.g. the ones for which we did // not find a corresponding attribute for (String exFactor : exFactorNames) { String type = ef.efTypes.get(exFactor); createEFItem(submissionId, type, exFactor, null); } storeSubmissionCollection(storedSubmissionId, "properties", allPropertyItems); } } /** * @param wikiPageUrl * @param attValue * @param submissionId * @param dccId * @return */ private String checkRefSub(String wikiPageUrl, String attValue, Integer submissionId, String dccId) { if (attValue.indexOf(":") > 0) { attValue = attValue.substring(0, attValue.indexOf(":")); } attValue = DCC_PREFIX + attValue; Integer referencedSubId = getSubmissionIdFromDccId(attValue); if (referencedSubId != null) { SubmissionReference subRef = new SubmissionReference(referencedSubId, wikiPageUrl); Util.addToListMap(submissionRefs, submissionId, subRef); LOG.info("Submission " + dccId + " (" + submissionId + ") has reference to " + attValue + " (" + referencedSubId + ")"); } else { LOG.warn("Could not find submission " + attValue + " referenced by " + dccId); } return attValue; } /** * @param comma * @param writer * @throws IOException */ private void writeHeader(final String comma, FileWriter writer) throws IOException { writer.write("submission" + comma); writer.write("data_heading" + comma); writer.write("data_name" + comma); writer.write("data_value" + comma); writer.write("cv_term" + comma); writer.write("att_heading" + comma); writer.write("att_name" + comma); writer.write("att_value" + comma); writer.write(System.getProperty("line.separator")); } // /** // * @param submissionId // * @param exFactorNames // * @param devStageItems // * @param clsName // * @param propName // * @throws ObjectStoreException // */ // private void finishProp(Integer submissionId, Integer storedSubmissionId, // Set<String> exFactorNames, // List<Item> devStageItems, String clsName, String propName) // throws ObjectStoreException { // if (devStageItems.isEmpty()) { // addNotApplicable(devStageItems, clsName, propName); // storeSubmissionCollection(storedSubmissionId, "developmentalStages", devStageItems); // } else { // if (exFactorNames.contains(propName)) { // createExperimentalFactors(submissionId, propName, devStageItems); // exFactorNames.remove(propName); // } // } // } /** * @param clsName the class name of the property (e.g. Strain) * @param propName the property name (e.g. strain) * @throws ObjectStoreException */ private void addNotApplicable(String clsName, String propName) throws ObjectStoreException { Item subProperty = getChadoDBConverter().createItem(clsName); subProperty.setAttribute("type", propName); subProperty.setAttribute("name", NA_PROP); getChadoDBConverter().store(subProperty); } // Traverse DAG following previous applied protocol links to build a list of all AppliedData private void findAppliedProtocolsAndDataFromEarlierInDag(Integer startDataId, List<AppliedData> foundAppliedData, List<AppliedProtocol> foundAppliedProtocols) { AppliedData aData = appliedDataMap.get(startDataId); if (foundAppliedData != null) { foundAppliedData.add(aData); } for (Integer previousAppliedProtocolId : aData.previousAppliedProtocols) { AppliedProtocol ap = appliedProtocolMap.get(previousAppliedProtocolId); if (foundAppliedProtocols != null) { foundAppliedProtocols.add(ap); } for (Integer previousDataId : ap.inputs) { findAppliedProtocolsAndDataFromEarlierInDag(previousDataId, foundAppliedData, foundAppliedProtocols); } } } private void createExperimentalFactors(Integer submissionId, String type, Collection<Item> items) throws ObjectStoreException { for (Item item : items) { createEFItem(submissionId, type, item.getAttribute("name").getValue(), item.getIdentifier()); } } private void createEFItemNEW(Integer current, String type, String efName, String propertyIdentifier) throws ObjectStoreException { // don't create an EF if it is a primer if (type.endsWith("primer")) { return; } String preferredType = getPreferredSynonym(type); String key = efName + preferredType; String [] efTok = {efName,preferredType}; // create the EF, if not there already if (!eFactorIdMap.containsKey(key)) { Item ef = getChadoDBConverter().createItem("ExperimentalFactor"); ef.setAttribute ("type", preferredType); ef.setAttribute ("name", efName); if (propertyIdentifier != null) { ef.setReference("property", propertyIdentifier); } LOG.info("ExFactor created for sub " + dccIdMap.get(current) + ":" + efName + "|" + type); Integer intermineObjectId = getChadoDBConverter().store(ef); eFactorIdMap.put(key, intermineObjectId); eFactorIdRefMap.put(key, ef.getIdentifier()); } // if pertinent to the current sub, add to the map for the references Util.addToListMap(submissionEFactorMap2, current, efTok); } private void createEFItem(Integer current, String type, String efName, String propertyIdentifier) throws ObjectStoreException { // don't create an EF if it is a primer if (type.endsWith("primer")) { return; } // create the EF, if not there already if (!eFactorIdMap.containsKey(efName)) { Item ef = getChadoDBConverter().createItem("ExperimentalFactor"); String preferredType = getPreferredSynonym(type); ef.setAttribute ("type", preferredType); ef.setAttribute ("name", efName); if (propertyIdentifier != null) { ef.setReference("property", propertyIdentifier); } LOG.info("ExFactor created for sub " + current + ":" + efName + "|" + type); Integer intermineObjectId = getChadoDBConverter().store(ef); eFactorIdMap.put(efName, intermineObjectId); eFactorIdRefMap.put(efName, ef.getIdentifier()); } // if pertinent to the current sub, add to the map for the references Util.addToListMap(submissionEFactorMap, current, efName); } private void addToSubToTypes(Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes, Integer submissionId, SubmissionProperty prop) { // submissionId -> [type -> SubmissionProperty] if (submissionId == null) { LOG.error("MISSING SUB: " + prop); return; //throw new RuntimeException("Called addToSubToTypes with a null sub id!"); } Map<String, List<SubmissionProperty>> typeToSubProp = subToTypes.get(submissionId); if (typeToSubProp == null) { typeToSubProp = new HashMap<String, List<SubmissionProperty>>(); subToTypes.put(submissionId, typeToSubProp); } List<SubmissionProperty> subProps = typeToSubProp.get(prop.type); if (subProps == null) { subProps = new ArrayList<SubmissionProperty>(); typeToSubProp.put(prop.type, subProps); } subProps.add(prop); } private void addSubmissionPropsFromCharacteristics( Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes, Connection connection) throws SQLException { ResultSet res = getAppliedDataCharacteristics(connection); Integer lastAttDbXref = new Integer(-1); Integer lastDataId = new Integer(-1); Map<Integer, SubmissionProperty> createdProps = new HashMap<Integer, SubmissionProperty>(); SubmissionProperty buildSubProperty = null; boolean isValidCharacteristic = false; Integer currentSubId = null; // we need those to attach the property to the correct sub Integer previousSubId = null; while (res.next()) { Integer dataId = new Integer(res.getInt("data_id")); String attHeading = res.getString("att_heading"); String attName = res.getString("att_name"); String attValue = res.getString("att_value"); Integer attDbxref = new Integer(res.getInt("att_dbxref")); int attRank = res.getInt("att_rank"); currentSubId = dataSubmissionMap.get(dataId); if (currentSubId == null) { LOG.info("DSM failing dataId: " + dataId + " - " + attHeading + "|" + attName + "|" + attValue); } if (dataId.intValue() != lastDataId.intValue() || attDbxref.intValue() != lastAttDbXref.intValue() || currentSubId != previousSubId) { // store the last build property if created, type is set only if we found an // attHeading of Characteristics // note: dbxref can remain the same in different subs -> or if (buildSubProperty != null && buildSubProperty.type != null) { createdProps.put(lastAttDbXref, buildSubProperty); addToSubToTypes(subToTypes, previousSubId, buildSubProperty); } // set up for next attDbxref if (createdProps.containsKey(attDbxref) && isValidCharacteristic) { // seen this property before so just add for this submission, don't build again buildSubProperty = null; isValidCharacteristic = false; addToSubToTypes(subToTypes, currentSubId, createdProps.get(attDbxref)); } else { buildSubProperty = new SubmissionProperty(); isValidCharacteristic = false; } } if (attHeading.startsWith("Characteristic")) { isValidCharacteristic = true; } // OR // if (buildSubProperty != null) { // if (attHeading.startsWith("Characteristic")) { // buildSubProperty.type = getPreferredSynonym(attName); // buildSubProperty.wikiPageUrl = attValue; // // add detail here as some Characteristics don't reference a wiki page // // but have all information on single row // buildSubProperty.addDetail(attName, attValue, attRank); // } else { // buildSubProperty.addDetail(attHeading, attValue, attRank); // } // } if (buildSubProperty != null) { if (attHeading.startsWith("Characteristic")) { String type = getPreferredSynonym(attName); String wikiUrl = attValue; String wikiType = checkWikiType(type, wikiUrl, currentSubId); buildSubProperty.type = wikiType; buildSubProperty.wikiPageUrl = wikiUrl; // add detail here as some Characteristics don't reference a wiki page // but have all information on single row buildSubProperty.addDetail(wikiType, attValue, attRank); } else { buildSubProperty.addDetail(attHeading, attValue, attRank); } } previousSubId = currentSubId; lastAttDbXref = attDbxref; lastDataId = dataId; } if (buildSubProperty != null && buildSubProperty.type != null) { createdProps.put(lastAttDbXref, buildSubProperty); addToSubToTypes(subToTypes, currentSubId, buildSubProperty); } } private String checkWikiType (String type, String wikiLink, Integer subId) { // for devstages and strain check the type on the wikilink and use it if different // from the declared one. LOG.info("WIKILINK: " + wikiLink + " -- type: " + type); if (wikiLink != null && wikiLink.contains(":")) { String wikiType = wikiLink.substring(0, wikiLink.indexOf(':')); if (type.equals(STRAIN)|| type.equals(DEVSTAGE)){ if (!congruentType(type, wikiType)) { LOG.warn("WIKILINK " + dccIdMap.get(subId) + ": " + type + " but in wiki url: " + wikiType); // not strictly necessary (code would deal with wikiType) if (wikiType.contains("Strain")){ return STRAIN; } if (wikiType.contains("Stage")){ return DEVSTAGE; } } } } return type; } private Boolean congruentType (String type, String wikiType) { // check only strain and devstages if (wikiType.contains("Strain") && !type.equals(STRAIN)){ return false; } if (wikiType.contains("Stage") && !type.equalsIgnoreCase(DEVSTAGE)){ return false; } return true; } // Some submission mention e.g. an RNA Sample but the details of how that sample was created, // stage, strain, etc are in a previous submission. There are references to previous submission // DCC ids where a sample with the corresponding name can be found. We then need to traverse // backwards along the AppliedProtocol DAG to find the stage, strain, etc wiki pages. These // should already have been processed so the properties can just be added to the referencing // submission. private void addSubmissionPropsFromReferencedSubmissions( Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes, Map<String, SubmissionProperty> props, Map<Integer, List<SubmissionReference>> submissionRefs) { for (Map.Entry<Integer, List<SubmissionReference>> entry : submissionRefs.entrySet()) { Integer submissionId = entry.getKey(); List<SubmissionReference> lref = entry.getValue(); Iterator<SubmissionReference> i = lref.iterator(); while (i.hasNext()) { SubmissionReference ref = i.next(); List<AppliedData> refAppliedData = findAppliedDataFromReferencedSubmission(ref); for (AppliedData aData : refAppliedData) { String possibleWikiUrl = aData.actualValue; if (possibleWikiUrl != null && props.containsKey(possibleWikiUrl)) { //LOG.debug("EEFF possible wikiurl: " + possibleWikiUrl); SubmissionProperty propFromReferencedSub = props.get(possibleWikiUrl); if (propFromReferencedSub != null) { addToSubToTypes(subToTypes, submissionId, propFromReferencedSub); LOG.debug("EEFF from referenced sub: " + propFromReferencedSub.type + ": " + propFromReferencedSub.details); } } } } } } private List<AppliedData> findAppliedDataFromReferencedSubmission(SubmissionReference subRef) { List<AppliedData> foundAppliedData = new ArrayList<AppliedData>(); findAppliedProtocolsAndDataFromReferencedSubmission(subRef, foundAppliedData, null); return foundAppliedData; } private List<AppliedProtocol> findAppliedProtocolsFromReferencedSubmission( SubmissionReference subRef) { List<AppliedProtocol> foundAppliedProtocols = new ArrayList<AppliedProtocol>(); findAppliedProtocolsAndDataFromReferencedSubmission(subRef, null, foundAppliedProtocols); return foundAppliedProtocols; } private void findAppliedProtocolsAndDataFromReferencedSubmission( SubmissionReference subRef, List<AppliedData> foundAppliedData, List<AppliedProtocol> foundAppliedProtocols) { String refDataValue = subRef.dataValue; Integer refSubId = subRef.referencedSubmissionId; for (AppliedData aData : appliedDataMap.values()) { String currentDataValue = aData.value; Integer currentDataSubId = dataSubmissionMap.get(aData.dataId); // added check that referenced and referring are not the same. if (refDataValue.equals(currentDataValue) && refSubId.equals(currentDataSubId)) { LOG.info("Found a matching data value: " + currentDataValue + " in referenced sub " + dccIdMap.get(currentDataSubId) + " for value " + aData.actualValue); Integer foundDataId = aData.dataId; findAppliedProtocolsAndDataFromEarlierInDag(foundDataId, foundAppliedData, foundAppliedProtocols); } } } private List<Item> createFromWikiPage(String dccId, String clsName, Map<String, List<SubmissionProperty>> typeToProp, List<String> types) throws ObjectStoreException { List<Item> items = new ArrayList<Item>(); List<SubmissionProperty> props = new ArrayList<SubmissionProperty>(); for (String type : types) { if (typeToProp.containsKey(type)) { props.addAll(typeToProp.get(type)); } } items.addAll(createItemsForSubmissionProperties(dccId, clsName, props)); return items; } private void storeSubmissionCollection(Integer storedSubmissionId, String name, List<Item> items) throws ObjectStoreException { if (!items.isEmpty()) { ReferenceList refList = new ReferenceList(name, getIdentifiersFromItems(items)); getChadoDBConverter().store(refList, storedSubmissionId); } } private List<String> getIdentifiersFromItems(Collection<Item> items) { List<String> ids = new ArrayList<String>(); for (Item item : items) { ids.add(item.getIdentifier()); } return ids; } private List<Item> createItemsForSubmissionProperties(String dccId, String clsName, List<SubmissionProperty> subProps) throws ObjectStoreException { List<Item> items = new ArrayList<Item>(); for (SubmissionProperty subProp : subProps) { Item item = getItemForSubmissionProperty(clsName, subProp, dccId); if (item != null) { items.add(item); } } return items; } private Item getItemForSubmissionProperty(String clsName, SubmissionProperty prop, String dccId) throws ObjectStoreException { Item propItem = subItemsMap.get(prop.wikiPageUrl); if (propItem == null) { if (clsName != null) { List<String> checkOfficialName = prop.details.get("official name"); if (checkOfficialName == null) { LOG.warn("No 'official name', using 'name' instead for: " + prop.wikiPageUrl); checkOfficialName = prop.details.get("name"); } if (checkOfficialName == null) { LOG.info("Official name - missing for property: " + prop.type + ", " + prop.wikiPageUrl); return null; } else if (checkOfficialName.size() != 1) { LOG.info("Official name - multiple times for property: " + prop.type + ", " + prop.wikiPageUrl + ", " + checkOfficialName); } String officialName = getCorrectedOfficialName(prop); propItem = createSubmissionProperty(clsName, officialName); propItem.setAttribute("type", getPreferredSynonym(prop.type)); propItem.setAttribute("wikiLink", WIKI_URL + prop.wikiPageUrl); if ("DevelopmentalStage".equals(clsName)) { setAttributeOnProp(prop, propItem, "sex", "sex"); List<String> devStageValues = prop.details.get("developmental stage"); if (devStageValues != null) { for (String devStageValue : devStageValues) { propItem.addToCollection("ontologyTerms", getDevStageTerm(devStageValue, dccId)); } } else { LOG.error("METADATA FAIL on " + dccId + ": no 'developmental stage' values for wiki page: " + prop.wikiPageUrl); } } else if ("Antibody".equals(clsName)) { setAttributeOnProp(prop, propItem, "antigen", "antigen"); setAttributeOnProp(prop, propItem, "host", "hostOrganism"); setAttributeOnProp(prop, propItem, "target name", "targetName"); setGeneItem(dccId, prop, propItem, "Antibody"); } else if ("Array".equals(clsName)) { setAttributeOnProp(prop, propItem, "platform", "platform"); setAttributeOnProp(prop, propItem, "resolution", "resolution"); setAttributeOnProp(prop, propItem, "genome", "genome"); } else if ("CellLine".equals(clsName)) { setAttributeOnProp(prop, propItem, "sex", "sex"); setAttributeOnProp(prop, propItem, "short description", "description"); setAttributeOnProp(prop, propItem, "species", "species"); setAttributeOnProp(prop, propItem, "tissue", "tissue"); setAttributeOnProp(prop, propItem, "cell type", "cellType"); setAttributeOnProp(prop, propItem, "target name", "targetName"); setGeneItem(dccId, prop, propItem, "CellLine"); } else if ("Strain".equals(clsName)) { setAttributeOnProp(prop, propItem, "species", "species"); setAttributeOnProp(prop, propItem, "source", "source"); // the following 2 should be mutually exclusive setAttributeOnProp(prop, propItem, "Description", "description"); setAttributeOnProp(prop, propItem, "details", "description"); setAttributeOnProp(prop, propItem, "aliases", "name"); setAttributeOnProp(prop, propItem, "reference", "reference"); setAttributeOnProp(prop, propItem, "target name", "targetName"); setGeneItem(dccId, prop, propItem, "Strain"); } else if ("Tissue".equals(clsName)) { setAttributeOnProp(prop, propItem, "species", "species"); setAttributeOnProp(prop, propItem, "sex", "sex"); setAttributeOnProp(prop, propItem, "organismPart", "organismPart"); } getChadoDBConverter().store(propItem); } subItemsMap.put(prop.wikiPageUrl, propItem); } return propItem; } private void setGeneItem(String dccId, SubmissionProperty prop, Item propItem, String source) throws ObjectStoreException { String targetText = null; String[] possibleTypes = new String[] {"target id"}; boolean tooMany = false; for (String targetType : possibleTypes) { if (prop.details.containsKey(targetType)) { if (prop.details.get(targetType).size() != 1) { // we used to complain if multiple values, now only // if they don't have the same value if (sameTargetValue(prop, source, targetType)) { tooMany = true; break; } } if (!tooMany) { targetText = prop.details.get(targetType).get(0); } break; } } if (targetText != null) { // if no target name was found use the target id if (!propItem.hasAttribute("targetName")) { propItem.setAttribute("targetName", targetText); } String geneItemId = getTargetGeneItemIdentfier(targetText, dccId); if (geneItemId != null) { propItem.setReference("target", geneItemId); } } } private boolean sameTargetValue(SubmissionProperty prop, String source, String targetType) { String value = prop.details.get(targetType).get(0); for (int i = 1; i < prop.details.get(targetType).size(); i++) { String newValue = prop.details.get(targetType).get(i); if (!newValue.equals(value)) { LOG.error(source + " (" + prop.wikiPageUrl + ") has more than 1 value for '" + targetType + "' field: " + prop.details.get(targetType)); //throw new RuntimeException(source + " should only have one value for '" // + targetType + "' field: " + prop.details.get(targetType)); return true; } } return false; } private void setAttributeOnProp(SubmissionProperty subProp, Item item, String metadataName, String attributeName) { if (subProp.details.containsKey(metadataName)) { if ("aliases".equalsIgnoreCase(metadataName)) { for (String s :subProp.details.get(metadataName)) { if ("yellow cinnabar brown speck".equalsIgnoreCase(s)) { // swapping name with fullName String full = item.getAttribute("name").getValue(); item.setAttribute("fullName", full); item.setAttribute(attributeName, s); break; } } } else if ("description".equalsIgnoreCase(metadataName) || "details".equalsIgnoreCase(metadataName)) { // description is often split in more than 1 line, details should be correct order StringBuffer sb = new StringBuffer(); for (String desc : subProp.details.get(metadataName)) { sb.append(desc); } if (sb.length() > 0) { item.setAttribute(attributeName, sb.toString()); } } else { String value = subProp.details.get(metadataName).get(0); item.setAttribute(attributeName, value); } } } private String getTargetGeneItemIdentfier(String geneTargetIdText, String dccId) throws ObjectStoreException { // TODO check: why not using only the else? String taxonId = ""; String originalId = null; String flyPrefix = "fly_genes:"; String wormPrefix = "worm_genes:"; if (geneTargetIdText.startsWith(flyPrefix)) { originalId = geneTargetIdText.substring(flyPrefix.length()); taxonId = "7227"; } else if (geneTargetIdText.startsWith(wormPrefix)) { originalId = geneTargetIdText.substring(wormPrefix.length()); taxonId = "6239"; } else { // attempt to work out the organism from the submission taxonId = getTaxonIdForSubmission(dccId); originalId = geneTargetIdText; LOG.debug("RESOLVER: found taxon " + taxonId + " for submission " + dccId); } IdResolver resolver = null; if ("7227".equals(taxonId)) { resolver = flyResolverFactory.getIdResolver(); } else if ("6239".equals(taxonId)) { resolver = wormResolverFactory.getIdResolver(); } else { LOG.info("RESOLVER: unable to work out organism for target id text: " + geneTargetIdText + " in submission " + dccId); } String geneItemId = null; String primaryIdentifier = resolveGene(originalId, taxonId, resolver); if (primaryIdentifier != null) { geneItemId = geneToItemIdentifier.get(primaryIdentifier); if (geneItemId == null) { Item gene = getChadoDBConverter().createItem("Gene"); geneItemId = gene.getIdentifier(); gene.setAttribute("primaryIdentifier", primaryIdentifier); getChadoDBConverter().store(gene); geneToItemIdentifier.put(primaryIdentifier, geneItemId); } else { LOG.info("RESOLVER fetched gene from cache: " + primaryIdentifier); } } return geneItemId; } private String resolveGene(String originalId, String taxonId, IdResolver resolver) { String primaryIdentifier = null; int resCount = resolver.countResolutions(taxonId, originalId); if (resCount != 1) { LOG.info("RESOLVER: failed to resolve gene to one identifier, ignoring " + "gene: " + originalId + " for organism " + taxonId + " count: " + resCount + " found ids: " + resolver.resolveId(taxonId, originalId) + "."); } else { primaryIdentifier = resolver.resolveId(taxonId, originalId).iterator().next(); LOG.info("RESOLVER found gene " + primaryIdentifier + " for original id: " + originalId); } return primaryIdentifier; } private List<Item> lookForAttributesInOtherWikiPages(String dccId, String clsName, Map<String, List<SubmissionProperty>> typeToProp, String[] lookFor) throws ObjectStoreException { List<Item> items = new ArrayList<Item>(); for (String typeProp : lookFor) { if (typeProp.indexOf(".") > 0) { String[] bits = StringUtils.split(typeProp, '.'); String type = bits[0]; String propName = bits[1]; if (typeToProp.containsKey(type)) { for (SubmissionProperty subProp : typeToProp.get(type)) { if (subProp.details.containsKey(propName)) { for (String value : subProp.details.get(propName)) { items.add(createNonWikiSubmissionPropertyItem(dccId, clsName, getPreferredSynonym(propName), correctAttrValue(value))); } } } if (!items.isEmpty()) { break; } } } else { // no attribute type given so use the data.value (SubmissionProperty.wikiPageUrl) // which probably won't be a wiki page if (typeToProp.containsKey(typeProp)) { for (SubmissionProperty subProp : typeToProp.get(typeProp)) { String value = subProp.wikiPageUrl; // This is an ugly special case to deal with 'exposure time/24 hours' if (subProp.details.containsKey("Unit")) { String unit = subProp.details.get("Unit").get(0); value = value + " " + unit + (unit.endsWith("s") ? "" : "s"); } items.add(createNonWikiSubmissionPropertyItem(dccId, clsName, subProp.type, correctAttrValue(value))); } } } } return items; } private String correctAttrValue(String value) { if (value == null) { return null; } value = value.replace("–", "-"); return value; } private Item createNonWikiSubmissionPropertyItem(String dccId, String clsName, String type, String name) throws ObjectStoreException { if ("DevelopmentalStage".equals(clsName)) { name = correctDevStageTerm(name); } Item item = nonWikiSubmissionProperties.get(name); if (item == null) { item = createSubmissionProperty(clsName, name); item.setAttribute("type", getPreferredSynonym(type)); if ("DevelopmentalStage".equals(clsName)) { String ontologyTermId = getDevStageTerm(name, dccId); item.addToCollection("ontologyTerms", ontologyTermId); } getChadoDBConverter().store(item); nonWikiSubmissionProperties.put(name, item); } return item; } private Item createSubmissionProperty(String clsName, String name) { Item subProp = getChadoDBConverter().createItem(clsName); if (name != null) { subProp.setAttribute("name", name); } return subProp; } private String getCorrectedOfficialName(SubmissionProperty prop) { String preferredType = getPreferredSynonym(prop.type); String name = null; if (prop.details.containsKey("official name")) { name = prop.details.get("official name").get(0); } else if (prop.details.containsKey("name")) { name = prop.details.get("name").get(0); } else { // no official name so maybe there is a key that matches the type - sometimes the // setup for Characteristics for (String lookup : makeLookupList(prop.type)) { if (prop.details.containsKey(lookup)) { name = prop.details.get(lookup).get(0); } } } return correctOfficialName(name, preferredType); } /** * Unify variations on similar official names. * @param name the original 'official name' value * @param type the treatment depends on the type * @return a unified official name */ protected String correctOfficialName(String name, String type) { if (name == null) { return null; } if ("developmental stage".equals(type)) { name = name.replace("_", " "); name = name.replaceFirst("embryo", "Embryo"); name = name.replaceFirst("Embyro", "Embryo"); if (name.matches("E\\d.*")) { name = name.replaceFirst("^E", "Embryo "); } if (name.matches("Embryo.*\\d")) { name = name + " h"; } if (name.matches(".*hr")) { name = name.replace("hr", "h"); } if (name.matches("Embryo.*\\dh")) { name = name.replaceFirst("h", " h"); } if (name.startsWith("DevStage:")) { name = name.replaceFirst("DevStage:", "").trim(); } if (name.matches("L\\d")) { name = name + " stage larvae"; } if (name.matches(".*L\\d")) { name = name + " stage larvae"; } if (name.matches("WPP.*")) { name = name.replaceFirst("WPP", "White prepupae (WPP)"); } } return name; } private String getDevStageTerm(String value, String dccId) throws ObjectStoreException { value = correctDevStageTerm(value); // there may be duplicate terms for fly and worm, include taxon in key String taxonId = getTaxonIdForSubmission(dccId); OrganismRepository or = OrganismRepository.getOrganismRepository(); String genus = or.getOrganismDataByTaxon(Integer.parseInt(taxonId)).getGenus(); String key = value + "_" + genus; String identifier = devStageTerms.get(key); if (identifier == null) { Item term = getChadoDBConverter().createItem("OntologyTerm"); term.setAttribute("name", value); String ontologyRef = getDevelopmentOntologyByTaxon(taxonId); if (ontologyRef != null) { term.setReference("ontology", ontologyRef); } getChadoDBConverter().store(term); devStageTerms.put(key, term.getIdentifier()); identifier = term.getIdentifier(); } return identifier; } private String correctDevStageTerm(String value) { // some terms are prefixed with ontology namespace String prefix = "FlyBase development CV:"; if (value.startsWith(prefix)) { value = value.substring(prefix.length()); } return value; } private String getTaxonIdForSubmission(String dccId) { Integer subChadoId = getSubmissionIdFromDccId(dccId); String organism = submissionOrganismMap.get(subChadoId); OrganismRepository or = OrganismRepository.getOrganismRepository(); return "" + or.getOrganismDataByFullName(organism).getTaxonId(); } private String getDevelopmentOntologyByTaxon(String taxonId) throws ObjectStoreException { if (taxonId == null) { return null; } String ontologyName = null; OrganismRepository or = OrganismRepository.getOrganismRepository(); String genus = or.getOrganismDataByTaxon(Integer.parseInt(taxonId)).getGenus(); if ("Drosophila".equals(genus)) { ontologyName = "Fly Development"; } else { ontologyName = "Worm Development"; } String ontologyId = devOntologies.get(ontologyName); if (ontologyId == null) { Item ontology = getChadoDBConverter().createItem("Ontology"); ontology.setAttribute("name", ontologyName); getChadoDBConverter().store(ontology); ontologyId = ontology.getIdentifier(); devOntologies.put(ontologyName, ontologyId); } return ontologyId; } private Integer getSubmissionIdFromDccId(String dccId) { for (Map.Entry<Integer, String> entry : dccIdMap.entrySet()) { if (entry.getValue().equals(dccId)) { return entry.getKey(); } } return null; } /** * Return the rows needed for data from the applied_protocol_data table. * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getAppliedDataAll(Connection connection) throws SQLException { String sraAcc = "SRA acc"; String query = "SELECT d.data_id, d.heading as data_heading," + " d.name as data_name, d.value as data_value," + " c.name as cv_term," + " a.attribute_id, a.heading as att_heading, a.name as att_name," + " a.value as att_value," + " a.dbxref_id as att_dbxref, a.rank as att_rank" + " FROM data d" + " LEFT JOIN data_attribute da ON (d.data_id = da.data_id)" + " LEFT JOIN attribute a ON (da.attribute_id = a.attribute_id)" + " LEFT JOIN cvterm c ON (d.type_id = c.cvterm_id)" + " LEFT JOIN dbxref as x ON (a.dbxref_id = x.dbxref_id)" + " WHERE d.name != '" + sraAcc + "'" + " AND d.value != '' " + " ORDER BY d.data_id"; return doQuery(connection, query, "getAppliedDataAll"); } /** * Return the rows needed for data from the applied_protocol_data table. * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getAppliedDataCharacteristics(Connection connection) throws SQLException { String query = "select d.data_id, d.heading as data_heading," + " d.name as data_name, d.value as data_value," + " a.attribute_id, a.heading as att_heading, a.name as att_name," + " a.value as att_value," + " a.dbxref_id as att_dbxref, a.rank as att_rank" + " FROM data d, data_attribute da, attribute a, dbxref ax, db" + " WHERE d.data_id = da.data_id" + " AND da.attribute_id = a.attribute_id" + " AND a.dbxref_id = ax.dbxref_id" + " AND ax.db_id = db.db_id" + " ORDER BY d.data_id, a.dbxref_id "; return doQuery(connection, query, "getAppliedDataCharacteristics"); } private class SubmissionProperty { protected String type; protected String wikiPageUrl; protected Map<String, List<String>> details; protected SubmissionProperty() { details = new HashMap<String, List<String>>(); } public SubmissionProperty(String type, String wikiPageUrl) { this.type = type; this.wikiPageUrl = wikiPageUrl; details = new HashMap<String, List<String>>(); } public void addDetail(String type, String value, int rank) { List<String> values = details.get(type); if (values == null) { values = new ArrayList<String>(); details.put(type, values); } while (values.size() <= rank) { values.add(null); } values.set(rank, value); } public String toString() { return this.type + ": " + this.wikiPageUrl + this.details.entrySet(); } } private final class DatabaseRecordConfig { private String dbName; private String dbDescrition; private String dbURL; private Set<String> types = new HashSet<String>(); private DatabaseRecordConfig() { // don't } } private Set<DatabaseRecordConfig> initDatabaseRecordConfigs() { Set<DatabaseRecordConfig> configs = new HashSet<DatabaseRecordConfig>(); DatabaseRecordConfig geo = new DatabaseRecordConfig(); geo.dbName = "GEO"; geo.dbDescrition = "Gene Expression Omnibus (NCBI)"; geo.dbURL = "http://www.ncbi.nlm.nih.gov/projects/geo/query/acc.cgi?acc="; geo.types.add("GEO_record"); configs.add(geo); DatabaseRecordConfig ae = new DatabaseRecordConfig(); ae.dbName = "ArrayExpress"; ae.dbDescrition = "ArrayExpress (EMBL-EBI)"; ae.dbURL = "http://www.ebi.ac.uk/microarray-as/ae/browse.html?keywords="; ae.types.add("ArrayExpress_record"); configs.add(ae); DatabaseRecordConfig sra = new DatabaseRecordConfig(); sra.dbName = "SRA"; sra.dbDescrition = "Sequence Read Archive (NCBI)"; sra.dbURL = "http://www.ncbi.nlm.nih.gov/Traces/sra/sra.cgi?cmd=viewer&m=data&s=viewer&run="; sra.types.add("ShortReadArchive_project_ID_list (SRA)"); sra.types.add("ShortReadArchive_project_ID (SRA)"); configs.add(sra); DatabaseRecordConfig ta = new DatabaseRecordConfig(); ta.dbName = "Trace Archive"; ta.dbDescrition = "Trace Archive (NCBI)"; ta.dbURL = "http://www.ncbi.nlm.nih.gov/Traces/trace.cgi?&cmd=retrieve&val="; ta.types.add("TraceArchive_record"); configs.add(ta); DatabaseRecordConfig de = new DatabaseRecordConfig(); de.dbName = "dbEST"; de.dbDescrition = "Expressed Sequence Tags database (NCBI)"; de.dbURL = "http://www.ncbi.nlm.nih.gov/nucest/"; de.types.add("dbEST_record"); configs.add(de); return configs; } /** * Query to get data attributes. * * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getAppliedDataAttributes(Connection connection) throws SQLException { String query = "select da.data_id, a.heading, a.value, a.name " + " from data_attribute da, attribute a" + " where da.attribute_id = a.attribute_id"; return doQuery(connection, query, "getAppliedDataAttributes"); } /** * ================ * REFERENCES * ================ * to store references between submission and submissionData * (1 to many) */ private void setSubmissionRefs(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process // note: the map should contain only live submissions for (Integer submissionId : submissionDataMap.keySet()) { for (Integer dataId : submissionDataMap.get(submissionId)) { LOG.debug("DAG subRef subid: " + submissionId + " dataId: " + dataId); if (appliedDataMap.get(dataId).intermineObjectId == null) { continue; } Reference reference = new Reference(); reference.setName("submission"); reference.setRefId(submissionMap.get(submissionId).itemIdentifier); getChadoDBConverter().store(reference, appliedDataMap.get(dataId).intermineObjectId); } } LOG.info("TIME setting submission-data references: " + (System.currentTimeMillis() - bT) + " ms"); } /** * ===================== * DATABASE RECORDS * ===================== */ private void createDatabaseRecords(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process Set<DatabaseRecordConfig> configs = initDatabaseRecordConfigs(); for (Integer submissionId : submissionDataMap.keySet()) { LOG.info("DB RECORD for sub " + dccIdMap.get(submissionId) + "..."); List<Integer> submissionDbRecords = new ArrayList<Integer>(); for (Integer dataId : submissionDataMap.get(submissionId)) { AppliedData ad = appliedDataMap.get(dataId); if (ad.type.equalsIgnoreCase("Result Value")) { for (DatabaseRecordConfig conf : configs) { for (String type : conf.types) { if (ad.name.equals(type)) { submissionDbRecords.addAll(createDatabaseRecords(ad.value, conf)); } } } } // prepare map for setting references if (!submissionDbRecords.isEmpty()) { for (Integer dbRecord : submissionDbRecords) { addToMap(dbRecordIdSubItems, dbRecord, submissionMap.get(submissionId).itemIdentifier); } } } } LOG.info("TIME creating DatabaseRecord objects: " + (System.currentTimeMillis() - bT) + " ms"); bT = System.currentTimeMillis(); // set references // NB: we are setting them from dbRecord to submissions because more efficient // (a few subs have a big collection of dbRecords) for (Integer dbRecordId : dbRecordIdSubItems.keySet()) { ReferenceList col = new ReferenceList("submissions", dbRecordIdSubItems.get(dbRecordId)); getChadoDBConverter().store(col, dbRecordId); } LOG.info("TIME creating refs DatabaseRecord objects: " + (System.currentTimeMillis() - bT) + " ms"); } private List<Integer> createDatabaseRecords(String accession, DatabaseRecordConfig config) throws ObjectStoreException { List<Integer> dbRecordIds = new ArrayList<Integer>(); String defaultURL = config.dbURL; Set<String> cleanAccessions = new HashSet<String>(); // NOTE - this is a special case to deal with a very strange SRA accession format in some // Celniker submissions. The 'accession' is provided as e.g. // SRR013492.225322.1;SRR013492.462158.1;... // We just want the unique SRR ids if ("SRA".equals(config.dbName) && (accession.indexOf(';') != -1 || accession.indexOf('.') != -1)) { for (String part : accession.split(";")) { if (part.indexOf('.') != -1) { cleanAccessions.add(part.substring(0, part.indexOf('.'))); } else { cleanAccessions.add(part); } } } else if ("SRA".equals(config.dbName) && (accession.startsWith("SRX"))) { config.dbURL = "http://www.ncbi.nlm.nih.gov/sra/"; dbRecordIds.add(createDatabaseRecord(accession, config)); config.dbURL = defaultURL; } else { cleanAccessions.add(accession); } for (String cleanAccession : cleanAccessions) { dbRecordIds.add(createDatabaseRecord(cleanAccession, config)); } return dbRecordIds; } private Integer createDatabaseRecord(String accession, DatabaseRecordConfig config) throws ObjectStoreException { DatabaseRecordKey key = new DatabaseRecordKey(config.dbName, accession); Integer dbRecordId = dbRecords.get(key); if (dbRecordId == null) { Item dbRecord = getChadoDBConverter().createItem("DatabaseRecord"); dbRecord.setAttribute("database", config.dbName); dbRecord.setAttribute("description", config.dbDescrition); if (StringUtils.isEmpty(accession)) { dbRecord.setAttribute("accession", "To be confirmed"); } else { dbRecord.setAttribute("url", config.dbURL + accession); dbRecord.setAttribute("accession", accession); } dbRecordId = getChadoDBConverter().store(dbRecord); dbRecords.put(key, dbRecordId); } return dbRecordId; } private class DatabaseRecordKey { private String db; private String accession; /** * Construct with the database and accession * @param db database name * @param accession id in database */ public DatabaseRecordKey(String db, String accession) { this.db = db; this.accession = accession; } /** * {@inheritDoc} */ public boolean equals(Object o) { if (o instanceof DatabaseRecordKey) { DatabaseRecordKey otherKey = (DatabaseRecordKey) o; if (StringUtils.isNotEmpty(accession) && StringUtils.isNotEmpty(otherKey.accession)) { return this.db.equals(otherKey.db) && this.accession.equals(otherKey.accession); } } return false; } /** * {@inheritDoc} */ public int hashCode() { return db.hashCode() + 3 * accession.hashCode(); } } /** * ===================== * RESULT FILES * ===================== */ private void createResultFiles(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process for (Integer submissionId : submissionDataMap.keySet()) { // the applied data is repeated for each protocol // so we want to uniquefy the created object Set<String> subFiles = new HashSet<String>(); for (Integer dataId : submissionDataMap.get(submissionId)) { AppliedData ad = appliedDataMap.get(dataId); // now checking only for 'file', not 'result file' if (StringUtils.containsIgnoreCase(ad.type, "file")) { if (!StringUtils.isBlank(ad.value) && !subFiles.contains(ad.value)) { String direction = null; if (StringUtils.containsIgnoreCase(ad.type, "result")) { direction = "result"; } else { direction = "input"; } createResultFile(ad.value, ad.name, ad.url, direction, submissionId); subFiles.add(ad.value); } } } } LOG.info("TIME creating ResultFile objects: " + (System.currentTimeMillis() - bT) + " ms"); } private void createResultFile(String fileName, String type, String relDccId, String direction, Integer submissionId) throws ObjectStoreException { Item resultFile = getChadoDBConverter().createItem("ResultFile"); resultFile.setAttribute("name", unversionName(fileName)); String url = null; if (fileName.startsWith("http") || fileName.startsWith("ftp")) { url = fileName; } else { if (relDccId != null) { // the file actually belongs to a related sub url = FILE_URL + relDccId + "/extracted/" + unversionName(fileName); } else { // note: on ftp site submission directories are named with the digits only String dccId = dccIdMap.get(submissionId).substring(DCC_PREFIX.length()); url = FILE_URL + dccId + "/extracted/" + unversionName(fileName); } } resultFile.setAttribute("url", url); resultFile.setAttribute("type", type); resultFile.setAttribute("direction", direction); resultFile.setReference("submission", submissionMap.get(submissionId).itemIdentifier); getChadoDBConverter().store(resultFile); } /** * @param fileName */ private String unversionName(String fileName) { // String versionRegex = "\\.*_*[WS|ws]+\\d\\d\\d+"; String versionRegex = "\\.*_*[Ww][Ss]+\\d\\d\\d+"; LOG.debug("FFFF: " + fileName + "--->>" + "====>" + fileName.replaceAll(versionRegex, "")); return fileName.replaceAll(versionRegex, ""); } private void createRelatedSubmissions(Connection connection) throws ObjectStoreException { Map<Integer, Set<String>> relatedSubs = new HashMap<Integer, Set<String>>(); for (Map.Entry<Integer, List<SubmissionReference>> entry : submissionRefs.entrySet()) { Integer submissionId = entry.getKey(); List<SubmissionReference> lref = entry.getValue(); Iterator<SubmissionReference> i = lref.iterator(); while (i.hasNext()) { SubmissionReference ref = i.next(); addRelatedSubmissions(relatedSubs, submissionId, ref.referencedSubmissionId); addRelatedSubmissions(relatedSubs, ref.referencedSubmissionId, submissionId); } LOG.debug("RRSS11 " + relatedSubs.size() + "|" + relatedSubs.keySet() + "|" + relatedSubs.values()); } for (Map.Entry<Integer, Set<String>> entry : relatedSubs.entrySet()) { ReferenceList related = new ReferenceList("relatedSubmissions", new ArrayList<String>(entry.getValue())); getChadoDBConverter().store(related, entry.getKey()); } } private void addRelatedSubmissions(Map<Integer, Set<String>> relatedSubs, Integer subId, Integer relatedId) { Integer subIdObjectId = submissionMap.get(subId).interMineObjectId; Set<String> itemIds = relatedSubs.get(subIdObjectId); if (itemIds == null) { itemIds = new HashSet<String>(); relatedSubs.put(submissionMap.get(subId).interMineObjectId, itemIds); } itemIds.add(submissionMap.get(relatedId).itemIdentifier); } //sub -> prot private void setSubmissionProtocolsRefs(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process Map<Integer, List<Integer>> submissionProtocolMap = new HashMap<Integer, List<Integer>>(); Iterator<Integer> apId = appliedProtocolMap.keySet().iterator(); while (apId.hasNext()) { Integer thisAP = apId.next(); AppliedProtocol ap = appliedProtocolMap.get(thisAP); Util.addToListMap(submissionProtocolMap, ap.submissionId, ap.protocolId); } Iterator<Integer> subs = submissionProtocolMap.keySet().iterator(); while (subs.hasNext()) { Integer thisSubmissionId = subs.next(); List<Integer> protocolChadoIds = submissionProtocolMap.get(thisSubmissionId); ReferenceList collection = new ReferenceList(); collection.setName("protocols"); for (Integer protocolChadoId : protocolChadoIds) { collection.addRefId(protocolItemIds.get(protocolChadoId)); } Integer storedSubmissionId = submissionMap.get(thisSubmissionId).interMineObjectId; getChadoDBConverter().store(collection, storedSubmissionId); // TODO use Item? // if the experiment type is not set in the db, check protocols if (!submissionWithExpTypeSet.contains(thisSubmissionId)) { LOG.warn("EXPERIMENT TYPE NOT SET in chado for submission: " + dccIdMap.get(thisSubmissionId)); // may need protocols from referenced submissions to work out experiment type List<Integer> relatedSubsProtocolIds = new ArrayList<Integer>( findProtocolIdsFromReferencedSubmissions(thisSubmissionId)); if (relatedSubsProtocolIds != null) { protocolChadoIds.addAll(relatedSubsProtocolIds); } String piName = submissionProjectMap.get(thisSubmissionId); setSubmissionExperimentType(storedSubmissionId, protocolChadoIds, piName); } } LOG.info("TIME setting submission-protocol references: " + (System.currentTimeMillis() - bT) + " ms"); } // store Submission.experimentType if it can be inferred from protocols private void setSubmissionExperimentType(Integer storedSubId, List<Integer> protocolIds, String piName) throws ObjectStoreException { Set<String> protocolTypes = new HashSet<String>(); for (Integer protocolId : protocolIds) { protocolTypes.add(protocolTypesMap.get(protocolId).trim()); } String experimentType = inferExperimentType(protocolTypes, piName); if (experimentType != null) { Attribute expTypeAtt = new Attribute("experimentType", experimentType); getChadoDBConverter().store(expTypeAtt, storedSubId); } } // Fetch protocols used to create reagents that are inputs to this submission, these are // found in referenced submissions private List<Integer> findProtocolIdsFromReferencedSubmissions(Integer submissionId) { List<Integer> protocolIds = new ArrayList<Integer>(); if (submissionRefs == null) { throw new RuntimeException("Attempting to access submissionRefs before it has been" + " populated, this method needs to be called after" + " processSubmissionProperties"); } List<SubmissionReference> refs = submissionRefs.get(submissionId); if (refs == null) { return protocolIds; } for (SubmissionReference subRef : refs) { LOG.info("RRSSprot: " + subRef.referencedSubmissionId + "|" + subRef.dataValue); for (AppliedProtocol aProtocol : findAppliedProtocolsFromReferencedSubmission(subRef)) { LOG.info("RRSSprotId: " + aProtocol.protocolId); protocolIds.add(aProtocol.protocolId); } } return protocolIds; } /** * Work out an experiment type give the combination of protocols used for the * submission. e.g. *immunoprecipitation + hybridization = chIP-chip * @param protocolTypes the protocol types * @param piName name of PI * @return a short experiment type */ protected String inferExperimentType(Set<String> protocolTypes, String piName) { // extraction + sequencing + reverse transcription - ChIP = RTPCR // extraction + sequencing - reverse transcription - ChIP = RNA-seq if (containsMatch(protocolTypes, "nucleic_acid_extraction|RNA extraction") && containsMatch(protocolTypes, "sequencing(_protocol)?") && !containsMatch(protocolTypes, "chromatin_immunoprecipitation")) { if (containsMatch(protocolTypes, "reverse_transcription")) { return "RTPCR"; } else { return "RNA-seq"; } } // reverse transcription + PCR + RACE = RACE // reverse transcription + PCR - RACE = RTPCR if (containsMatch(protocolTypes, "reverse_transcription") && containsMatch(protocolTypes, "PCR(_amplification)?")) { if (containsMatch(protocolTypes, "RACE")) { return "RACE"; } else { return "RTPCR"; } } // ChIP + hybridization = ChIP-chip // ChIP - hybridization = ChIP-seq if (containsMatch(protocolTypes, "(.*)?immunoprecipitation")) { if (containsMatch(protocolTypes, "hybridization")) { return "ChIP-chip"; } else { return "ChIP-seq"; } } // hybridization - ChIP = // Celniker: RNA tiling array // Henikoff: Chromatin-chip // otherwise: Tiling array if (containsMatch(protocolTypes, "hybridization") && !containsMatch(protocolTypes, "immunoprecipitation")) { if ("Celniker".equals(piName)) { return "RNA tiling array"; } else if ("Henikoff".equals(piName)) { return "Chromatin-chip"; } else { return "Tiling array"; } } // annotation = Computational annotation if (containsMatch(protocolTypes, "annotation")) { return "Computational annotation"; } // If we haven't found a type yet, and there is a growth protocol, then // this is probably an RNA sample creation experiment from Celniker if (containsMatch(protocolTypes, "grow")) { return "RNA sample creation"; } return null; } // utility method for looking up in a set by regular expression private boolean containsMatch(Set<String> testSet, String regex) { boolean matches = false; Pattern p = Pattern.compile(regex); for (String test : testSet) { Matcher m = p.matcher(test); if (m.matches()) { matches = true; } } return matches; } //sub -> exp private void setSubmissionExperimentRefs(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process // the map should contain only live submissions Iterator<String> exp = expSubMap.keySet().iterator(); while (exp.hasNext()) { String thisExp = exp.next(); List<Integer> subs = expSubMap.get(thisExp); Iterator<Integer> s = subs.iterator(); while (s.hasNext()) { Integer thisSubId = s.next(); Reference reference = new Reference(); reference.setName("experiment"); reference.setRefId(experimentIdRefMap.get(thisExp)); getChadoDBConverter().store(reference, submissionMap.get(thisSubId).interMineObjectId); } } LOG.info("TIME setting submission-experiment references: " + (System.currentTimeMillis() - bT) + " ms"); } //sub -> ef private void setSubmissionEFactorsRefsNEW(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process Iterator<Integer> subs = submissionEFactorMap2.keySet().iterator(); while (subs.hasNext()) { Integer thisSubmissionId = subs.next(); List<String[]> eFactors = submissionEFactorMap2.get(thisSubmissionId); LOG.info("EF REFS: " + thisSubmissionId + " (" + eFactors.get(0) + ")"); Iterator<String[]> ef = eFactors.iterator(); ReferenceList collection = new ReferenceList(); collection.setName("experimentalFactors"); while (ef.hasNext()) { String [] thisEF = ef.next(); String efName = thisEF[0]; String efType = thisEF[1]; String key = efName + efType; collection.addRefId(eFactorIdRefMap.get(efName + efType)); LOG.info("EF REFS!!: ->" + efName + " ref: " + eFactorIdRefMap.get(key)); } if (!collection.equals(null)) { LOG.info("EF REFS: ->" + thisSubmissionId + "|" + submissionMap.get(thisSubmissionId).interMineObjectId); getChadoDBConverter().store(collection, submissionMap.get(thisSubmissionId).interMineObjectId); } } LOG.info("TIME setting submission-exFactors references: " + (System.currentTimeMillis() - bT) + " ms"); } //sub -> ef private void setSubmissionEFactorsRefs(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process Iterator<Integer> subs = submissionEFactorMap.keySet().iterator(); while (subs.hasNext()) { Integer thisSubmissionId = subs.next(); List<String> eFactors = submissionEFactorMap.get(thisSubmissionId); LOG.info("EF REFS: " + thisSubmissionId + " (" + eFactors + ")"); Iterator<String> ef = eFactors.iterator(); ReferenceList collection = new ReferenceList(); collection.setName("experimentalFactors"); while (ef.hasNext()) { String currentEF = ef.next(); collection.addRefId(eFactorIdRefMap.get(currentEF)); LOG.debug("EF REFS: ->" + currentEF + " ref: " + eFactorIdRefMap.get(currentEF)); } if (!collection.equals(null)) { LOG.info("EF REFS: ->" + thisSubmissionId + "|" + submissionMap.get(thisSubmissionId).interMineObjectId); getChadoDBConverter().store(collection, submissionMap.get(thisSubmissionId).interMineObjectId); } } LOG.info("TIME setting submission-exFactors references: " + (System.currentTimeMillis() - bT) + " ms"); } //sub -> publication private void setSubmissionPublicationRefs(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process Iterator<Integer> subs = publicationIdMap.keySet().iterator(); while (subs.hasNext()) { Integer thisSubmissionId = subs.next(); Reference reference = new Reference(); reference.setName("publication"); reference.setRefId(publicationIdRefMap.get(thisSubmissionId)); getChadoDBConverter().store(reference, submissionMap.get(thisSubmissionId).interMineObjectId); } LOG.info("TIME setting submission-publication references: " + (System.currentTimeMillis() - bT) + " ms"); } /** * to store references between applied protocols and their input data * reverse reference: data -> next appliedProtocols * and between applied protocols and their output data * reverse reference: data -> previous appliedProtocols * (many to many) */ private void setDAGRefs(Connection connection) throws ObjectStoreException { long bT = System.currentTimeMillis(); // to monitor time spent in the process for (Integer thisAP : appliedProtocolMap.keySet()) { AppliedProtocol ap = appliedProtocolMap.get(thisAP); if (!ap.inputs.isEmpty()) { ReferenceList collection = new ReferenceList("inputs"); for (Integer inputId : ap.inputs) { collection.addRefId(appliedDataMap.get(inputId).itemIdentifier); //if (collection.getRefIds().contains(null)) { // LOG.info("Applied Protocol " + thisAP + " of protocol " + ap.protocolId // + " and inputs " + ap.inputs ); // } } if (collection.getRefIds().contains(null)) { LOG.warn("Applied Protocol " + thisAP + " has only inputs not corresponding" + " to any output in previous protocol" + " and cannot be linked in the DAG."); continue; } getChadoDBConverter().store(collection, appliedProtocolIdMap.get(thisAP)); } if (!ap.outputs.isEmpty()) { ReferenceList collection = new ReferenceList("outputs"); for (Integer outputId : ap.outputs) { collection.addRefId(appliedDataMap.get(outputId).itemIdentifier); } if (collection.getRefIds().contains(null)) { LOG.warn("Applied Protocol " + thisAP + " has null AD.itemidentifiers"); continue; } getChadoDBConverter().store(collection, appliedProtocolIdMap.get(thisAP)); } } LOG.info("TIME setting DAG references: " + (System.currentTimeMillis() - bT) + " ms"); } /** * maps from chado field names to ours. * * TODO: check if up to date * * if a field is not needed it is marked with NOT_TO_BE_LOADED * a check is performed and fields unaccounted for are logged. */ private static final Map<String, String> FIELD_NAME_MAP = new HashMap<String, String>(); private static final String NOT_TO_BE_LOADED = "this is ; illegal - anyway"; static { // experiment // swapping back to uniquename in experiment table // FIELD_NAME_MAP.put("Investigation Title", "title"); FIELD_NAME_MAP.put("Investigation Title", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Project", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Project URL", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Lab", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Experiment Description", "description"); FIELD_NAME_MAP.put("Experimental Design", "design"); FIELD_NAME_MAP.put("Experimental Factor Type", "factorType"); FIELD_NAME_MAP.put("Experimental Factor Name", "factorName"); FIELD_NAME_MAP.put("Quality Control Type", "qualityControl"); FIELD_NAME_MAP.put("Replicate Type", "replicate"); FIELD_NAME_MAP.put("Date of Experiment", "experimentDate"); FIELD_NAME_MAP.put("Public Release Date", "publicReleaseDate"); FIELD_NAME_MAP.put("Embargo Date", "embargoDate"); FIELD_NAME_MAP.put("dcc_id", "DCCid"); FIELD_NAME_MAP.put("replaces", "replacesSubmission"); FIELD_NAME_MAP.put("PubMed ID", "pubMedId"); FIELD_NAME_MAP.put("Person First Name", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Person Mid Initials", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Person Last Name", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Person Affiliation", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Person Address", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Person Phone", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Person Email", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Person Roles", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Data Type", "category"); FIELD_NAME_MAP.put("Assay Type", "experimentType"); FIELD_NAME_MAP.put("Release Reservations", "notice"); FIELD_NAME_MAP.put("RNAsize", "RNAsize"); // these are names in name/value couples for ReadCount FIELD_NAME_MAP.put("Total Read Count", "totalReadCount"); FIELD_NAME_MAP.put("Total Mapped Read Count", "totalMappedReadCount"); FIELD_NAME_MAP.put("Multiply Mapped Read Count", "multiplyMappedReadCount"); FIELD_NAME_MAP.put("Uniquely Mapped Read Count", "uniquelyMappedReadCount"); // data: parameter values FIELD_NAME_MAP.put("Array Data File", "arrayDataFile"); FIELD_NAME_MAP.put("Array Design REF", "arrayDesignRef"); FIELD_NAME_MAP.put("Derived Array Data File", "derivedArrayDataFile"); FIELD_NAME_MAP.put("Result File", "resultFile"); // protocol FIELD_NAME_MAP.put("Protocol Type", "type"); FIELD_NAME_MAP.put("url protocol", "url"); FIELD_NAME_MAP.put("Characteristics", "characteristics"); FIELD_NAME_MAP.put("species", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("references", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("lab", NOT_TO_BE_LOADED); FIELD_NAME_MAP.put("Comment", NOT_TO_BE_LOADED); } /** * to store identifiers in project maps. * @param i * @param chadoId * @param intermineObjectId * @throws ObjectStoreException */ private void storeInProjectMaps(Item i, String surnamePI, Integer intermineObjectId) throws ObjectStoreException { if ("Project".equals(i.getClassName())) { projectIdMap .put(surnamePI, intermineObjectId); projectIdRefMap .put(surnamePI, i.getIdentifier()); } else { throw new IllegalArgumentException( "Type mismatch: expecting Project, getting " + i.getClassName().substring(37) + " with intermineObjectId = " + intermineObjectId + ", project = " + surnamePI); } debugMap .put(i.getIdentifier(), i.getClassName()); } /** * to store identifiers in lab maps. * @param i * @param chadoId * @param intermineObjectId * @throws ObjectStoreException */ private void storeInLabMaps(Item i, String labName, Integer intermineObjectId) throws ObjectStoreException { if ("Lab".equals(i.getClassName())) { labIdMap .put(labName, intermineObjectId); labIdRefMap .put(labName, i.getIdentifier()); } else { throw new IllegalArgumentException( "Type mismatch: expecting Lab, getting " + i.getClassName().substring(37) + " with intermineObjectId = " + intermineObjectId + ", lab = " + labName); } debugMap .put(i.getIdentifier(), i.getClassName()); } private void mapSubmissionAndData(Integer submissionId, Integer dataId) { Util.addToListMap(submissionDataMap, submissionId, dataId); dataSubmissionMap.put(dataId, submissionId); } /** * ===================== * UTILITY METHODS * ===================== */ /** * method to wrap the execution of a query, without log info * @param connection * @param query * @return the result set * @throws SQLException */ private ResultSet doQuery(Connection connection, String query) throws SQLException { Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * method to wrap the execution of a query with log info) * @param connection * @param query * @param comment for not logging * @return the result set * @throws SQLException */ private ResultSet doQuery(Connection connection, String query, String comment) throws SQLException { // we could avoid passing comment if we trace the calling method // new Throwable().fillInStackTrace().getStackTrace()[1].getMethodName() LOG.info("executing: " + query); long bT = System.currentTimeMillis(); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); LOG.info("QUERY TIME " + comment + ": " + (System.currentTimeMillis() - bT) + " ms"); return res; } /** * adds an element to a list which is the value of a map * @param m the map (<Integer, List<String>>) * @param key the key for the map * @param value the list */ private static void addToMap(Map<Integer, List<String>> m, Integer key, String value) { List<String> ids = new ArrayList<String>(); if (m.containsKey(key)) { ids = m.get(key); } if (!ids.contains(value)) { ids.add(value); m.put(key, ids); } } }
updated to the new way to call idresolver
bio/sources/chado-db/main/src/org/intermine/bio/dataconversion/ModEncodeMetaDataProcessor.java
updated to the new way to call idresolver
Java
apache-2.0
a76ea05dcb9db06e4048cf05303b1489eca71a3e
0
henrichg/PhoneProfilesPlus
package sk.henrichg.phoneprofilesplus; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager; import android.os.SystemClock; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceManager; import android.support.v4.app.NotificationCompat; import android.support.v4.content.ContextCompat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; class Event { long _id; String _name; int _startOrder; long _fkProfileStart; long _fkProfileEnd; //public boolean _undoneProfile; int _atEndDo; private int _status; String _notificationSound; boolean _notificationVibrate; boolean _repeatNotification; int _repeatNotificationInterval; boolean _forceRun; boolean _blocked; int _priority; int _delayStart; boolean _isInDelayStart; boolean _manualProfileActivation; String _startWhenActivatedProfile; int _delayEnd; boolean _isInDelayEnd; long _startStatusTime; long _pauseStatusTime; boolean _noPauseByManualActivation; EventPreferencesTime _eventPreferencesTime; EventPreferencesBattery _eventPreferencesBattery; EventPreferencesCall _eventPreferencesCall; EventPreferencesPeripherals _eventPreferencesPeripherals; EventPreferencesCalendar _eventPreferencesCalendar; EventPreferencesWifi _eventPreferencesWifi; EventPreferencesScreen _eventPreferencesScreen; EventPreferencesBluetooth _eventPreferencesBluetooth; EventPreferencesSMS _eventPreferencesSMS; EventPreferencesNotification _eventPreferencesNotification; EventPreferencesApplication _eventPreferencesApplication; EventPreferencesLocation _eventPreferencesLocation; EventPreferencesOrientation _eventPreferencesOrientation; EventPreferencesMobileCells _eventPreferencesMobileCells; EventPreferencesNFC _eventPreferencesNFC; EventPreferencesRadioSwitch _eventPreferencesRadioSwitch; EventPreferencesAlarmClock _eventPreferencesAlarmClock; static final int ESTATUS_STOP = 0; static final int ESTATUS_PAUSE = 1; static final int ESTATUS_RUNNING = 2; //static final int ESTATUS_NONE = 99; //static final int EPRIORITY_LOWEST = -5; //static final int EPRIORITY_VERY_LOW = -4; //static final int EPRIORITY_LOWER = -3; //static final int EPRIORITY_LOW = -1; //static final int EPRIORITY_LOWER_MEDIUM = -1; static final int EPRIORITY_MEDIUM = 0; //static final int EPRIORITY_UPPER_MEDIUM = 1; //static final int EPRIORITY_HIGH = 2; static final int EPRIORITY_HIGHER = 3; //static final int EPRIORITY_VERY_HIGH = 4; static final int EPRIORITY_HIGHEST = 5; static final int EATENDDO_NONE = 0; static final int EATENDDO_UNDONE_PROFILE = 1; static final int EATENDDO_RESTART_EVENTS = 2; private static final String PREF_EVENT_ID = "eventId"; static final String PREF_EVENT_ENABLED = "eventEnabled"; static final String PREF_EVENT_NAME = "eventName"; private static final String PREF_EVENT_PROFILE_START = "eventProfileStart"; private static final String PREF_EVENT_PROFILE_END = "eventProfileEnd"; static final String PREF_EVENT_NOTIFICATION_SOUND = "eventNotificationSound"; private static final String PREF_EVENT_NOTIFICATION_VIBRATE = "eventNotificationVibrate"; private static final String PREF_EVENT_NOTIFICATION_REPEAT = "eventNotificationRepeat"; private static final String PREF_EVENT_NOTIFICATION_REPEAT_INTERVAL = "eventNotificationRepeatInterval"; private static final String PREF_EVENT_FORCE_RUN = "eventForceRun"; //static final String PREF_EVENT_UNDONE_PROFILE = "eventUndoneProfile"; static final String PREF_EVENT_PRIORITY = "eventPriority"; private static final String PREF_EVENT_DELAY_START = "eventDelayStart"; private static final String PREF_EVENT_AT_END_DO = "eventAtEndDo"; private static final String PREF_EVENT_MANUAL_PROFILE_ACTIVATION = "manualProfileActivation"; private static final String PREF_EVENT_START_WHEN_ACTIVATED_PROFILE = "eventStartWhenActivatedProfile"; private static final String PREF_EVENT_DELAY_END = "eventDelayEnd"; private static final String PREF_EVENT_NO_PAUSE_BY_MANUAL_ACTIVATION = "eventNoPauseByManualActivation"; private static final String PREF_GLOBAL_EVENTS_RUN_STOP = "globalEventsRunStop"; private static final String PREF_EVENTS_BLOCKED = "eventsBlocked"; private static final String PREF_FORCE_RUN_EVENT_RUNNING = "forceRunEventRunning"; // alarm time offset (milliseconds) for events with generated alarms static final int EVENT_ALARM_TIME_OFFSET = 15000; static final int EVENT_ALARM_TIME_SOFT_OFFSET = 5000; // Empty constructor Event(){ createEventPreferences(); } // constructor Event(long id, String name, int startOrder, long fkProfileStart, long fkProfileEnd, int status, String notificationSound, boolean forceRun, boolean blocked, //boolean undoneProfile, int priority, int delayStart, boolean isInDelayStart, int atEndDo, boolean manualProfileActivation, String startWhenActivatedProfile, int delayEnd, boolean isInDelayEnd, long startStatusTime, long pauseStatusTime, boolean notificationVibrate, boolean noPauseByManualActivation, boolean repeatNotification, int repeatNotificationInterval) { this._id = id; this._name = name; this._startOrder = startOrder; this._fkProfileStart = fkProfileStart; this._fkProfileEnd = fkProfileEnd; this._status = status; this._notificationSound = notificationSound; this._notificationVibrate = notificationVibrate; this._repeatNotification = repeatNotification; this._repeatNotificationInterval = repeatNotificationInterval; this._forceRun = forceRun; this._blocked = blocked; //this._undoneProfile = undoneProfile; this._priority = priority; this._delayStart = delayStart; this._isInDelayStart = isInDelayStart; this._atEndDo = atEndDo; this._manualProfileActivation = manualProfileActivation; this._startWhenActivatedProfile = startWhenActivatedProfile; this._delayEnd = delayEnd; this._isInDelayEnd = isInDelayEnd; this._startStatusTime = startStatusTime; this._pauseStatusTime = pauseStatusTime; this._noPauseByManualActivation = noPauseByManualActivation; createEventPreferences(); } // constructor Event(String name, int startOrder, long fkProfileStart, long fkProfileEnd, int status, String notificationSound, boolean forceRun, boolean blocked, //boolean undoneProfile, int priority, int delayStart, boolean isInDelayStart, int atEndDo, boolean manualProfileActivation, String startWhenActivatedProfile, int delayEnd, boolean isInDelayEnd, long startStatusTime, long pauseStatusTime, boolean notificationVibrate, boolean noPauseByManualActivation, boolean repeatNotification, int repeatNotificationInterval) { this._name = name; this._startOrder = startOrder; this._fkProfileStart = fkProfileStart; this._fkProfileEnd = fkProfileEnd; this._status = status; this._notificationSound = notificationSound; this._notificationVibrate = notificationVibrate; this._repeatNotification = repeatNotification; this._repeatNotificationInterval = repeatNotificationInterval; this._forceRun = forceRun; this._blocked = blocked; //this._undoneProfile = undoneProfile; this._priority = priority; this._delayStart = delayStart; this._isInDelayStart = isInDelayStart; this._atEndDo = atEndDo; this._manualProfileActivation = manualProfileActivation; this._startWhenActivatedProfile = startWhenActivatedProfile; this._delayEnd = delayEnd; this._isInDelayEnd = isInDelayEnd; this._startStatusTime = startStatusTime; this._pauseStatusTime = pauseStatusTime; this._noPauseByManualActivation = noPauseByManualActivation; createEventPreferences(); } void copyEvent(Event event) { this._id = event._id; this._name = event._name; this._startOrder = event._startOrder; this._fkProfileStart = event._fkProfileStart; this._fkProfileEnd = event._fkProfileEnd; this._status = event._status; this._notificationSound = event._notificationSound; this._notificationVibrate = event._notificationVibrate; this._repeatNotification = event._repeatNotification; this._repeatNotificationInterval = event._repeatNotificationInterval; this._forceRun = event._forceRun; this._blocked = event._blocked; //this._undoneProfile = event._undoneProfile; this._priority = event._priority; this._delayStart = event._delayStart; this._isInDelayStart = event._isInDelayStart; this._atEndDo = event._atEndDo; this._manualProfileActivation = event._manualProfileActivation; this._startWhenActivatedProfile = event._startWhenActivatedProfile; this._delayEnd = event._delayEnd; this._isInDelayEnd = event._isInDelayEnd; this._startStatusTime = event._startStatusTime; this._pauseStatusTime = event._pauseStatusTime; this._noPauseByManualActivation = event._noPauseByManualActivation; copyEventPreferences(event); } private void createEventPreferencesTime() { this._eventPreferencesTime = new EventPreferencesTime(this, false, false, false, false, false, false, false, false, 0, 0/*, false*/); } private void createEventPreferencesBattery() { this._eventPreferencesBattery = new EventPreferencesBattery(this, false, 0, 100, 0, false); } private void createEventPreferencesCall() { this._eventPreferencesCall = new EventPreferencesCall(this, false, 0, "", "", 0, false, 5); } private void createEventPreferencesPeripherals() { this._eventPreferencesPeripherals = new EventPreferencesPeripherals(this, false, 0); } private void createEventPreferencesCalendar() { this._eventPreferencesCalendar = new EventPreferencesCalendar(this, false, "", false,0, "", 0, false, 0); } private void createEventPreferencesWiFi() { this._eventPreferencesWifi = new EventPreferencesWifi(this, false, "", 1); } private void createEventPreferencesScreen() { this._eventPreferencesScreen = new EventPreferencesScreen(this, false, 1, false); } private void createEventPreferencesBluetooth() { this._eventPreferencesBluetooth = new EventPreferencesBluetooth(this, false, "", 0, 0); } private void createEventPreferencesSMS() { this._eventPreferencesSMS = new EventPreferencesSMS(this, false, "", "", 0, false, 5); } private void createEventPreferencesNotification() { this._eventPreferencesNotification = new EventPreferencesNotification(this, false, "", false, false/*, false, 5, false*/); } private void createEventPreferencesApplication() { this._eventPreferencesApplication = new EventPreferencesApplication(this, false, ""); } private void createEventPreferencesLocation() { this._eventPreferencesLocation = new EventPreferencesLocation(this, false, "", false); } private void createEventPreferencesOrientation() { this._eventPreferencesOrientation = new EventPreferencesOrientation(this, false, "", "", 0, ""); } private void createEventPreferencesMobileCells() { this._eventPreferencesMobileCells = new EventPreferencesMobileCells(this, false, "", false); } private void createEventPreferencesNFC() { this._eventPreferencesNFC = new EventPreferencesNFC(this, false, "", true, 5); } private void createEventPreferencesRadioSwitch() { this._eventPreferencesRadioSwitch = new EventPreferencesRadioSwitch(this, false, 0, 0, 0, 0, 0, 0); } private void createEventPreferencesAlarmClock() { this._eventPreferencesAlarmClock = new EventPreferencesAlarmClock(this, false, false, 5); } void createEventPreferences() { createEventPreferencesTime(); createEventPreferencesBattery(); createEventPreferencesCall(); createEventPreferencesPeripherals(); createEventPreferencesCalendar(); createEventPreferencesWiFi(); createEventPreferencesScreen(); createEventPreferencesBluetooth(); createEventPreferencesSMS(); createEventPreferencesNotification(); createEventPreferencesApplication(); createEventPreferencesLocation(); createEventPreferencesOrientation(); createEventPreferencesMobileCells(); createEventPreferencesNFC(); createEventPreferencesRadioSwitch(); createEventPreferencesAlarmClock(); } void copyEventPreferences(Event fromEvent) { if (this._eventPreferencesTime == null) createEventPreferencesTime(); if (this._eventPreferencesBattery == null) createEventPreferencesBattery(); if (this._eventPreferencesCall == null) createEventPreferencesCall(); if (this._eventPreferencesPeripherals == null) createEventPreferencesPeripherals(); if (this._eventPreferencesCalendar == null) createEventPreferencesCalendar(); if (this._eventPreferencesWifi == null) createEventPreferencesWiFi(); if (this._eventPreferencesScreen == null) createEventPreferencesScreen(); if (this._eventPreferencesBluetooth == null) createEventPreferencesBluetooth(); if (this._eventPreferencesSMS == null) createEventPreferencesSMS(); if (this._eventPreferencesNotification == null) createEventPreferencesNotification(); if (this._eventPreferencesApplication == null) createEventPreferencesApplication(); if (this._eventPreferencesLocation == null) createEventPreferencesLocation(); if (this._eventPreferencesOrientation == null) createEventPreferencesOrientation(); if (this._eventPreferencesMobileCells == null) createEventPreferencesMobileCells(); if (this._eventPreferencesNFC == null) createEventPreferencesNFC(); if (this._eventPreferencesRadioSwitch == null) createEventPreferencesRadioSwitch(); if (this._eventPreferencesAlarmClock == null) createEventPreferencesAlarmClock(); this._eventPreferencesTime.copyPreferences(fromEvent); this._eventPreferencesBattery.copyPreferences(fromEvent); this._eventPreferencesCall.copyPreferences(fromEvent); this._eventPreferencesPeripherals.copyPreferences(fromEvent); this._eventPreferencesCalendar.copyPreferences(fromEvent); this._eventPreferencesWifi.copyPreferences(fromEvent); this._eventPreferencesScreen.copyPreferences(fromEvent); this._eventPreferencesBluetooth.copyPreferences(fromEvent); this._eventPreferencesSMS.copyPreferences(fromEvent); this._eventPreferencesNotification.copyPreferences(fromEvent); this._eventPreferencesApplication.copyPreferences(fromEvent); this._eventPreferencesLocation.copyPreferences(fromEvent); this._eventPreferencesOrientation.copyPreferences(fromEvent); this._eventPreferencesMobileCells.copyPreferences(fromEvent); this._eventPreferencesNFC.copyPreferences(fromEvent); this._eventPreferencesRadioSwitch.copyPreferences(fromEvent); this._eventPreferencesAlarmClock.copyPreferences(fromEvent); } public boolean isEnabledSomeSensor() { return this._eventPreferencesTime._enabled || this._eventPreferencesBattery._enabled || this._eventPreferencesCall._enabled || this._eventPreferencesPeripherals._enabled || this._eventPreferencesCalendar._enabled || this._eventPreferencesWifi._enabled || this._eventPreferencesScreen._enabled || this._eventPreferencesBluetooth._enabled || this._eventPreferencesSMS._enabled || this._eventPreferencesNotification._enabled || this._eventPreferencesApplication._enabled || this._eventPreferencesLocation._enabled || this._eventPreferencesOrientation._enabled || this._eventPreferencesMobileCells._enabled || this._eventPreferencesNFC._enabled || this._eventPreferencesRadioSwitch._enabled || this._eventPreferencesAlarmClock._enabled; } public boolean isRunnable(Context context, boolean checkSomeSensorEnabled) { boolean runnable = (this._fkProfileStart != 0); if (checkSomeSensorEnabled) if (!(this._eventPreferencesTime._enabled || this._eventPreferencesBattery._enabled || this._eventPreferencesCall._enabled || this._eventPreferencesPeripherals._enabled || this._eventPreferencesCalendar._enabled || this._eventPreferencesWifi._enabled || this._eventPreferencesScreen._enabled || this._eventPreferencesBluetooth._enabled || this._eventPreferencesSMS._enabled || this._eventPreferencesNotification._enabled || this._eventPreferencesApplication._enabled || this._eventPreferencesLocation._enabled || this._eventPreferencesOrientation._enabled || this._eventPreferencesMobileCells._enabled || this._eventPreferencesNFC._enabled || this._eventPreferencesRadioSwitch._enabled || this._eventPreferencesAlarmClock._enabled)) runnable = false; if (this._eventPreferencesTime._enabled) runnable = runnable && this._eventPreferencesTime.isRunnable(context); if (this._eventPreferencesBattery._enabled) runnable = runnable && this._eventPreferencesBattery.isRunnable(context); if (this._eventPreferencesCall._enabled) runnable = runnable && this._eventPreferencesCall.isRunnable(context); if (this._eventPreferencesPeripherals._enabled) runnable = runnable && this._eventPreferencesPeripherals.isRunnable(context); if (this._eventPreferencesCalendar._enabled) runnable = runnable && this._eventPreferencesCalendar.isRunnable(context); if (this._eventPreferencesWifi._enabled) runnable = runnable && this._eventPreferencesWifi.isRunnable(context); if (this._eventPreferencesScreen._enabled) runnable = runnable && this._eventPreferencesScreen.isRunnable(context); if (this._eventPreferencesBluetooth._enabled) runnable = runnable && this._eventPreferencesBluetooth.isRunnable(context); if (this._eventPreferencesSMS._enabled) runnable = runnable && this._eventPreferencesSMS.isRunnable(context); if (this._eventPreferencesNotification._enabled) runnable = runnable && this._eventPreferencesNotification.isRunnable(context); if (this._eventPreferencesApplication._enabled) runnable = runnable && this._eventPreferencesApplication.isRunnable(context); if (this._eventPreferencesLocation._enabled) runnable = runnable && this._eventPreferencesLocation.isRunnable(context); if (this._eventPreferencesOrientation._enabled) runnable = runnable && this._eventPreferencesOrientation.isRunnable(context); if (this._eventPreferencesMobileCells._enabled) runnable = runnable && this._eventPreferencesMobileCells.isRunnable(context); if (this._eventPreferencesNFC._enabled) runnable = runnable && this._eventPreferencesNFC.isRunnable(context); if (this._eventPreferencesRadioSwitch._enabled) runnable = runnable && this._eventPreferencesRadioSwitch.isRunnable(context); if (this._eventPreferencesAlarmClock._enabled) runnable = runnable && this._eventPreferencesAlarmClock.isRunnable(context); return runnable; } public void loadSharedPreferences(SharedPreferences preferences) { Editor editor = preferences.edit(); editor.putLong(PREF_EVENT_ID, this._id); editor.putString(PREF_EVENT_NAME, this._name); editor.putString(PREF_EVENT_PROFILE_START, Long.toString(this._fkProfileStart)); editor.putString(PREF_EVENT_PROFILE_END, Long.toString(this._fkProfileEnd)); editor.putBoolean(PREF_EVENT_ENABLED, this._status != ESTATUS_STOP); editor.putString(PREF_EVENT_NOTIFICATION_SOUND, this._notificationSound); editor.putBoolean(PREF_EVENT_NOTIFICATION_VIBRATE, this._notificationVibrate); editor.putBoolean(PREF_EVENT_NOTIFICATION_REPEAT, this._repeatNotification); editor.putString(PREF_EVENT_NOTIFICATION_REPEAT_INTERVAL, String.valueOf(this._repeatNotificationInterval)); editor.putBoolean(PREF_EVENT_FORCE_RUN, this._forceRun); //editor.putBoolean(PREF_EVENT_UNDONE_PROFILE, this._undoneProfile); editor.putString(PREF_EVENT_PRIORITY, Integer.toString(this._priority)); editor.putString(PREF_EVENT_DELAY_START, Integer.toString(this._delayStart)); editor.putString(PREF_EVENT_AT_END_DO, Integer.toString(this._atEndDo)); editor.putBoolean(PREF_EVENT_MANUAL_PROFILE_ACTIVATION, this._manualProfileActivation); editor.putString(PREF_EVENT_START_WHEN_ACTIVATED_PROFILE, this._startWhenActivatedProfile); editor.putString(PREF_EVENT_DELAY_END, Integer.toString(this._delayEnd)); editor.putBoolean(PREF_EVENT_NO_PAUSE_BY_MANUAL_ACTIVATION, this._noPauseByManualActivation); this._eventPreferencesTime.loadSharedPreferences(preferences); this._eventPreferencesBattery.loadSharedPreferences(preferences); this._eventPreferencesCall.loadSharedPreferences(preferences); this._eventPreferencesPeripherals.loadSharedPreferences(preferences); this._eventPreferencesCalendar.loadSharedPreferences(preferences); this._eventPreferencesWifi.loadSharedPreferences(preferences); this._eventPreferencesScreen.loadSharedPreferences(preferences); this._eventPreferencesBluetooth.loadSharedPreferences(preferences); this._eventPreferencesSMS.loadSharedPreferences(preferences); this._eventPreferencesNotification.loadSharedPreferences(preferences); this._eventPreferencesApplication.loadSharedPreferences(preferences); this._eventPreferencesLocation.loadSharedPreferences(preferences); this._eventPreferencesOrientation.loadSharedPreferences(preferences); this._eventPreferencesMobileCells.loadSharedPreferences(preferences); this._eventPreferencesNFC.loadSharedPreferences(preferences); this._eventPreferencesRadioSwitch.loadSharedPreferences(preferences); this._eventPreferencesAlarmClock.loadSharedPreferences(preferences); editor.apply(); } public void saveSharedPreferences(SharedPreferences preferences, Context context) { this._name = preferences.getString(PREF_EVENT_NAME, ""); this._fkProfileStart = Long.parseLong(preferences.getString(PREF_EVENT_PROFILE_START, "0")); this._fkProfileEnd = Long.parseLong(preferences.getString(PREF_EVENT_PROFILE_END, Long.toString(Profile.PROFILE_NO_ACTIVATE))); this._status = (preferences.getBoolean(PREF_EVENT_ENABLED, false)) ? ESTATUS_PAUSE : ESTATUS_STOP; this._notificationSound = preferences.getString(PREF_EVENT_NOTIFICATION_SOUND, ""); this._notificationVibrate = preferences.getBoolean(PREF_EVENT_NOTIFICATION_VIBRATE, false); this._repeatNotification = preferences.getBoolean(PREF_EVENT_NOTIFICATION_REPEAT, false); this._repeatNotificationInterval = Integer.parseInt(preferences.getString(PREF_EVENT_NOTIFICATION_REPEAT_INTERVAL, "900")); this._forceRun = preferences.getBoolean(PREF_EVENT_FORCE_RUN, false); //this._undoneProfile = preferences.getBoolean(PREF_EVENT_UNDONE_PROFILE, true); this._priority = Integer.parseInt(preferences.getString(PREF_EVENT_PRIORITY, Integer.toString(EPRIORITY_MEDIUM))); this._atEndDo = Integer.parseInt(preferences.getString(PREF_EVENT_AT_END_DO, Integer.toString(EATENDDO_RESTART_EVENTS))); this._manualProfileActivation = preferences.getBoolean(PREF_EVENT_MANUAL_PROFILE_ACTIVATION, false); this._startWhenActivatedProfile = preferences.getString(PREF_EVENT_START_WHEN_ACTIVATED_PROFILE, ""); this._noPauseByManualActivation = preferences.getBoolean(PREF_EVENT_NO_PAUSE_BY_MANUAL_ACTIVATION, false); String sDelayStart = preferences.getString(PREF_EVENT_DELAY_START, "0"); if (sDelayStart.isEmpty()) sDelayStart = "0"; int iDelayStart = Integer.parseInt(sDelayStart); if (iDelayStart < 0) iDelayStart = 0; this._delayStart = iDelayStart; String sDelayEnd = preferences.getString(PREF_EVENT_DELAY_END, "0"); if (sDelayEnd.isEmpty()) sDelayEnd = "0"; int iDelayEnd = Integer.parseInt(sDelayEnd); if (iDelayEnd < 0) iDelayEnd = 0; this._delayEnd = iDelayEnd; this._eventPreferencesTime.saveSharedPreferences(preferences); this._eventPreferencesBattery.saveSharedPreferences(preferences); this._eventPreferencesCall.saveSharedPreferences(preferences); this._eventPreferencesPeripherals.saveSharedPreferences(preferences); this._eventPreferencesCalendar.saveSharedPreferences(preferences); this._eventPreferencesWifi.saveSharedPreferences(preferences); this._eventPreferencesScreen.saveSharedPreferences(preferences); this._eventPreferencesBluetooth.saveSharedPreferences(preferences); this._eventPreferencesSMS.saveSharedPreferences(preferences); this._eventPreferencesNotification.saveSharedPreferences(preferences); this._eventPreferencesApplication.saveSharedPreferences(preferences); this._eventPreferencesLocation.saveSharedPreferences(preferences); this._eventPreferencesOrientation.saveSharedPreferences(preferences); this._eventPreferencesMobileCells.saveSharedPreferences(preferences); this._eventPreferencesNFC.saveSharedPreferences(preferences); this._eventPreferencesRadioSwitch.saveSharedPreferences(preferences); this._eventPreferencesAlarmClock.saveSharedPreferences(preferences); if (!this.isRunnable(context, true)) this._status = ESTATUS_STOP; } private void setSummary(PreferenceManager prefMng, String key, String value, Context context) { Preference pref = prefMng.findPreference(key); if (pref == null) return; if (key.equals(PREF_EVENT_NAME)) { Preference preference = prefMng.findPreference(key); if (preference != null) { preference.setSummary(value); GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, !value.isEmpty(), false, false, false); } } if (key.equals(PREF_EVENT_PROFILE_START)||key.equals(PREF_EVENT_PROFILE_END)) { ProfilePreference preference = (ProfilePreference)prefMng.findPreference(key); if (preference != null) { long lProfileId; try { lProfileId = Long.parseLong(value); } catch (Exception e) { lProfileId = 0; } preference.setSummary(lProfileId); if (key.equals(PREF_EVENT_PROFILE_START)) GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, (lProfileId != 0) && (lProfileId != Profile.PROFILE_NO_ACTIVATE), true, lProfileId == 0, false); else GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, (lProfileId != 0) && (lProfileId != Profile.PROFILE_NO_ACTIVATE), false, false, false); } } if (key.equals(PREF_EVENT_START_WHEN_ACTIVATED_PROFILE)) { ProfileMultiSelectPreference preference = (ProfileMultiSelectPreference)prefMng.findPreference(key); if (preference != null) { GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, !value.isEmpty(), false, false, false); } } if (key.equals(PREF_EVENT_NOTIFICATION_SOUND)) { Preference preference = prefMng.findPreference(key); GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, !value.isEmpty(), false, false, false); } if (key.equals(PREF_EVENT_PRIORITY)) { ListPreference listPreference = (ListPreference)prefMng.findPreference(key); if (listPreference != null) { if (ApplicationPreferences.applicationEventUsePriority(context)) { int index = listPreference.findIndexOfValue(value); CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null; listPreference.setSummary(summary); } else { listPreference.setSummary(R.string.event_preferences_priority_notUse); } listPreference.setEnabled(ApplicationPreferences.applicationEventUsePriority(context)); } } if (key.equals(PREF_EVENT_AT_END_DO)) { ListPreference listPreference = (ListPreference)prefMng.findPreference(key); if (listPreference != null) { int index = listPreference.findIndexOfValue(value); CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null; listPreference.setSummary(summary); GlobalGUIRoutines.setPreferenceTitleStyle(listPreference, true, index > 0, false, false, false); } } if (key.equals(PREF_EVENT_DELAY_START)) { Preference preference = prefMng.findPreference(key); int delay; try { delay = Integer.parseInt(value); } catch (Exception e) { delay = 0; } GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, delay > 0, false, false, false); } if (key.equals(PREF_EVENT_DELAY_END)) { Preference preference = prefMng.findPreference(key); int delay; try { delay = Integer.parseInt(value); } catch (Exception e) { delay = 0; } GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, delay > 0, false, false, false); } /* if (key.equals(PREF_EVENT_NOTIFICATION_REPEAT_INTERVAL)) { Preference preference = prefMng.findPreference(key); if (preference != null) { preference.setSummary(value); //int iValue; //try { // iValue = Integer.parseInt(value); //} catch (Exception e) { // iValue = 0; //} //GlobalGUIRoutines.setPreferenceTitleStyle(preference, iValue != 15, false, false, false); } } */ if (key.equals(PREF_EVENT_ENABLED) || key.equals(PREF_EVENT_FORCE_RUN) || key.equals(PREF_EVENT_MANUAL_PROFILE_ACTIVATION) || key.equals(PREF_EVENT_NOTIFICATION_VIBRATE) || key.equals(PREF_EVENT_NOTIFICATION_REPEAT) || key.equals(PREF_EVENT_NO_PAUSE_BY_MANUAL_ACTIVATION)) { Preference preference = prefMng.findPreference(key); GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, value.equals("true"), false, false, false); } } private void setCategorySummary(PreferenceManager prefMng, String key, SharedPreferences preferences, Context context) { if (key.isEmpty() || //key.equals(PREF_EVENT_FORCE_RUN) || key.equals(PREF_EVENT_MANUAL_PROFILE_ACTIVATION) || key.equals(PREF_EVENT_NOTIFICATION_SOUND) || key.equals(PREF_EVENT_NOTIFICATION_VIBRATE) || key.equals(PREF_EVENT_NOTIFICATION_REPEAT) || key.equals(PREF_EVENT_NOTIFICATION_REPEAT_INTERVAL) || key.equals(PREF_EVENT_DELAY_START) || key.equals(PREF_EVENT_DELAY_END) || key.equals(PREF_EVENT_START_WHEN_ACTIVATED_PROFILE)) { //boolean forceRunChanged = false; boolean manualProfileActivationChanged; boolean profileStartWhenActivatedChanged; boolean delayStartChanged; boolean delayEndChanged; boolean notificationSoundChanged; boolean notificationVibrateChanged; boolean notificationRepeatChanged; String startWhenActivatedProfile; int delayStart; int delayEnd; if (preferences == null) { //forceRunChanged = this._forceRun; manualProfileActivationChanged = this._manualProfileActivation; profileStartWhenActivatedChanged = !this._startWhenActivatedProfile.isEmpty(); startWhenActivatedProfile = this._startWhenActivatedProfile; delayStartChanged = this._delayStart != 0; delayEndChanged = this._delayEnd != 0; delayStart = this._delayStart; delayEnd = this._delayEnd; notificationSoundChanged = !this._notificationSound.isEmpty(); notificationVibrateChanged = this._notificationVibrate; notificationRepeatChanged = this._repeatNotification; } else { //forceRunChanged = preferences.getBoolean(PREF_EVENT_FORCE_RUN, false); manualProfileActivationChanged = preferences.getBoolean(PREF_EVENT_MANUAL_PROFILE_ACTIVATION, false); startWhenActivatedProfile = preferences.getString(PREF_EVENT_START_WHEN_ACTIVATED_PROFILE, ""); profileStartWhenActivatedChanged = !startWhenActivatedProfile.isEmpty(); delayStartChanged = !preferences.getString(PREF_EVENT_DELAY_START, "0").equals("0"); delayEndChanged = !preferences.getString(PREF_EVENT_DELAY_END, "0").equals("0"); delayStart = Integer.parseInt(preferences.getString(PREF_EVENT_DELAY_START, "0")); delayEnd = Integer.parseInt(preferences.getString(PREF_EVENT_DELAY_END, "0")); notificationSoundChanged = !preferences.getString(PREF_EVENT_NOTIFICATION_SOUND, "").isEmpty(); notificationVibrateChanged = preferences.getBoolean(PREF_EVENT_NOTIFICATION_VIBRATE, false); notificationRepeatChanged = preferences.getBoolean(PREF_EVENT_NOTIFICATION_REPEAT, false); } Preference preference = prefMng.findPreference("eventStartOthersCategory"); if (preference != null) { boolean bold = (//forceRunChanged || manualProfileActivationChanged || profileStartWhenActivatedChanged || delayStartChanged || notificationSoundChanged || notificationVibrateChanged || notificationRepeatChanged); GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, bold, false, false, false); if (bold) { String summary = ""; //if (forceRunChanged) // summary = summary + "[»] " + context.getString(R.string.event_preferences_ForceRun); if (manualProfileActivationChanged) { if (!summary.isEmpty()) summary = summary + " • "; summary = summary + context.getString(R.string.event_preferences_manualProfileActivation); } if (profileStartWhenActivatedChanged) { if (!summary.isEmpty()) summary = summary + " • "; summary = summary + context.getString(R.string.event_preferences_eventStartWhenActivatedProfile) + ": "; DataWrapper dataWrapper = new DataWrapper(context.getApplicationContext(), false, 0); String[] splits = startWhenActivatedProfile.split("\\|"); Profile profile; if (splits.length == 1) { profile = dataWrapper.getProfileById(Long.valueOf(startWhenActivatedProfile), false, false, false); if (profile != null) summary = summary + profile._name; } else { summary = summary + context.getString(R.string.profile_multiselect_summary_text_selected) + " " + splits.length; } } if (delayStartChanged) { if (!summary.isEmpty()) summary = summary + " • "; summary = summary + context.getString(R.string.event_preferences_delayStart) + ": "; summary = summary + GlobalGUIRoutines.getDurationString(delayStart); } if (notificationSoundChanged) { if (!summary.isEmpty()) summary = summary + " • "; summary = summary + context.getString(R.string.event_preferences_notificationSound); } if (notificationVibrateChanged) { if (!summary.isEmpty()) summary = summary + " • "; summary = summary + context.getString(R.string.event_preferences_notificationVibrate); } if (notificationRepeatChanged) { if (!summary.isEmpty()) summary = summary + " • "; summary = summary + context.getString(R.string.event_preferences_notificationRepeat); } preference.setSummary(summary); } else preference.setSummary(""); } preference = prefMng.findPreference("eventEndOthersCategory"); if (preference != null) { //boolean bold = (delayEndChanged); GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, delayEndChanged, false, false, false); if (delayEndChanged) { String summary = ""; //if (delayEndChanged) { if (!summary.isEmpty()) summary = summary + " • "; summary = summary + context.getString(R.string.event_preferences_delayStart) + ": "; summary = summary + GlobalGUIRoutines.getDurationString(delayEnd); //} preference.setSummary(summary); } else preference.setSummary(""); } } } public void setSummary(PreferenceManager prefMng, String key, SharedPreferences preferences, Context context) { if (key.equals(PREF_EVENT_NAME) || key.equals(PREF_EVENT_PROFILE_START) || key.equals(PREF_EVENT_PROFILE_END) || key.equals(PREF_EVENT_NOTIFICATION_SOUND) || key.equals(PREF_EVENT_NOTIFICATION_REPEAT_INTERVAL) || key.equals(PREF_EVENT_PRIORITY) || key.equals(PREF_EVENT_DELAY_START) || key.equals(PREF_EVENT_DELAY_END) || key.equals(PREF_EVENT_AT_END_DO) || key.equals(PREF_EVENT_START_WHEN_ACTIVATED_PROFILE)) setSummary(prefMng, key, preferences.getString(key, ""), context); if (key.equals(PREF_EVENT_ENABLED) || key.equals(PREF_EVENT_FORCE_RUN) || key.equals(PREF_EVENT_MANUAL_PROFILE_ACTIVATION) || key.equals(PREF_EVENT_NOTIFICATION_VIBRATE) || key.equals(PREF_EVENT_NOTIFICATION_REPEAT) || key.equals(PREF_EVENT_NO_PAUSE_BY_MANUAL_ACTIVATION)) { boolean value = preferences.getBoolean(key, false); setSummary(prefMng, key, Boolean.toString(value), context); } setCategorySummary(prefMng, key, preferences, context); _eventPreferencesTime.setSummary(prefMng, key, preferences, context); _eventPreferencesTime.setCategorySummary(prefMng, preferences, context); _eventPreferencesBattery.setSummary(prefMng, key, preferences, context); _eventPreferencesBattery.setCategorySummary(prefMng, preferences, context); _eventPreferencesCall.setSummary(prefMng, key, preferences, context); _eventPreferencesCall.setCategorySummary(prefMng, preferences, context); _eventPreferencesPeripherals.setSummary(prefMng, key, preferences, context); _eventPreferencesPeripherals.setCategorySummary(prefMng, preferences, context); _eventPreferencesCalendar.setSummary(prefMng, key, preferences, context); _eventPreferencesCalendar.setCategorySummary(prefMng, preferences, context); _eventPreferencesWifi.setSummary(prefMng, key, preferences, context); _eventPreferencesWifi.setCategorySummary(prefMng, preferences, context); _eventPreferencesScreen.setSummary(prefMng, key, preferences, context); _eventPreferencesScreen.setCategorySummary(prefMng, preferences, context); _eventPreferencesBluetooth.setSummary(prefMng, key, preferences, context); _eventPreferencesBluetooth.setCategorySummary(prefMng, preferences, context); _eventPreferencesSMS.setSummary(prefMng, key, preferences, context); _eventPreferencesSMS.setCategorySummary(prefMng, preferences, context); _eventPreferencesNotification.setSummary(prefMng, key, preferences, context); _eventPreferencesNotification.setCategorySummary(prefMng, preferences, context); _eventPreferencesApplication.setSummary(prefMng, key, preferences, context); _eventPreferencesApplication.setCategorySummary(prefMng, preferences, context); _eventPreferencesLocation.setSummary(prefMng, key, preferences, context); _eventPreferencesLocation.setCategorySummary(prefMng, preferences, context); _eventPreferencesOrientation.setSummary(prefMng, key, preferences, context); _eventPreferencesOrientation.setCategorySummary(prefMng, preferences, context); _eventPreferencesMobileCells.setSummary(prefMng, key, preferences, context); _eventPreferencesMobileCells.setCategorySummary(prefMng, preferences, context); _eventPreferencesNFC.setSummary(prefMng, key, preferences, context); _eventPreferencesNFC.setCategorySummary(prefMng, preferences, context); _eventPreferencesRadioSwitch.setSummary(prefMng, key, preferences, context); _eventPreferencesRadioSwitch.setCategorySummary(prefMng, preferences, context); _eventPreferencesAlarmClock.setSummary(prefMng, key, preferences, context); _eventPreferencesAlarmClock.setCategorySummary(prefMng, preferences, context); } public void setAllSummary(PreferenceManager prefMng, SharedPreferences preferences, Context context) { Preference preference = prefMng.findPreference(PREF_EVENT_FORCE_RUN); if (preference != null) preference.setTitle("[»] " + context.getString(R.string.event_preferences_ForceRun)); setSummary(prefMng, PREF_EVENT_ENABLED, preferences, context); setSummary(prefMng, PREF_EVENT_NAME, preferences, context); setSummary(prefMng, PREF_EVENT_PROFILE_START, preferences, context); setSummary(prefMng, PREF_EVENT_PROFILE_END, preferences, context); setSummary(prefMng, PREF_EVENT_NOTIFICATION_SOUND, preferences, context); setSummary(prefMng, PREF_EVENT_NOTIFICATION_VIBRATE, preferences, context); setSummary(prefMng, PREF_EVENT_NOTIFICATION_REPEAT, preferences, context); setSummary(prefMng, PREF_EVENT_NOTIFICATION_REPEAT_INTERVAL, preferences, context); setSummary(prefMng, PREF_EVENT_PRIORITY, preferences, context); setSummary(prefMng, PREF_EVENT_DELAY_START, preferences, context); setSummary(prefMng, PREF_EVENT_DELAY_END, preferences, context); setSummary(prefMng, PREF_EVENT_AT_END_DO, preferences, context); setSummary(prefMng, PREF_EVENT_START_WHEN_ACTIVATED_PROFILE, preferences, context); setSummary(prefMng, PREF_EVENT_FORCE_RUN, preferences, context); setSummary(prefMng, PREF_EVENT_MANUAL_PROFILE_ACTIVATION, preferences, context); setSummary(prefMng, PREF_EVENT_NO_PAUSE_BY_MANUAL_ACTIVATION, preferences, context); setCategorySummary(prefMng, "", preferences, context); _eventPreferencesTime.setAllSummary(prefMng, preferences, context); _eventPreferencesTime.setCategorySummary(prefMng, preferences, context); _eventPreferencesBattery.setAllSummary(prefMng, preferences, context); _eventPreferencesBattery.setCategorySummary(prefMng, preferences, context); _eventPreferencesCall.setAllSummary(prefMng, preferences, context); _eventPreferencesCall.setCategorySummary(prefMng, preferences, context); _eventPreferencesPeripherals.setAllSummary(prefMng, preferences, context); _eventPreferencesPeripherals.setCategorySummary(prefMng, preferences, context); _eventPreferencesCalendar.setAllSummary(prefMng, preferences, context); _eventPreferencesCalendar.setCategorySummary(prefMng, preferences, context); _eventPreferencesWifi.setAllSummary(prefMng, preferences, context); _eventPreferencesWifi.setCategorySummary(prefMng, preferences, context); _eventPreferencesScreen.setAllSummary(prefMng, preferences, context); _eventPreferencesScreen.setCategorySummary(prefMng, preferences, context); _eventPreferencesBluetooth.setAllSummary(prefMng, preferences, context); _eventPreferencesBluetooth.setCategorySummary(prefMng, preferences, context); _eventPreferencesSMS.setAllSummary(prefMng, preferences, context); _eventPreferencesSMS.setCategorySummary(prefMng, preferences, context); _eventPreferencesNotification.setAllSummary(prefMng, preferences, context); _eventPreferencesNotification.setCategorySummary(prefMng, preferences, context); _eventPreferencesApplication.setAllSummary(prefMng, preferences, context); _eventPreferencesApplication.setCategorySummary(prefMng, preferences, context); _eventPreferencesLocation.setAllSummary(prefMng, preferences, context); _eventPreferencesLocation.setCategorySummary(prefMng, preferences, context); _eventPreferencesOrientation.setAllSummary(prefMng, preferences, context); _eventPreferencesOrientation.setCategorySummary(prefMng, preferences, context); _eventPreferencesMobileCells.setAllSummary(prefMng, preferences, context); _eventPreferencesMobileCells.setCategorySummary(prefMng, preferences, context); _eventPreferencesNFC.setAllSummary(prefMng, preferences, context); _eventPreferencesNFC.setCategorySummary(prefMng, preferences, context); _eventPreferencesRadioSwitch.setAllSummary(prefMng, preferences, context); _eventPreferencesRadioSwitch.setCategorySummary(prefMng, preferences, context); _eventPreferencesAlarmClock.setAllSummary(prefMng, preferences, context); _eventPreferencesAlarmClock.setCategorySummary(prefMng, preferences, context); } public String getPreferencesDescription(Context context, boolean addPassStatus) { String description; description = ""; description = description + _eventPreferencesTime.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesCalendar._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesCalendar.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesBattery._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesBattery.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesCall._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesCall.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesSMS._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesSMS.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesRadioSwitch._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesRadioSwitch.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesLocation._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesLocation.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesWifi._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesWifi.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesBluetooth._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesBluetooth.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesMobileCells._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesMobileCells.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesPeripherals._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesPeripherals.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesScreen._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesScreen.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesNotification._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesNotification.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesApplication._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesApplication.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesOrientation._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesOrientation.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesNFC._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesNFC.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesAlarmClock._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesAlarmClock.getPreferencesDescription(true, addPassStatus, context); //description = description.replace(' ', '\u00A0'); return description; } public void checkPreferences(PreferenceManager prefMng, Context context) { _eventPreferencesTime.checkPreferences(prefMng, context); _eventPreferencesBattery.checkPreferences(prefMng, context); _eventPreferencesCall.checkPreferences(prefMng, context); _eventPreferencesPeripherals.checkPreferences(prefMng, context); _eventPreferencesCalendar.checkPreferences(prefMng, context); _eventPreferencesWifi.checkPreferences(prefMng, context); _eventPreferencesScreen.checkPreferences(prefMng, context); _eventPreferencesBluetooth.checkPreferences(prefMng, context); _eventPreferencesSMS.checkPreferences(prefMng, context); _eventPreferencesNotification.checkPreferences(prefMng, context); _eventPreferencesApplication.checkPreferences(prefMng, context); _eventPreferencesLocation.checkPreferences(prefMng, context); _eventPreferencesOrientation.checkPreferences(prefMng, context); _eventPreferencesMobileCells.checkPreferences(prefMng, context); _eventPreferencesNFC.checkPreferences(prefMng, context); _eventPreferencesRadioSwitch.checkPreferences(prefMng, context); _eventPreferencesAlarmClock.checkPreferences(prefMng, context); } /* private boolean canActivateReturnProfile() { return true; } */ private int getEventTimelinePosition(List<EventTimeline> eventTimelineList) { boolean exists = false; int eventPosition = -1; for (EventTimeline eventTimeline : eventTimelineList) { eventPosition++; if (eventTimeline._fkEvent == this._id) { exists = true; break; } } if (exists) return eventPosition; else return -1; } private void addEventTimeline(DataWrapper dataWrapper, List<EventTimeline> eventTimelineList/*, Profile mergedProfile*/) { EventTimeline eventTimeline = new EventTimeline(); eventTimeline._fkEvent = this._id; eventTimeline._eorder = 0; if (eventTimelineList.size() == 0) { Profile profile = dataWrapper.getActivatedProfile(false, false); if (profile != null) eventTimeline._fkProfileEndActivated = profile._id; else eventTimeline._fkProfileEndActivated = 0; } else { eventTimeline._fkProfileEndActivated = 0; EventTimeline _eventTimeline = eventTimelineList.get(eventTimelineList.size()-1); if (_eventTimeline != null) { Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); if (event != null) eventTimeline._fkProfileEndActivated = event._fkProfileStart; } } DatabaseHandler.getInstance(dataWrapper.context).addEventTimeline(eventTimeline); eventTimelineList.add(eventTimeline); } void startEvent(DataWrapper dataWrapper, List<EventTimeline> eventTimelineList, //boolean ignoreGlobalPref, //boolean interactive, boolean reactivate, //boolean log, Profile mergedProfile) { // remove delay alarm removeDelayStartAlarm(dataWrapper); // for start delay removeDelayEndAlarm(dataWrapper); // for end delay if ((!getGlobalEventsRunning(dataWrapper.context))/* && (!ignoreGlobalPref)*/) // events are globally stopped return; if (!this.isRunnable(dataWrapper.context, true)) // event is not runnable, no pause it return; if (getEventsBlocked(dataWrapper.context)) { // blocked by manual profile activation PPApplication.logE("Event.startEvent","event_id="+this._id+" events blocked"); PPApplication.logE("Event.startEvent","event_id="+this._id+" forceRun="+_forceRun); PPApplication.logE("Event.startEvent","event_id="+this._id+" blocked="+_blocked); if (!_forceRun) // event is not forceRun return; if (_blocked) // forceRun event is temporary blocked return; } // check activated profile if (!_startWhenActivatedProfile.isEmpty()) { Profile activatedProfile = dataWrapper.getActivatedProfile(false, false); if (activatedProfile != null) { boolean found = false; String[] splits = _startWhenActivatedProfile.split("\\|"); for (String split : splits) { if (activatedProfile._id == Long.valueOf(split)) { found = true; break; } } if (!found) // if activated profile is not _startWhenActivatedProfile, not start event return; } } // search for running event with higher priority for (EventTimeline eventTimeline : eventTimelineList) { Event event = dataWrapper.getEventById(eventTimeline._fkEvent); if ((event != null) && ApplicationPreferences.applicationEventUsePriority(dataWrapper.context) && (event._priority > this._priority)) // is running event with higher priority return; } if (_forceRun) setForceRunEventRunning(dataWrapper.context, true); PPApplication.logE("@@@ Event.startEvent","event_id="+this._id+"-----------------------------------"); PPApplication.logE("@@@ Event.startEvent","-- event_name="+this._name); EventTimeline eventTimeline; /////// delete duplicate from timeline boolean exists = true; while (exists) { //exists = false; int timeLineSize = eventTimelineList.size(); // test whenever event exists in timeline eventTimeline = null; int eventPosition = getEventTimelinePosition(eventTimelineList); PPApplication.logE("Event.startEvent","eventPosition="+eventPosition); if (eventPosition != -1) eventTimeline = eventTimelineList.get(eventPosition); exists = eventPosition != -1; if (exists) { // remove event from timeline eventTimelineList.remove(eventTimeline); DatabaseHandler.getInstance(dataWrapper.context).deleteEventTimeline(eventTimeline); if (eventPosition < (timeLineSize-1)) { if (eventPosition > 0) { EventTimeline _eventTimeline = eventTimelineList.get(eventPosition-1); Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); if (event != null) eventTimelineList.get(eventPosition)._fkProfileEndActivated = event._fkProfileStart; else eventTimelineList.get(eventPosition)._fkProfileEndActivated = 0; } else { eventTimelineList.get(eventPosition)._fkProfileEndActivated = eventTimeline._fkProfileEndActivated; } } } } ////////////////////////////////// addEventTimeline(dataWrapper, eventTimelineList/*, mergedProfile*/); setSystemEvent(dataWrapper.context, ESTATUS_RUNNING); int status = this._status; this._status = ESTATUS_RUNNING; DatabaseHandler.getInstance(dataWrapper.context).updateEventStatus(this); if (/*log && */(status != this._status)) { dataWrapper.addActivityLog(DatabaseHandler.ALTYPE_EVENTSTART, _name, null, null, 0); } long activatedProfileId = 0; Profile activatedProfile = dataWrapper.getActivatedProfile(false, false); if (activatedProfile != null) activatedProfileId = activatedProfile._id; if ((this._fkProfileStart != activatedProfileId) || this._manualProfileActivation || reactivate) { // no activate profile, when is already activated PPApplication.logE("Event.startEvent","event_id="+this._id+" activate profile id="+this._fkProfileStart); if (mergedProfile == null) dataWrapper.activateProfileFromEvent(this._fkProfileStart, /*interactive,*/ false, false); else { mergedProfile.mergeProfiles(this._fkProfileStart, dataWrapper, true); if (this._manualProfileActivation) { DatabaseHandler.getInstance(dataWrapper.context).saveMergedProfile(mergedProfile); dataWrapper.activateProfileFromEvent(mergedProfile._id, /*interactive,*/ true, true); mergedProfile._id = 0; } } } else { dataWrapper.updateNotificationAndWidgets(); } //return; } private void doActivateEndProfile(DataWrapper dataWrapper, int eventPosition, int timeLineSize, List<EventTimeline> eventTimelineList, EventTimeline eventTimeline, boolean activateReturnProfile, Profile mergedProfile, boolean allowRestart) { if (!(eventPosition == (timeLineSize-1))) { // event is not in end of timeline // check whether events behind have set _fkProfileEnd or _undoProfile // when true, no activate "end profile" /*for (int i = eventPosition; i < (timeLineSize-1); i++) { if (_fkProfileEnd != Event.PROFILE_END_NO_ACTIVATE) return; if (_undoneProfile) return; }*/ return; } boolean profileActivated = false; Profile activatedProfile = dataWrapper.getActivatedProfile(false, false); // activate profile only when profile not already activated //noinspection ConstantConditions if (activateReturnProfile/* && canActivateReturnProfile()*/) { long activatedProfileId = 0; if (activatedProfile != null) activatedProfileId = activatedProfile._id; // first activate _fkProfileEnd if (_fkProfileEnd != Profile.PROFILE_NO_ACTIVATE) { if (_fkProfileEnd != activatedProfileId) { PPApplication.logE("Event.pauseEvent","activate end profile"); if (mergedProfile == null) dataWrapper.activateProfileFromEvent(_fkProfileEnd, /*false,*/ false, false); else mergedProfile.mergeProfiles(_fkProfileEnd, dataWrapper, false); activatedProfileId = _fkProfileEnd; profileActivated = true; } } // second activate when undone profile is set if (_atEndDo == EATENDDO_UNDONE_PROFILE) { // when in timeline list is event, get start profile from last event in timeline list // because last event in timeline list may be changed if (eventTimelineList.size() > 0) { EventTimeline _eventTimeline = eventTimelineList.get(eventTimelineList.size() - 1); if (_eventTimeline != null) { Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); if (event != null) eventTimeline._fkProfileEndActivated = event._fkProfileStart; } } if (eventTimeline._fkProfileEndActivated != activatedProfileId) { PPApplication.logE("Event.pauseEvent","undone profile"); PPApplication.logE("Event.pauseEvent","_fkProfileEndActivated="+eventTimeline._fkProfileEndActivated); if (eventTimeline._fkProfileEndActivated != 0) { if (mergedProfile == null) dataWrapper.activateProfileFromEvent(eventTimeline._fkProfileEndActivated, /*false,*/ false, false); else mergedProfile.mergeProfiles(eventTimeline._fkProfileEndActivated, dataWrapper, false); profileActivated = true; } } } // restart events when is set if ((_atEndDo == EATENDDO_RESTART_EVENTS) && allowRestart) { PPApplication.logE("Event.pauseEvent","restart events"); dataWrapper.restartEventsWithDelay(5, true, true, DatabaseHandler.ALTYPE_UNDEFINED); profileActivated = true; } } if (!profileActivated) { dataWrapper.updateNotificationAndWidgets(); } } void pauseEvent(DataWrapper dataWrapper, List<EventTimeline> eventTimelineList, boolean activateReturnProfile, boolean ignoreGlobalPref, boolean noSetSystemEvent, //boolean log, Profile mergedProfile, boolean allowRestart) { // remove delay alarm removeDelayStartAlarm(dataWrapper); // for start delay removeDelayEndAlarm(dataWrapper); // for end delay if ((!getGlobalEventsRunning(dataWrapper.context)) && (!ignoreGlobalPref)) // events are globally stopped return; if (!this.isRunnable(dataWrapper.context, true)) // event is not runnable, no pause it return; /* if (PPApplication.getEventsBlocked(dataWrapper.context)) { // blocked by manual profile activation PPApplication.logE("Event.pauseEvent","event_id="+this._id+" events blocked"); if (!_forceRun) // event is not forceRun return; } */ // unblock event when paused dataWrapper.setEventBlocked(this, false); PPApplication.logE("@@@ Event.pauseEvent","event_id="+this._id+"-----------------------------------"); PPApplication.logE("@@@ Event.pauseEvent","-- event_name="+this._name); int timeLineSize = eventTimelineList.size(); // test whenever event exists in timeline int eventPosition = getEventTimelinePosition(eventTimelineList); PPApplication.logE("Event.pauseEvent","eventPosition="+eventPosition); boolean exists = eventPosition != -1; EventTimeline eventTimeline = null; if (exists) { // clear start event notification if (_repeatNotification) { boolean clearNotification = true; for (int i = eventTimelineList.size()-1; i > 0; i--) { EventTimeline _eventTimeline = eventTimelineList.get(i); Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); if ((event != null) && (event._repeatNotification) && (event._id != this._id)) { // not clear, notification is from another event clearNotification = false; break; } } if (clearNotification) { NotificationManager notificationManager = (NotificationManager) dataWrapper.context.getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager != null) notificationManager.cancel(PPApplication.EVENT_START_NOTIFICATION_ID); StartEventNotificationBroadcastReceiver.removeAlarm(dataWrapper.context); } } eventTimeline = eventTimelineList.get(eventPosition); // remove event from timeline eventTimelineList.remove(eventTimeline); DatabaseHandler.getInstance(dataWrapper.context).deleteEventTimeline(eventTimeline); if (eventPosition < (timeLineSize-1)) // event is not in end of timeline and no only one event in timeline { if (eventPosition > 0) // event is not in start of timeline { // get event prior deleted event EventTimeline _eventTimeline = eventTimelineList.get(eventPosition-1); Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); // set _fkProfileEndActivated for event behind deleted event with _fkProfileStart of deleted event if (event != null) eventTimelineList.get(eventPosition)._fkProfileEndActivated = event._fkProfileStart; else eventTimelineList.get(eventPosition)._fkProfileEndActivated = 0; } else // event is in start of timeline { // set _fkProfileEndActivated of first event with _fkProfileEndActivated of deleted event eventTimelineList.get(eventPosition)._fkProfileEndActivated = eventTimeline._fkProfileEndActivated; } } } if (!noSetSystemEvent) setSystemEvent(dataWrapper.context, ESTATUS_PAUSE); int status = this._status; PPApplication.logE("@@@ Event.pauseEvent","-- old status="+this._status); this._status = ESTATUS_PAUSE; PPApplication.logE("@@@ Event.pauseEvent","-- new status="+this._status); DatabaseHandler.getInstance(dataWrapper.context).updateEventStatus(this); if (/*log &&*/ (status != this._status)) { doLogForPauseEvent(dataWrapper, allowRestart); } //if (_forceRun) //{ look for forceRun events always, not only when forceRun event is paused boolean forceRunRunning = false; for (EventTimeline _eventTimeline : eventTimelineList) { Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); if ((event != null) && (event._forceRun)) { forceRunRunning = true; break; } } if (!forceRunRunning) setForceRunEventRunning(dataWrapper.context, false); //} if (exists) { doActivateEndProfile(dataWrapper, eventPosition, timeLineSize, eventTimelineList, eventTimeline, activateReturnProfile, mergedProfile, allowRestart); } //return; } void doLogForPauseEvent(DataWrapper dataWrapper, boolean allowRestart) { int alType = DatabaseHandler.ALTYPE_EVENTEND_NONE; if ((_atEndDo == EATENDDO_UNDONE_PROFILE) && (_fkProfileEnd != Profile.PROFILE_NO_ACTIVATE)) alType = DatabaseHandler.ALTYPE_EVENTEND_ACTIVATEPROFILE_UNDOPROFILE; if ((_atEndDo == EATENDDO_RESTART_EVENTS) && (_fkProfileEnd != Profile.PROFILE_NO_ACTIVATE)) { if (allowRestart) alType = DatabaseHandler.ALTYPE_EVENTEND_ACTIVATEPROFILE_RESTARTEVENTS; else alType = DatabaseHandler.ALTYPE_EVENTEND_ACTIVATEPROFILE; } else if (_atEndDo == EATENDDO_UNDONE_PROFILE) alType = DatabaseHandler.ALTYPE_EVENTEND_UNDOPROFILE; else if (_atEndDo == EATENDDO_RESTART_EVENTS) { if (allowRestart) alType = DatabaseHandler.ALTYPE_EVENTEND_RESTARTEVENTS; } else if (_fkProfileEnd != Profile.PROFILE_NO_ACTIVATE) alType = DatabaseHandler.ALTYPE_EVENTEND_ACTIVATEPROFILE; dataWrapper.addActivityLog(alType, _name, null, null, 0); } void stopEvent(DataWrapper dataWrapper, List<EventTimeline> eventTimelineList, boolean activateReturnProfile, boolean ignoreGlobalPref, boolean saveEventStatus) //boolean log) //boolean allowRestart) { // remove delay alarm removeDelayStartAlarm(dataWrapper); // for start delay removeDelayEndAlarm(dataWrapper); // for end delay if ((!getGlobalEventsRunning(dataWrapper.context)) && (!ignoreGlobalPref)) // events are globally stopped return; PPApplication.logE("@@@ Event.stopEvent","event_id="+this._id+"-----------------------------------"); PPApplication.logE("@@@ Event.stopEvent", "-- event_name=" + this._name); if (this._status != ESTATUS_STOP) { pauseEvent(dataWrapper, eventTimelineList, activateReturnProfile, ignoreGlobalPref, true, /*false,*/ null, false/*allowRestart*/); } setSystemEvent(dataWrapper.context, ESTATUS_STOP); int status = this._status; PPApplication.logE("@@@ Event.stopEvent","-- old status="+this._status); this._status = ESTATUS_STOP; PPApplication.logE("@@@ Event.stopEvent","-- new status="+this._status); if (saveEventStatus) DatabaseHandler.getInstance(dataWrapper.context).updateEventStatus(this); if (/*log &&*/ (status != this._status)) { dataWrapper.addActivityLog(DatabaseHandler.ALTYPE_EVENTSTOP, _name, null, null, 0); } //return; } public int getStatus() { return _status; } int getStatusFromDB(Context context) { return DatabaseHandler.getInstance(context).getEventStatus(this); } public void setStatus(int status) { _status = status; } private void setSystemEvent(Context context, int forStatus) { if (forStatus == ESTATUS_PAUSE) { // event paused // setup system event for next running status _eventPreferencesTime.setSystemEventForStart(context); _eventPreferencesBattery.setSystemEventForStart(context); _eventPreferencesCall.setSystemEventForStart(context); _eventPreferencesPeripherals.setSystemEventForStart(context); _eventPreferencesCalendar.setSystemEventForStart(context); _eventPreferencesWifi.setSystemEventForStart(context); _eventPreferencesScreen.setSystemEventForStart(context); _eventPreferencesBluetooth.setSystemEventForStart(context); _eventPreferencesSMS.setSystemEventForStart(context); _eventPreferencesNotification.setSystemEventForStart(context); _eventPreferencesApplication.setSystemEventForStart(context); _eventPreferencesLocation.setSystemEventForStart(context); _eventPreferencesOrientation.setSystemEventForStart(context); _eventPreferencesMobileCells.setSystemEventForStart(context); _eventPreferencesNFC.setSystemEventForStart(context); _eventPreferencesRadioSwitch.setSystemEventForStart(context); _eventPreferencesAlarmClock.setSystemEventForStart(context); } else if (forStatus == ESTATUS_RUNNING) { // event started // setup system event for pause status _eventPreferencesTime.setSystemEventForPause(context); _eventPreferencesBattery.setSystemEventForPause(context); _eventPreferencesCall.setSystemEventForPause(context); _eventPreferencesPeripherals.setSystemEventForPause(context); _eventPreferencesCalendar.setSystemEventForPause(context); _eventPreferencesWifi.setSystemEventForPause(context); _eventPreferencesScreen.setSystemEventForPause(context); _eventPreferencesBluetooth.setSystemEventForPause(context); _eventPreferencesSMS.setSystemEventForPause(context); _eventPreferencesNotification.setSystemEventForPause(context); _eventPreferencesApplication.setSystemEventForPause(context); _eventPreferencesLocation.setSystemEventForPause(context); _eventPreferencesOrientation.setSystemEventForPause(context); _eventPreferencesMobileCells.setSystemEventForPause(context); _eventPreferencesNFC.setSystemEventForPause(context); _eventPreferencesRadioSwitch.setSystemEventForPause(context); _eventPreferencesAlarmClock.setSystemEventForPause(context); } else if (forStatus == ESTATUS_STOP) { // event stopped // remove all system events _eventPreferencesTime.removeSystemEvent(context); _eventPreferencesBattery.removeSystemEvent(context); _eventPreferencesCall.removeSystemEvent(context); _eventPreferencesPeripherals.removeSystemEvent(context); _eventPreferencesCalendar.removeSystemEvent(context); _eventPreferencesWifi.removeSystemEvent(context); _eventPreferencesScreen.removeSystemEvent(context); _eventPreferencesBluetooth.removeSystemEvent(context); _eventPreferencesSMS.removeSystemEvent(context); _eventPreferencesNotification.removeSystemEvent(context); _eventPreferencesApplication.removeSystemEvent(context); _eventPreferencesLocation.removeSystemEvent(context); _eventPreferencesOrientation.removeSystemEvent(context); _eventPreferencesMobileCells.removeSystemEvent(context); _eventPreferencesNFC.removeSystemEvent(context); _eventPreferencesRadioSwitch.removeSystemEvent(context); _eventPreferencesAlarmClock.removeSystemEvent(context); } } @SuppressLint({"SimpleDateFormat", "NewApi"}) void setDelayStartAlarm(DataWrapper dataWrapper) { removeDelayStartAlarm(dataWrapper); if (!getGlobalEventsRunning(dataWrapper.context)) // events are globally stopped return; if (!this.isRunnable(dataWrapper.context, true)) // event is not runnable, no pause it return; if (getEventsBlocked(dataWrapper.context)) { // blocked by manual profile activation PPApplication.logE("Event.setDelayStartAlarm","event_id="+this._id+" events blocked"); if (!_forceRun) // event is not forceRun return; if (_blocked) // forceRun event is temporary blocked return; } PPApplication.logE("@@@ Event.setDelayStartAlarm","event_id="+this._id+"-----------------------------------"); PPApplication.logE("@@@ Event.setDelayStartAlarm","-- event_name="+this._name); PPApplication.logE("@@@ Event.setDelayStartAlarm","-- delay="+this._delayStart); if (this._delayStart > 0) { Context _context = dataWrapper.context; if (PhoneProfilesService.getInstance() != null) _context = PhoneProfilesService.getInstance(); // delay for start is > 0 // set alarm //Intent intent = new Intent(_context, EventDelayStartBroadcastReceiver.class); Intent intent = new Intent(); intent.setAction(PhoneProfilesService.ACTION_EVENT_DELAY_START_BROADCAST_RECEIVER); //intent.setClass(context, EventDelayStartBroadcastReceiver.class); //intent.putExtra(PPApplication.EXTRA_EVENT_ID, this._id); PendingIntent pendingIntent = PendingIntent.getBroadcast(_context, (int) this._id, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE); if (alarmManager != null) { if ((android.os.Build.VERSION.SDK_INT >= 21) && ApplicationPreferences.applicationUseAlarmClock(_context)) { Calendar now = Calendar.getInstance(); now.add(Calendar.SECOND, this._delayStart); long alarmTime = now.getTimeInMillis(); if (PPApplication.logEnabled()) { SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S"); String result = sdf.format(alarmTime); PPApplication.logE("Event.setDelayStartAlarm", "startTime=" + result); } Intent editorIntent = new Intent(_context, EditorProfilesActivity.class); PendingIntent infoPendingIntent = PendingIntent.getActivity(_context, 1000, editorIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(alarmTime, infoPendingIntent); alarmManager.setAlarmClock(clockInfo, pendingIntent); } else { long alarmTime = SystemClock.elapsedRealtime() + this._delayStart * 1000; if (android.os.Build.VERSION.SDK_INT >= 23) alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingIntent); else /*if (android.os.Build.VERSION.SDK_INT >= 19)*/ alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingIntent); //else // alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingIntent); } Calendar now = Calendar.getInstance(); int gmtOffset = 0; //TimeZone.getDefault().getRawOffset(); this._startStatusTime = now.getTimeInMillis() - gmtOffset; this._isInDelayStart = true; } else { this._startStatusTime = 0; this._isInDelayStart = false; } } else { this._startStatusTime = 0; this._isInDelayStart = false; } DatabaseHandler.getInstance(dataWrapper.context).updateEventInDelayStart(this); if (_isInDelayStart) { dataWrapper.addActivityLog(DatabaseHandler.ALTYPE_EVENTSTARTDELAY, _name, null, null, _delayStart); } //return; } void checkDelayStart(/*DataWrapper dataWrapper*/) { if (this._startStatusTime == 0) { this._isInDelayStart = false; return; } Calendar now = Calendar.getInstance(); int gmtOffset = 0; //TimeZone.getDefault().getRawOffset(); long nowTime = now.getTimeInMillis() - gmtOffset; now.add(Calendar.SECOND, this._delayStart); long delayTime = now.getTimeInMillis() - gmtOffset; if (nowTime > delayTime) this._isInDelayStart = false; } void removeDelayStartAlarm(DataWrapper dataWrapper) { Context _context = dataWrapper.context; if (PhoneProfilesService.getInstance() != null) _context = PhoneProfilesService.getInstance(); AlarmManager alarmManager = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE); if (alarmManager != null) { //Intent intent = new Intent(_context, EventDelayStartBroadcastReceiver.class); Intent intent = new Intent(); intent.setAction(PhoneProfilesService.ACTION_EVENT_DELAY_START_BROADCAST_RECEIVER); //intent.setClass(context, EventDelayStartBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(_context, (int) this._id, intent, PendingIntent.FLAG_NO_CREATE); if (pendingIntent != null) { PPApplication.logE("Event.removeDelayStartAlarm", "alarm found"); alarmManager.cancel(pendingIntent); pendingIntent.cancel(); } } this._isInDelayStart = false; this._startStatusTime = 0; DatabaseHandler.getInstance(dataWrapper.context).updateEventInDelayStart(this); } @SuppressLint({"SimpleDateFormat", "NewApi"}) void setDelayEndAlarm(DataWrapper dataWrapper) { removeDelayEndAlarm(dataWrapper); if (!getGlobalEventsRunning(dataWrapper.context)) // events are globally stopped return; if (!this.isRunnable(dataWrapper.context, true)) // event is not runnable, no pause it return; if (getEventsBlocked(dataWrapper.context)) { // blocked by manual profile activation PPApplication.logE("Event.setDelayEndAlarm","event_id="+this._id+" events blocked"); if (!_forceRun) // event is not forceRun return; if (_blocked) // forceRun event is temporary blocked return; } PPApplication.logE("@@@ Event.setDelayEndAlarm","event_id="+this._id+"-----------------------------------"); PPApplication.logE("@@@ Event.setDelayEndAlarm","-- event_name="+this._name); PPApplication.logE("@@@ Event.setDelayEndAlarm","-- delay="+this._delayEnd); if (this._delayEnd > 0) { Context _context = dataWrapper.context; if (PhoneProfilesService.getInstance() != null) _context = PhoneProfilesService.getInstance(); // delay for end is > 0 // set alarm //Intent intent = new Intent(_context, EventDelayEndBroadcastReceiver.class); Intent intent = new Intent(); intent.setAction(PhoneProfilesService.ACTION_EVENT_DELAY_END_BROADCAST_RECEIVER); //intent.setClass(context, EventDelayEndBroadcastReceiver.class); //intent.putExtra(PPApplication.EXTRA_EVENT_ID, this._id); PendingIntent pendingIntent = PendingIntent.getBroadcast(_context, (int) this._id, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE); if (alarmManager != null) { if ((android.os.Build.VERSION.SDK_INT >= 21) && ApplicationPreferences.applicationUseAlarmClock(_context)) { Calendar now = Calendar.getInstance(); now.add(Calendar.SECOND, this._delayEnd); long alarmTime = now.getTimeInMillis(); // + 1000 * /* 60 * */ this._delayEnd; if (PPApplication.logEnabled()) { SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S"); String result = sdf.format(alarmTime); PPApplication.logE("Event.setDelayEndAlarm", "endTime=" + result); } Intent editorIntent = new Intent(_context, EditorProfilesActivity.class); PendingIntent infoPendingIntent = PendingIntent.getActivity(_context, 1000, editorIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(alarmTime, infoPendingIntent); alarmManager.setAlarmClock(clockInfo, pendingIntent); } else { long alarmTime = SystemClock.elapsedRealtime() + this._delayEnd * 1000; if (android.os.Build.VERSION.SDK_INT >= 23) alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingIntent); else /*if (android.os.Build.VERSION.SDK_INT >= 19)*/ alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingIntent); //else // alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingIntent); } Calendar now = Calendar.getInstance(); int gmtOffset = 0; //TimeZone.getDefault().getRawOffset(); this._pauseStatusTime = now.getTimeInMillis() - gmtOffset; this._isInDelayEnd = true; } else { this._pauseStatusTime = 0; this._isInDelayEnd = false; } } else { this._pauseStatusTime = 0; this._isInDelayEnd = false; } DatabaseHandler.getInstance(dataWrapper.context).updateEventInDelayEnd(this); if (_isInDelayEnd) { dataWrapper.addActivityLog(DatabaseHandler.ALTYPE_EVENTENDDELAY, _name, null, null, _delayEnd); } //return; } void checkDelayEnd(/*DataWrapper dataWrapper*/) { //PPApplication.logE("Event.checkDelayEnd","this._pauseStatusTime="+this._pauseStatusTime); //PPApplication.logE("Event.checkDelayEnd","this._isInDelayEnd="+this._isInDelayEnd); //PPApplication.logE("Event.checkDelayEnd","this._delayEnd="+this._delayEnd); if (this._pauseStatusTime == 0) { this._isInDelayEnd = false; return; } Calendar now = Calendar.getInstance(); int gmtOffset = 0; //TimeZone.getDefault().getRawOffset(); long nowTime = now.getTimeInMillis() - gmtOffset; now.add(Calendar.SECOND, this._delayEnd); long delayTime = now.getTimeInMillis() - gmtOffset; /* SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S"); String result = sdf.format(nowTime); PPApplication.logE("Event.checkDelayEnd","nowTime="+result); result = sdf.format(this._pauseStatusTime); PPApplication.logE("Event.checkDelayEnd","pauseStatusTime="+result); result = sdf.format(delayTime); PPApplication.logE("Event.checkDelayEnd","delayTime="+result); */ if (nowTime > delayTime) this._isInDelayEnd = false; //PPApplication.logE("Event.checkDelayEnd","this._isInDelayEnd="+this._isInDelayEnd); } void removeDelayEndAlarm(DataWrapper dataWrapper) { Context _context = dataWrapper.context; if (PhoneProfilesService.getInstance() != null) _context = PhoneProfilesService.getInstance(); AlarmManager alarmManager = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE); if (alarmManager != null) { //Intent intent = new Intent(_context, EventDelayEndBroadcastReceiver.class); Intent intent = new Intent(); intent.setAction(PhoneProfilesService.ACTION_EVENT_DELAY_END_BROADCAST_RECEIVER); //intent.setClass(context, EventDelayEndBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(_context, (int) this._id, intent, PendingIntent.FLAG_NO_CREATE); if (pendingIntent != null) { PPApplication.logE("Event.removeDelayEndAlarm", "alarm found"); alarmManager.cancel(pendingIntent); pendingIntent.cancel(); } } this._isInDelayEnd = false; DatabaseHandler.getInstance(dataWrapper.context).updateEventInDelayEnd(this); } static PreferenceAllowed isEventPreferenceAllowed(String preferenceKey, Context context) { PreferenceAllowed preferenceAllowed = new PreferenceAllowed(); preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_NOT_ALLOWED; boolean checked = false; if (preferenceKey.equals(EventPreferencesWifi.PREF_EVENT_WIFI_ENABLED)) { if (PPApplication.hasSystemFeature(context, PackageManager.FEATURE_WIFI)) // device has Wifi preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_ALLOWED; else preferenceAllowed.notAllowedReason = PreferenceAllowed.PREFERENCE_NOT_ALLOWED_NO_HARDWARE; checked = true; } if (checked) return preferenceAllowed; if (preferenceKey.equals(EventPreferencesBluetooth.PREF_EVENT_BLUETOOTH_ENABLED)) { if (PPApplication.hasSystemFeature(context, PackageManager.FEATURE_BLUETOOTH)) // device has bluetooth preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_ALLOWED; else preferenceAllowed.notAllowedReason = PreferenceAllowed.PREFERENCE_NOT_ALLOWED_NO_HARDWARE; checked = true; } if (checked) return preferenceAllowed; if (preferenceKey.equals(EventPreferencesNotification.PREF_EVENT_NOTIFICATION_ENABLED)) { //if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_ALLOWED; /*else { PPApplication.notAllowedReason = PreferenceAllowed.PREFERENCE_NOT_ALLOWED_NOT_SUPPORTED_BY_SYSTEM; PPApplication.notAllowedReasonDetail = context.getString(R.string.preference_not_allowed_reason_detail_old_android); }*/ checked = true; } if (checked) return preferenceAllowed; if (preferenceKey.equals(EventPreferencesApplication.PREF_EVENT_APPLICATION_ENABLED)) { //if (AccessibilityServiceBroadcastReceiver.isExtenderInstalled(context.getApplicationContext())) preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_ALLOWED; //else // PPApplication.notAllowedReason = PPApplication.PREFERENCE_NOT_ALLOWED_NO_EXTENDER_INSTALLED; checked = true; } if (checked) return preferenceAllowed; if (preferenceKey.equals(EventPreferencesOrientation.PREF_EVENT_ORIENTATION_ENABLED)) { boolean enabled = (PhoneProfilesService.getAccelerometerSensor(context.getApplicationContext()) != null) && (PhoneProfilesService.getMagneticFieldSensor(context.getApplicationContext()) != null) && (PhoneProfilesService.getAccelerometerSensor(context.getApplicationContext()) != null); if (enabled) { //if (AccessibilityServiceBroadcastReceiver.isExtenderInstalled(context.getApplicationContext())) preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_ALLOWED; //else // PPApplication.notAllowedReason = PPApplication.PREFERENCE_NOT_ALLOWED_NO_EXTENDER_INSTALLED; } else preferenceAllowed.notAllowedReason = PreferenceAllowed.PREFERENCE_NOT_ALLOWED_NO_HARDWARE; checked = true; } if (checked) return preferenceAllowed; if (preferenceKey.equals(EventPreferencesMobileCells.PREF_EVENT_MOBILE_CELLS_ENABLED)) { if (PPApplication.hasSystemFeature(context, PackageManager.FEATURE_TELEPHONY)) // device has telephony preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_ALLOWED; else preferenceAllowed.notAllowedReason = PreferenceAllowed.PREFERENCE_NOT_ALLOWED_NO_HARDWARE; checked = true; } if (checked) return preferenceAllowed; if (preferenceKey.equals(EventPreferencesNFC.PREF_EVENT_NFC_ENABLED)) { if (PPApplication.hasSystemFeature(context, PackageManager.FEATURE_NFC)) // device has nfc preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_ALLOWED; else preferenceAllowed.notAllowedReason = PreferenceAllowed.PREFERENCE_NOT_ALLOWED_NO_HARDWARE; checked = true; } if (checked) return preferenceAllowed; preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_ALLOWED; return preferenceAllowed; } static public boolean getGlobalEventsRunning(Context context) { ApplicationPreferences.getSharedPreferences(context); return ApplicationPreferences.preferences.getBoolean(PREF_GLOBAL_EVENTS_RUN_STOP, true); } static void setGlobalEventsRunning(Context context, boolean globalEventsRunning) { ApplicationPreferences.getSharedPreferences(context); Editor editor = ApplicationPreferences.preferences.edit(); editor.putBoolean(PREF_GLOBAL_EVENTS_RUN_STOP, globalEventsRunning); editor.apply(); } static boolean getEventsBlocked(Context context) { ApplicationPreferences.getSharedPreferences(context); return ApplicationPreferences.preferences.getBoolean(PREF_EVENTS_BLOCKED, false); } static void setEventsBlocked(Context context, boolean eventsBlocked) { ApplicationPreferences.getSharedPreferences(context); Editor editor = ApplicationPreferences.preferences.edit(); editor.putBoolean(PREF_EVENTS_BLOCKED, eventsBlocked); editor.apply(); } static boolean getForceRunEventRunning(Context context) { ApplicationPreferences.getSharedPreferences(context); return ApplicationPreferences.preferences.getBoolean(PREF_FORCE_RUN_EVENT_RUNNING, false); } static void setForceRunEventRunning(Context context, boolean forceRunEventRunning) { ApplicationPreferences.getSharedPreferences(context); Editor editor = ApplicationPreferences.preferences.edit(); editor.putBoolean(PREF_FORCE_RUN_EVENT_RUNNING, forceRunEventRunning); editor.apply(); } //---------------------------------- boolean notifyEventStart(Context context) { String notificationSound = _notificationSound; boolean notificationVibrate = _notificationVibrate; if (!notificationSound.isEmpty() || notificationVibrate) { PPApplication.logE("Event.notifyEventStart", "event._id="+_id); if (_repeatNotification) { NotificationCompat.Builder mBuilder; String nTitle = context.getString(R.string.start_event_notification_title); String nText = context.getString(R.string.start_event_notification_text1); nText = nText + ": " + _name; nText = nText + ". " + context.getString(R.string.start_event_notification_text2); if (android.os.Build.VERSION.SDK_INT < 24) { nTitle = context.getString(R.string.app_name); nText = context.getString(R.string.start_event_notification_title) + ": " + nText; } PPApplication.createNotifyEventStartNotificationChannel(context); mBuilder = new NotificationCompat.Builder(context, PPApplication.NOTIFY_EVENT_START_NOTIFICATION_CHANNEL) .setColor(ContextCompat.getColor(context, R.color.primary)) .setSmallIcon(R.drawable.ic_exclamation_notify) // notification icon .setContentTitle(nTitle) // title for notification .setContentText(nText) .setStyle(new NotificationCompat.BigTextStyle().bigText(nText)) .setAutoCancel(false); // clear notification after click PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pi); mBuilder.setPriority(Notification.PRIORITY_MAX); if (android.os.Build.VERSION.SDK_INT >= 21) { mBuilder.setCategory(Notification.CATEGORY_EVENT); mBuilder.setVisibility(Notification.VISIBILITY_PUBLIC); } Intent deleteIntent = new Intent(StartEventNotificationDeletedReceiver.START_EVENT_NOTIFICATION_DELETED_ACTION); PendingIntent deletePendingIntent = PendingIntent.getBroadcast(context, 0, deleteIntent, 0); mBuilder.setDeleteIntent(deletePendingIntent); NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (mNotificationManager != null) mNotificationManager.notify(PPApplication.EVENT_START_NOTIFICATION_ID, mBuilder.build()); StartEventNotificationBroadcastReceiver.setAlarm(this, context); } if (PhoneProfilesService.getInstance() != null) PhoneProfilesService.getInstance().playNotificationSound(notificationSound, notificationVibrate); return true; } return false; } }
phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/Event.java
package sk.henrichg.phoneprofilesplus; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceManager; import android.support.v4.app.NotificationCompat; import android.support.v4.content.ContextCompat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; class Event { long _id; String _name; int _startOrder; long _fkProfileStart; long _fkProfileEnd; //public boolean _undoneProfile; int _atEndDo; private int _status; String _notificationSound; boolean _notificationVibrate; boolean _repeatNotification; int _repeatNotificationInterval; boolean _forceRun; boolean _blocked; int _priority; int _delayStart; boolean _isInDelayStart; boolean _manualProfileActivation; String _startWhenActivatedProfile; int _delayEnd; boolean _isInDelayEnd; long _startStatusTime; long _pauseStatusTime; boolean _noPauseByManualActivation; EventPreferencesTime _eventPreferencesTime; EventPreferencesBattery _eventPreferencesBattery; EventPreferencesCall _eventPreferencesCall; EventPreferencesPeripherals _eventPreferencesPeripherals; EventPreferencesCalendar _eventPreferencesCalendar; EventPreferencesWifi _eventPreferencesWifi; EventPreferencesScreen _eventPreferencesScreen; EventPreferencesBluetooth _eventPreferencesBluetooth; EventPreferencesSMS _eventPreferencesSMS; EventPreferencesNotification _eventPreferencesNotification; EventPreferencesApplication _eventPreferencesApplication; EventPreferencesLocation _eventPreferencesLocation; EventPreferencesOrientation _eventPreferencesOrientation; EventPreferencesMobileCells _eventPreferencesMobileCells; EventPreferencesNFC _eventPreferencesNFC; EventPreferencesRadioSwitch _eventPreferencesRadioSwitch; EventPreferencesAlarmClock _eventPreferencesAlarmClock; static final int ESTATUS_STOP = 0; static final int ESTATUS_PAUSE = 1; static final int ESTATUS_RUNNING = 2; //static final int ESTATUS_NONE = 99; //static final int EPRIORITY_LOWEST = -5; //static final int EPRIORITY_VERY_LOW = -4; //static final int EPRIORITY_LOWER = -3; //static final int EPRIORITY_LOW = -1; //static final int EPRIORITY_LOWER_MEDIUM = -1; static final int EPRIORITY_MEDIUM = 0; //static final int EPRIORITY_UPPER_MEDIUM = 1; //static final int EPRIORITY_HIGH = 2; static final int EPRIORITY_HIGHER = 3; //static final int EPRIORITY_VERY_HIGH = 4; static final int EPRIORITY_HIGHEST = 5; static final int EATENDDO_NONE = 0; static final int EATENDDO_UNDONE_PROFILE = 1; static final int EATENDDO_RESTART_EVENTS = 2; private static final String PREF_EVENT_ID = "eventId"; static final String PREF_EVENT_ENABLED = "eventEnabled"; static final String PREF_EVENT_NAME = "eventName"; private static final String PREF_EVENT_PROFILE_START = "eventProfileStart"; private static final String PREF_EVENT_PROFILE_END = "eventProfileEnd"; static final String PREF_EVENT_NOTIFICATION_SOUND = "eventNotificationSound"; private static final String PREF_EVENT_NOTIFICATION_VIBRATE = "eventNotificationVibrate"; private static final String PREF_EVENT_NOTIFICATION_REPEAT = "eventNotificationRepeat"; private static final String PREF_EVENT_NOTIFICATION_REPEAT_INTERVAL = "eventNotificationRepeatInterval"; private static final String PREF_EVENT_FORCE_RUN = "eventForceRun"; //static final String PREF_EVENT_UNDONE_PROFILE = "eventUndoneProfile"; static final String PREF_EVENT_PRIORITY = "eventPriority"; private static final String PREF_EVENT_DELAY_START = "eventDelayStart"; private static final String PREF_EVENT_AT_END_DO = "eventAtEndDo"; private static final String PREF_EVENT_MANUAL_PROFILE_ACTIVATION = "manualProfileActivation"; private static final String PREF_EVENT_START_WHEN_ACTIVATED_PROFILE = "eventStartWhenActivatedProfile"; private static final String PREF_EVENT_DELAY_END = "eventDelayEnd"; private static final String PREF_EVENT_NO_PAUSE_BY_MANUAL_ACTIVATION = "eventNoPauseByManualActivation"; private static final String PREF_GLOBAL_EVENTS_RUN_STOP = "globalEventsRunStop"; private static final String PREF_EVENTS_BLOCKED = "eventsBlocked"; private static final String PREF_FORCE_RUN_EVENT_RUNNING = "forceRunEventRunning"; // alarm time offset (milliseconds) for events with generated alarms static final int EVENT_ALARM_TIME_OFFSET = 15000; static final int EVENT_ALARM_TIME_SOFT_OFFSET = 5000; // Empty constructor Event(){ createEventPreferences(); } // constructor Event(long id, String name, int startOrder, long fkProfileStart, long fkProfileEnd, int status, String notificationSound, boolean forceRun, boolean blocked, //boolean undoneProfile, int priority, int delayStart, boolean isInDelayStart, int atEndDo, boolean manualProfileActivation, String startWhenActivatedProfile, int delayEnd, boolean isInDelayEnd, long startStatusTime, long pauseStatusTime, boolean notificationVibrate, boolean noPauseByManualActivation, boolean repeatNotification, int repeatNotificationInterval) { this._id = id; this._name = name; this._startOrder = startOrder; this._fkProfileStart = fkProfileStart; this._fkProfileEnd = fkProfileEnd; this._status = status; this._notificationSound = notificationSound; this._notificationVibrate = notificationVibrate; this._repeatNotification = repeatNotification; this._repeatNotificationInterval = repeatNotificationInterval; this._forceRun = forceRun; this._blocked = blocked; //this._undoneProfile = undoneProfile; this._priority = priority; this._delayStart = delayStart; this._isInDelayStart = isInDelayStart; this._atEndDo = atEndDo; this._manualProfileActivation = manualProfileActivation; this._startWhenActivatedProfile = startWhenActivatedProfile; this._delayEnd = delayEnd; this._isInDelayEnd = isInDelayEnd; this._startStatusTime = startStatusTime; this._pauseStatusTime = pauseStatusTime; this._noPauseByManualActivation = noPauseByManualActivation; createEventPreferences(); } // constructor Event(String name, int startOrder, long fkProfileStart, long fkProfileEnd, int status, String notificationSound, boolean forceRun, boolean blocked, //boolean undoneProfile, int priority, int delayStart, boolean isInDelayStart, int atEndDo, boolean manualProfileActivation, String startWhenActivatedProfile, int delayEnd, boolean isInDelayEnd, long startStatusTime, long pauseStatusTime, boolean notificationVibrate, boolean noPauseByManualActivation, boolean repeatNotification, int repeatNotificationInterval) { this._name = name; this._startOrder = startOrder; this._fkProfileStart = fkProfileStart; this._fkProfileEnd = fkProfileEnd; this._status = status; this._notificationSound = notificationSound; this._notificationVibrate = notificationVibrate; this._repeatNotification = repeatNotification; this._repeatNotificationInterval = repeatNotificationInterval; this._forceRun = forceRun; this._blocked = blocked; //this._undoneProfile = undoneProfile; this._priority = priority; this._delayStart = delayStart; this._isInDelayStart = isInDelayStart; this._atEndDo = atEndDo; this._manualProfileActivation = manualProfileActivation; this._startWhenActivatedProfile = startWhenActivatedProfile; this._delayEnd = delayEnd; this._isInDelayEnd = isInDelayEnd; this._startStatusTime = startStatusTime; this._pauseStatusTime = pauseStatusTime; this._noPauseByManualActivation = noPauseByManualActivation; createEventPreferences(); } void copyEvent(Event event) { this._id = event._id; this._name = event._name; this._startOrder = event._startOrder; this._fkProfileStart = event._fkProfileStart; this._fkProfileEnd = event._fkProfileEnd; this._status = event._status; this._notificationSound = event._notificationSound; this._notificationVibrate = event._notificationVibrate; this._repeatNotification = event._repeatNotification; this._repeatNotificationInterval = event._repeatNotificationInterval; this._forceRun = event._forceRun; this._blocked = event._blocked; //this._undoneProfile = event._undoneProfile; this._priority = event._priority; this._delayStart = event._delayStart; this._isInDelayStart = event._isInDelayStart; this._atEndDo = event._atEndDo; this._manualProfileActivation = event._manualProfileActivation; this._startWhenActivatedProfile = event._startWhenActivatedProfile; this._delayEnd = event._delayEnd; this._isInDelayEnd = event._isInDelayEnd; this._startStatusTime = event._startStatusTime; this._pauseStatusTime = event._pauseStatusTime; this._noPauseByManualActivation = event._noPauseByManualActivation; copyEventPreferences(event); } private void createEventPreferencesTime() { this._eventPreferencesTime = new EventPreferencesTime(this, false, false, false, false, false, false, false, false, 0, 0/*, false*/); } private void createEventPreferencesBattery() { this._eventPreferencesBattery = new EventPreferencesBattery(this, false, 0, 100, 0, false); } private void createEventPreferencesCall() { this._eventPreferencesCall = new EventPreferencesCall(this, false, 0, "", "", 0, false, 5); } private void createEventPreferencesPeripherals() { this._eventPreferencesPeripherals = new EventPreferencesPeripherals(this, false, 0); } private void createEventPreferencesCalendar() { this._eventPreferencesCalendar = new EventPreferencesCalendar(this, false, "", false,0, "", 0, false, 0); } private void createEventPreferencesWiFi() { this._eventPreferencesWifi = new EventPreferencesWifi(this, false, "", 1); } private void createEventPreferencesScreen() { this._eventPreferencesScreen = new EventPreferencesScreen(this, false, 1, false); } private void createEventPreferencesBluetooth() { this._eventPreferencesBluetooth = new EventPreferencesBluetooth(this, false, "", 0, 0); } private void createEventPreferencesSMS() { this._eventPreferencesSMS = new EventPreferencesSMS(this, false, "", "", 0, false, 5); } private void createEventPreferencesNotification() { this._eventPreferencesNotification = new EventPreferencesNotification(this, false, "", false, false/*, false, 5, false*/); } private void createEventPreferencesApplication() { this._eventPreferencesApplication = new EventPreferencesApplication(this, false, ""); } private void createEventPreferencesLocation() { this._eventPreferencesLocation = new EventPreferencesLocation(this, false, "", false); } private void createEventPreferencesOrientation() { this._eventPreferencesOrientation = new EventPreferencesOrientation(this, false, "", "", 0, ""); } private void createEventPreferencesMobileCells() { this._eventPreferencesMobileCells = new EventPreferencesMobileCells(this, false, "", false); } private void createEventPreferencesNFC() { this._eventPreferencesNFC = new EventPreferencesNFC(this, false, "", true, 5); } private void createEventPreferencesRadioSwitch() { this._eventPreferencesRadioSwitch = new EventPreferencesRadioSwitch(this, false, 0, 0, 0, 0, 0, 0); } private void createEventPreferencesAlarmClock() { this._eventPreferencesAlarmClock = new EventPreferencesAlarmClock(this, false, false, 5); } void createEventPreferences() { createEventPreferencesTime(); createEventPreferencesBattery(); createEventPreferencesCall(); createEventPreferencesPeripherals(); createEventPreferencesCalendar(); createEventPreferencesWiFi(); createEventPreferencesScreen(); createEventPreferencesBluetooth(); createEventPreferencesSMS(); createEventPreferencesNotification(); createEventPreferencesApplication(); createEventPreferencesLocation(); createEventPreferencesOrientation(); createEventPreferencesMobileCells(); createEventPreferencesNFC(); createEventPreferencesRadioSwitch(); createEventPreferencesAlarmClock(); } void copyEventPreferences(Event fromEvent) { if (this._eventPreferencesTime == null) createEventPreferencesTime(); if (this._eventPreferencesBattery == null) createEventPreferencesBattery(); if (this._eventPreferencesCall == null) createEventPreferencesCall(); if (this._eventPreferencesPeripherals == null) createEventPreferencesPeripherals(); if (this._eventPreferencesCalendar == null) createEventPreferencesCalendar(); if (this._eventPreferencesWifi == null) createEventPreferencesWiFi(); if (this._eventPreferencesScreen == null) createEventPreferencesScreen(); if (this._eventPreferencesBluetooth == null) createEventPreferencesBluetooth(); if (this._eventPreferencesSMS == null) createEventPreferencesSMS(); if (this._eventPreferencesNotification == null) createEventPreferencesNotification(); if (this._eventPreferencesApplication == null) createEventPreferencesApplication(); if (this._eventPreferencesLocation == null) createEventPreferencesLocation(); if (this._eventPreferencesOrientation == null) createEventPreferencesOrientation(); if (this._eventPreferencesMobileCells == null) createEventPreferencesMobileCells(); if (this._eventPreferencesNFC == null) createEventPreferencesNFC(); if (this._eventPreferencesRadioSwitch == null) createEventPreferencesRadioSwitch(); if (this._eventPreferencesAlarmClock == null) createEventPreferencesAlarmClock(); this._eventPreferencesTime.copyPreferences(fromEvent); this._eventPreferencesBattery.copyPreferences(fromEvent); this._eventPreferencesCall.copyPreferences(fromEvent); this._eventPreferencesPeripherals.copyPreferences(fromEvent); this._eventPreferencesCalendar.copyPreferences(fromEvent); this._eventPreferencesWifi.copyPreferences(fromEvent); this._eventPreferencesScreen.copyPreferences(fromEvent); this._eventPreferencesBluetooth.copyPreferences(fromEvent); this._eventPreferencesSMS.copyPreferences(fromEvent); this._eventPreferencesNotification.copyPreferences(fromEvent); this._eventPreferencesApplication.copyPreferences(fromEvent); this._eventPreferencesLocation.copyPreferences(fromEvent); this._eventPreferencesOrientation.copyPreferences(fromEvent); this._eventPreferencesMobileCells.copyPreferences(fromEvent); this._eventPreferencesNFC.copyPreferences(fromEvent); this._eventPreferencesRadioSwitch.copyPreferences(fromEvent); this._eventPreferencesAlarmClock.copyPreferences(fromEvent); } public boolean isEnabledSomeSensor() { return this._eventPreferencesTime._enabled || this._eventPreferencesBattery._enabled || this._eventPreferencesCall._enabled || this._eventPreferencesPeripherals._enabled || this._eventPreferencesCalendar._enabled || this._eventPreferencesWifi._enabled || this._eventPreferencesScreen._enabled || this._eventPreferencesBluetooth._enabled || this._eventPreferencesSMS._enabled || this._eventPreferencesNotification._enabled || this._eventPreferencesApplication._enabled || this._eventPreferencesLocation._enabled || this._eventPreferencesOrientation._enabled || this._eventPreferencesMobileCells._enabled || this._eventPreferencesNFC._enabled || this._eventPreferencesRadioSwitch._enabled || this._eventPreferencesAlarmClock._enabled; } public boolean isRunnable(Context context, boolean checkSomeSensorEnabled) { boolean runnable = (this._fkProfileStart != 0); if (checkSomeSensorEnabled) if (!(this._eventPreferencesTime._enabled || this._eventPreferencesBattery._enabled || this._eventPreferencesCall._enabled || this._eventPreferencesPeripherals._enabled || this._eventPreferencesCalendar._enabled || this._eventPreferencesWifi._enabled || this._eventPreferencesScreen._enabled || this._eventPreferencesBluetooth._enabled || this._eventPreferencesSMS._enabled || this._eventPreferencesNotification._enabled || this._eventPreferencesApplication._enabled || this._eventPreferencesLocation._enabled || this._eventPreferencesOrientation._enabled || this._eventPreferencesMobileCells._enabled || this._eventPreferencesNFC._enabled || this._eventPreferencesRadioSwitch._enabled || this._eventPreferencesAlarmClock._enabled)) runnable = false; if (this._eventPreferencesTime._enabled) runnable = runnable && this._eventPreferencesTime.isRunnable(context); if (this._eventPreferencesBattery._enabled) runnable = runnable && this._eventPreferencesBattery.isRunnable(context); if (this._eventPreferencesCall._enabled) runnable = runnable && this._eventPreferencesCall.isRunnable(context); if (this._eventPreferencesPeripherals._enabled) runnable = runnable && this._eventPreferencesPeripherals.isRunnable(context); if (this._eventPreferencesCalendar._enabled) runnable = runnable && this._eventPreferencesCalendar.isRunnable(context); if (this._eventPreferencesWifi._enabled) runnable = runnable && this._eventPreferencesWifi.isRunnable(context); if (this._eventPreferencesScreen._enabled) runnable = runnable && this._eventPreferencesScreen.isRunnable(context); if (this._eventPreferencesBluetooth._enabled) runnable = runnable && this._eventPreferencesBluetooth.isRunnable(context); if (this._eventPreferencesSMS._enabled) runnable = runnable && this._eventPreferencesSMS.isRunnable(context); if (this._eventPreferencesNotification._enabled) runnable = runnable && this._eventPreferencesNotification.isRunnable(context); if (this._eventPreferencesApplication._enabled) runnable = runnable && this._eventPreferencesApplication.isRunnable(context); if (this._eventPreferencesLocation._enabled) runnable = runnable && this._eventPreferencesLocation.isRunnable(context); if (this._eventPreferencesOrientation._enabled) runnable = runnable && this._eventPreferencesOrientation.isRunnable(context); if (this._eventPreferencesMobileCells._enabled) runnable = runnable && this._eventPreferencesMobileCells.isRunnable(context); if (this._eventPreferencesNFC._enabled) runnable = runnable && this._eventPreferencesNFC.isRunnable(context); if (this._eventPreferencesRadioSwitch._enabled) runnable = runnable && this._eventPreferencesRadioSwitch.isRunnable(context); if (this._eventPreferencesAlarmClock._enabled) runnable = runnable && this._eventPreferencesAlarmClock.isRunnable(context); return runnable; } public void loadSharedPreferences(SharedPreferences preferences) { Editor editor = preferences.edit(); editor.putLong(PREF_EVENT_ID, this._id); editor.putString(PREF_EVENT_NAME, this._name); editor.putString(PREF_EVENT_PROFILE_START, Long.toString(this._fkProfileStart)); editor.putString(PREF_EVENT_PROFILE_END, Long.toString(this._fkProfileEnd)); editor.putBoolean(PREF_EVENT_ENABLED, this._status != ESTATUS_STOP); editor.putString(PREF_EVENT_NOTIFICATION_SOUND, this._notificationSound); editor.putBoolean(PREF_EVENT_NOTIFICATION_VIBRATE, this._notificationVibrate); editor.putBoolean(PREF_EVENT_NOTIFICATION_REPEAT, this._repeatNotification); editor.putString(PREF_EVENT_NOTIFICATION_REPEAT_INTERVAL, String.valueOf(this._repeatNotificationInterval)); editor.putBoolean(PREF_EVENT_FORCE_RUN, this._forceRun); //editor.putBoolean(PREF_EVENT_UNDONE_PROFILE, this._undoneProfile); editor.putString(PREF_EVENT_PRIORITY, Integer.toString(this._priority)); editor.putString(PREF_EVENT_DELAY_START, Integer.toString(this._delayStart)); editor.putString(PREF_EVENT_AT_END_DO, Integer.toString(this._atEndDo)); editor.putBoolean(PREF_EVENT_MANUAL_PROFILE_ACTIVATION, this._manualProfileActivation); editor.putString(PREF_EVENT_START_WHEN_ACTIVATED_PROFILE, this._startWhenActivatedProfile); editor.putString(PREF_EVENT_DELAY_END, Integer.toString(this._delayEnd)); editor.putBoolean(PREF_EVENT_NO_PAUSE_BY_MANUAL_ACTIVATION, this._noPauseByManualActivation); this._eventPreferencesTime.loadSharedPreferences(preferences); this._eventPreferencesBattery.loadSharedPreferences(preferences); this._eventPreferencesCall.loadSharedPreferences(preferences); this._eventPreferencesPeripherals.loadSharedPreferences(preferences); this._eventPreferencesCalendar.loadSharedPreferences(preferences); this._eventPreferencesWifi.loadSharedPreferences(preferences); this._eventPreferencesScreen.loadSharedPreferences(preferences); this._eventPreferencesBluetooth.loadSharedPreferences(preferences); this._eventPreferencesSMS.loadSharedPreferences(preferences); this._eventPreferencesNotification.loadSharedPreferences(preferences); this._eventPreferencesApplication.loadSharedPreferences(preferences); this._eventPreferencesLocation.loadSharedPreferences(preferences); this._eventPreferencesOrientation.loadSharedPreferences(preferences); this._eventPreferencesMobileCells.loadSharedPreferences(preferences); this._eventPreferencesNFC.loadSharedPreferences(preferences); this._eventPreferencesRadioSwitch.loadSharedPreferences(preferences); this._eventPreferencesAlarmClock.loadSharedPreferences(preferences); editor.apply(); } public void saveSharedPreferences(SharedPreferences preferences, Context context) { this._name = preferences.getString(PREF_EVENT_NAME, ""); this._fkProfileStart = Long.parseLong(preferences.getString(PREF_EVENT_PROFILE_START, "0")); this._fkProfileEnd = Long.parseLong(preferences.getString(PREF_EVENT_PROFILE_END, Long.toString(Profile.PROFILE_NO_ACTIVATE))); this._status = (preferences.getBoolean(PREF_EVENT_ENABLED, false)) ? ESTATUS_PAUSE : ESTATUS_STOP; this._notificationSound = preferences.getString(PREF_EVENT_NOTIFICATION_SOUND, ""); this._notificationVibrate = preferences.getBoolean(PREF_EVENT_NOTIFICATION_VIBRATE, false); this._repeatNotification = preferences.getBoolean(PREF_EVENT_NOTIFICATION_REPEAT, false); this._repeatNotificationInterval = Integer.parseInt(preferences.getString(PREF_EVENT_NOTIFICATION_REPEAT_INTERVAL, "900")); this._forceRun = preferences.getBoolean(PREF_EVENT_FORCE_RUN, false); //this._undoneProfile = preferences.getBoolean(PREF_EVENT_UNDONE_PROFILE, true); this._priority = Integer.parseInt(preferences.getString(PREF_EVENT_PRIORITY, Integer.toString(EPRIORITY_MEDIUM))); this._atEndDo = Integer.parseInt(preferences.getString(PREF_EVENT_AT_END_DO, Integer.toString(EATENDDO_RESTART_EVENTS))); this._manualProfileActivation = preferences.getBoolean(PREF_EVENT_MANUAL_PROFILE_ACTIVATION, false); this._startWhenActivatedProfile = preferences.getString(PREF_EVENT_START_WHEN_ACTIVATED_PROFILE, ""); this._noPauseByManualActivation = preferences.getBoolean(PREF_EVENT_NO_PAUSE_BY_MANUAL_ACTIVATION, false); String sDelayStart = preferences.getString(PREF_EVENT_DELAY_START, "0"); if (sDelayStart.isEmpty()) sDelayStart = "0"; int iDelayStart = Integer.parseInt(sDelayStart); if (iDelayStart < 0) iDelayStart = 0; this._delayStart = iDelayStart; String sDelayEnd = preferences.getString(PREF_EVENT_DELAY_END, "0"); if (sDelayEnd.isEmpty()) sDelayEnd = "0"; int iDelayEnd = Integer.parseInt(sDelayEnd); if (iDelayEnd < 0) iDelayEnd = 0; this._delayEnd = iDelayEnd; this._eventPreferencesTime.saveSharedPreferences(preferences); this._eventPreferencesBattery.saveSharedPreferences(preferences); this._eventPreferencesCall.saveSharedPreferences(preferences); this._eventPreferencesPeripherals.saveSharedPreferences(preferences); this._eventPreferencesCalendar.saveSharedPreferences(preferences); this._eventPreferencesWifi.saveSharedPreferences(preferences); this._eventPreferencesScreen.saveSharedPreferences(preferences); this._eventPreferencesBluetooth.saveSharedPreferences(preferences); this._eventPreferencesSMS.saveSharedPreferences(preferences); this._eventPreferencesNotification.saveSharedPreferences(preferences); this._eventPreferencesApplication.saveSharedPreferences(preferences); this._eventPreferencesLocation.saveSharedPreferences(preferences); this._eventPreferencesOrientation.saveSharedPreferences(preferences); this._eventPreferencesMobileCells.saveSharedPreferences(preferences); this._eventPreferencesNFC.saveSharedPreferences(preferences); this._eventPreferencesRadioSwitch.saveSharedPreferences(preferences); this._eventPreferencesAlarmClock.saveSharedPreferences(preferences); if (!this.isRunnable(context, true)) this._status = ESTATUS_STOP; } private void setSummary(PreferenceManager prefMng, String key, String value, Context context) { Preference pref = prefMng.findPreference(key); if (pref == null) return; if (key.equals(PREF_EVENT_NAME)) { Preference preference = prefMng.findPreference(key); if (preference != null) { preference.setSummary(value); GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, !value.isEmpty(), false, false, false); } } if (key.equals(PREF_EVENT_PROFILE_START)||key.equals(PREF_EVENT_PROFILE_END)) { ProfilePreference preference = (ProfilePreference)prefMng.findPreference(key); if (preference != null) { long lProfileId; try { lProfileId = Long.parseLong(value); } catch (Exception e) { lProfileId = 0; } preference.setSummary(lProfileId); if (key.equals(PREF_EVENT_PROFILE_START)) GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, (lProfileId != 0) && (lProfileId != Profile.PROFILE_NO_ACTIVATE), true, lProfileId == 0, false); else GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, (lProfileId != 0) && (lProfileId != Profile.PROFILE_NO_ACTIVATE), false, false, false); } } if (key.equals(PREF_EVENT_START_WHEN_ACTIVATED_PROFILE)) { ProfileMultiSelectPreference preference = (ProfileMultiSelectPreference)prefMng.findPreference(key); if (preference != null) { GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, !value.isEmpty(), false, false, false); } } if (key.equals(PREF_EVENT_NOTIFICATION_SOUND)) { Preference preference = prefMng.findPreference(key); GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, !value.isEmpty(), false, false, false); } if (key.equals(PREF_EVENT_PRIORITY)) { ListPreference listPreference = (ListPreference)prefMng.findPreference(key); if (listPreference != null) { if (ApplicationPreferences.applicationEventUsePriority(context)) { int index = listPreference.findIndexOfValue(value); CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null; listPreference.setSummary(summary); } else { listPreference.setSummary(R.string.event_preferences_priority_notUse); } listPreference.setEnabled(ApplicationPreferences.applicationEventUsePriority(context)); } } if (key.equals(PREF_EVENT_AT_END_DO)) { ListPreference listPreference = (ListPreference)prefMng.findPreference(key); if (listPreference != null) { int index = listPreference.findIndexOfValue(value); CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null; listPreference.setSummary(summary); GlobalGUIRoutines.setPreferenceTitleStyle(listPreference, true, index > 0, false, false, false); } } if (key.equals(PREF_EVENT_DELAY_START)) { Preference preference = prefMng.findPreference(key); int delay; try { delay = Integer.parseInt(value); } catch (Exception e) { delay = 0; } GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, delay > 0, false, false, false); } if (key.equals(PREF_EVENT_DELAY_END)) { Preference preference = prefMng.findPreference(key); int delay; try { delay = Integer.parseInt(value); } catch (Exception e) { delay = 0; } GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, delay > 0, false, false, false); } /* if (key.equals(PREF_EVENT_NOTIFICATION_REPEAT_INTERVAL)) { Preference preference = prefMng.findPreference(key); if (preference != null) { preference.setSummary(value); //int iValue; //try { // iValue = Integer.parseInt(value); //} catch (Exception e) { // iValue = 0; //} //GlobalGUIRoutines.setPreferenceTitleStyle(preference, iValue != 15, false, false, false); } } */ if (key.equals(PREF_EVENT_ENABLED) || key.equals(PREF_EVENT_FORCE_RUN) || key.equals(PREF_EVENT_MANUAL_PROFILE_ACTIVATION) || key.equals(PREF_EVENT_NOTIFICATION_VIBRATE) || key.equals(PREF_EVENT_NOTIFICATION_REPEAT) || key.equals(PREF_EVENT_NO_PAUSE_BY_MANUAL_ACTIVATION)) { Preference preference = prefMng.findPreference(key); GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, value.equals("true"), false, false, false); } } private void setCategorySummary(PreferenceManager prefMng, String key, SharedPreferences preferences, Context context) { if (key.isEmpty() || //key.equals(PREF_EVENT_FORCE_RUN) || key.equals(PREF_EVENT_MANUAL_PROFILE_ACTIVATION) || key.equals(PREF_EVENT_NOTIFICATION_SOUND) || key.equals(PREF_EVENT_NOTIFICATION_VIBRATE) || key.equals(PREF_EVENT_NOTIFICATION_REPEAT) || key.equals(PREF_EVENT_NOTIFICATION_REPEAT_INTERVAL) || key.equals(PREF_EVENT_DELAY_START) || key.equals(PREF_EVENT_DELAY_END) || key.equals(PREF_EVENT_START_WHEN_ACTIVATED_PROFILE)) { //boolean forceRunChanged = false; boolean manualProfileActivationChanged; boolean profileStartWhenActivatedChanged; boolean delayStartChanged; boolean delayEndChanged; boolean notificationSoundChanged; boolean notificationVibrateChanged; boolean notificationRepeatChanged; String startWhenActivatedProfile; int delayStart; int delayEnd; if (preferences == null) { //forceRunChanged = this._forceRun; manualProfileActivationChanged = this._manualProfileActivation; profileStartWhenActivatedChanged = !this._startWhenActivatedProfile.isEmpty(); startWhenActivatedProfile = this._startWhenActivatedProfile; delayStartChanged = this._delayStart != 0; delayEndChanged = this._delayEnd != 0; delayStart = this._delayStart; delayEnd = this._delayEnd; notificationSoundChanged = !this._notificationSound.isEmpty(); notificationVibrateChanged = this._notificationVibrate; notificationRepeatChanged = this._repeatNotification; } else { //forceRunChanged = preferences.getBoolean(PREF_EVENT_FORCE_RUN, false); manualProfileActivationChanged = preferences.getBoolean(PREF_EVENT_MANUAL_PROFILE_ACTIVATION, false); startWhenActivatedProfile = preferences.getString(PREF_EVENT_START_WHEN_ACTIVATED_PROFILE, ""); profileStartWhenActivatedChanged = !startWhenActivatedProfile.isEmpty(); delayStartChanged = !preferences.getString(PREF_EVENT_DELAY_START, "0").equals("0"); delayEndChanged = !preferences.getString(PREF_EVENT_DELAY_END, "0").equals("0"); delayStart = Integer.parseInt(preferences.getString(PREF_EVENT_DELAY_START, "0")); delayEnd = Integer.parseInt(preferences.getString(PREF_EVENT_DELAY_END, "0")); notificationSoundChanged = !preferences.getString(PREF_EVENT_NOTIFICATION_SOUND, "").isEmpty(); notificationVibrateChanged = preferences.getBoolean(PREF_EVENT_NOTIFICATION_VIBRATE, false); notificationRepeatChanged = preferences.getBoolean(PREF_EVENT_NOTIFICATION_REPEAT, false); } Preference preference = prefMng.findPreference("eventStartOthersCategory"); if (preference != null) { boolean bold = (//forceRunChanged || manualProfileActivationChanged || profileStartWhenActivatedChanged || delayStartChanged || notificationSoundChanged || notificationVibrateChanged || notificationRepeatChanged); GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, bold, false, false, false); if (bold) { String summary = ""; //if (forceRunChanged) // summary = summary + "[»] " + context.getString(R.string.event_preferences_ForceRun); if (manualProfileActivationChanged) { if (!summary.isEmpty()) summary = summary + " • "; summary = summary + context.getString(R.string.event_preferences_manualProfileActivation); } if (profileStartWhenActivatedChanged) { if (!summary.isEmpty()) summary = summary + " • "; summary = summary + context.getString(R.string.event_preferences_eventStartWhenActivatedProfile) + ": "; DataWrapper dataWrapper = new DataWrapper(context.getApplicationContext(), false, 0); String[] splits = startWhenActivatedProfile.split("\\|"); Profile profile; if (splits.length == 1) { profile = dataWrapper.getProfileById(Long.valueOf(startWhenActivatedProfile), false, false, false); if (profile != null) summary = summary + profile._name; } else { summary = summary + context.getString(R.string.profile_multiselect_summary_text_selected) + " " + splits.length; } } if (delayStartChanged) { if (!summary.isEmpty()) summary = summary + " • "; summary = summary + context.getString(R.string.event_preferences_delayStart) + ": "; summary = summary + GlobalGUIRoutines.getDurationString(delayStart); } if (notificationSoundChanged) { if (!summary.isEmpty()) summary = summary + " • "; summary = summary + context.getString(R.string.event_preferences_notificationSound); } if (notificationVibrateChanged) { if (!summary.isEmpty()) summary = summary + " • "; summary = summary + context.getString(R.string.event_preferences_notificationVibrate); } if (notificationRepeatChanged) { if (!summary.isEmpty()) summary = summary + " • "; summary = summary + context.getString(R.string.event_preferences_notificationRepeat); } preference.setSummary(summary); } else preference.setSummary(""); } preference = prefMng.findPreference("eventEndOthersCategory"); if (preference != null) { //boolean bold = (delayEndChanged); GlobalGUIRoutines.setPreferenceTitleStyle(preference, true, delayEndChanged, false, false, false); if (delayEndChanged) { String summary = ""; //if (delayEndChanged) { if (!summary.isEmpty()) summary = summary + " • "; summary = summary + context.getString(R.string.event_preferences_delayStart) + ": "; summary = summary + GlobalGUIRoutines.getDurationString(delayEnd); //} preference.setSummary(summary); } else preference.setSummary(""); } } } public void setSummary(PreferenceManager prefMng, String key, SharedPreferences preferences, Context context) { if (key.equals(PREF_EVENT_NAME) || key.equals(PREF_EVENT_PROFILE_START) || key.equals(PREF_EVENT_PROFILE_END) || key.equals(PREF_EVENT_NOTIFICATION_SOUND) || key.equals(PREF_EVENT_NOTIFICATION_REPEAT_INTERVAL) || key.equals(PREF_EVENT_PRIORITY) || key.equals(PREF_EVENT_DELAY_START) || key.equals(PREF_EVENT_DELAY_END) || key.equals(PREF_EVENT_AT_END_DO) || key.equals(PREF_EVENT_START_WHEN_ACTIVATED_PROFILE)) setSummary(prefMng, key, preferences.getString(key, ""), context); if (key.equals(PREF_EVENT_ENABLED) || key.equals(PREF_EVENT_FORCE_RUN) || key.equals(PREF_EVENT_MANUAL_PROFILE_ACTIVATION) || key.equals(PREF_EVENT_NOTIFICATION_VIBRATE) || key.equals(PREF_EVENT_NOTIFICATION_REPEAT) || key.equals(PREF_EVENT_NO_PAUSE_BY_MANUAL_ACTIVATION)) { boolean value = preferences.getBoolean(key, false); setSummary(prefMng, key, Boolean.toString(value), context); } setCategorySummary(prefMng, key, preferences, context); _eventPreferencesTime.setSummary(prefMng, key, preferences, context); _eventPreferencesTime.setCategorySummary(prefMng, preferences, context); _eventPreferencesBattery.setSummary(prefMng, key, preferences, context); _eventPreferencesBattery.setCategorySummary(prefMng, preferences, context); _eventPreferencesCall.setSummary(prefMng, key, preferences, context); _eventPreferencesCall.setCategorySummary(prefMng, preferences, context); _eventPreferencesPeripherals.setSummary(prefMng, key, preferences, context); _eventPreferencesPeripherals.setCategorySummary(prefMng, preferences, context); _eventPreferencesCalendar.setSummary(prefMng, key, preferences, context); _eventPreferencesCalendar.setCategorySummary(prefMng, preferences, context); _eventPreferencesWifi.setSummary(prefMng, key, preferences, context); _eventPreferencesWifi.setCategorySummary(prefMng, preferences, context); _eventPreferencesScreen.setSummary(prefMng, key, preferences, context); _eventPreferencesScreen.setCategorySummary(prefMng, preferences, context); _eventPreferencesBluetooth.setSummary(prefMng, key, preferences, context); _eventPreferencesBluetooth.setCategorySummary(prefMng, preferences, context); _eventPreferencesSMS.setSummary(prefMng, key, preferences, context); _eventPreferencesSMS.setCategorySummary(prefMng, preferences, context); _eventPreferencesNotification.setSummary(prefMng, key, preferences, context); _eventPreferencesNotification.setCategorySummary(prefMng, preferences, context); _eventPreferencesApplication.setSummary(prefMng, key, preferences, context); _eventPreferencesApplication.setCategorySummary(prefMng, preferences, context); _eventPreferencesLocation.setSummary(prefMng, key, preferences, context); _eventPreferencesLocation.setCategorySummary(prefMng, preferences, context); _eventPreferencesOrientation.setSummary(prefMng, key, preferences, context); _eventPreferencesOrientation.setCategorySummary(prefMng, preferences, context); _eventPreferencesMobileCells.setSummary(prefMng, key, preferences, context); _eventPreferencesMobileCells.setCategorySummary(prefMng, preferences, context); _eventPreferencesNFC.setSummary(prefMng, key, preferences, context); _eventPreferencesNFC.setCategorySummary(prefMng, preferences, context); _eventPreferencesRadioSwitch.setSummary(prefMng, key, preferences, context); _eventPreferencesRadioSwitch.setCategorySummary(prefMng, preferences, context); _eventPreferencesAlarmClock.setSummary(prefMng, key, preferences, context); _eventPreferencesAlarmClock.setCategorySummary(prefMng, preferences, context); } public void setAllSummary(PreferenceManager prefMng, SharedPreferences preferences, Context context) { Preference preference = prefMng.findPreference(PREF_EVENT_FORCE_RUN); if (preference != null) preference.setTitle("[»] " + context.getString(R.string.event_preferences_ForceRun)); setSummary(prefMng, PREF_EVENT_ENABLED, preferences, context); setSummary(prefMng, PREF_EVENT_NAME, preferences, context); setSummary(prefMng, PREF_EVENT_PROFILE_START, preferences, context); setSummary(prefMng, PREF_EVENT_PROFILE_END, preferences, context); setSummary(prefMng, PREF_EVENT_NOTIFICATION_SOUND, preferences, context); setSummary(prefMng, PREF_EVENT_NOTIFICATION_VIBRATE, preferences, context); setSummary(prefMng, PREF_EVENT_NOTIFICATION_REPEAT, preferences, context); setSummary(prefMng, PREF_EVENT_NOTIFICATION_REPEAT_INTERVAL, preferences, context); setSummary(prefMng, PREF_EVENT_PRIORITY, preferences, context); setSummary(prefMng, PREF_EVENT_DELAY_START, preferences, context); setSummary(prefMng, PREF_EVENT_DELAY_END, preferences, context); setSummary(prefMng, PREF_EVENT_AT_END_DO, preferences, context); setSummary(prefMng, PREF_EVENT_START_WHEN_ACTIVATED_PROFILE, preferences, context); setSummary(prefMng, PREF_EVENT_FORCE_RUN, preferences, context); setSummary(prefMng, PREF_EVENT_MANUAL_PROFILE_ACTIVATION, preferences, context); setSummary(prefMng, PREF_EVENT_NO_PAUSE_BY_MANUAL_ACTIVATION, preferences, context); setCategorySummary(prefMng, "", preferences, context); _eventPreferencesTime.setAllSummary(prefMng, preferences, context); _eventPreferencesTime.setCategorySummary(prefMng, preferences, context); _eventPreferencesBattery.setAllSummary(prefMng, preferences, context); _eventPreferencesBattery.setCategorySummary(prefMng, preferences, context); _eventPreferencesCall.setAllSummary(prefMng, preferences, context); _eventPreferencesCall.setCategorySummary(prefMng, preferences, context); _eventPreferencesPeripherals.setAllSummary(prefMng, preferences, context); _eventPreferencesPeripherals.setCategorySummary(prefMng, preferences, context); _eventPreferencesCalendar.setAllSummary(prefMng, preferences, context); _eventPreferencesCalendar.setCategorySummary(prefMng, preferences, context); _eventPreferencesWifi.setAllSummary(prefMng, preferences, context); _eventPreferencesWifi.setCategorySummary(prefMng, preferences, context); _eventPreferencesScreen.setAllSummary(prefMng, preferences, context); _eventPreferencesScreen.setCategorySummary(prefMng, preferences, context); _eventPreferencesBluetooth.setAllSummary(prefMng, preferences, context); _eventPreferencesBluetooth.setCategorySummary(prefMng, preferences, context); _eventPreferencesSMS.setAllSummary(prefMng, preferences, context); _eventPreferencesSMS.setCategorySummary(prefMng, preferences, context); _eventPreferencesNotification.setAllSummary(prefMng, preferences, context); _eventPreferencesNotification.setCategorySummary(prefMng, preferences, context); _eventPreferencesApplication.setAllSummary(prefMng, preferences, context); _eventPreferencesApplication.setCategorySummary(prefMng, preferences, context); _eventPreferencesLocation.setAllSummary(prefMng, preferences, context); _eventPreferencesLocation.setCategorySummary(prefMng, preferences, context); _eventPreferencesOrientation.setAllSummary(prefMng, preferences, context); _eventPreferencesOrientation.setCategorySummary(prefMng, preferences, context); _eventPreferencesMobileCells.setAllSummary(prefMng, preferences, context); _eventPreferencesMobileCells.setCategorySummary(prefMng, preferences, context); _eventPreferencesNFC.setAllSummary(prefMng, preferences, context); _eventPreferencesNFC.setCategorySummary(prefMng, preferences, context); _eventPreferencesRadioSwitch.setAllSummary(prefMng, preferences, context); _eventPreferencesRadioSwitch.setCategorySummary(prefMng, preferences, context); _eventPreferencesAlarmClock.setAllSummary(prefMng, preferences, context); _eventPreferencesAlarmClock.setCategorySummary(prefMng, preferences, context); } public String getPreferencesDescription(Context context, boolean addPassStatus) { String description; description = ""; description = description + _eventPreferencesTime.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesCalendar._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesCalendar.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesBattery._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesBattery.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesCall._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesCall.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesSMS._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesSMS.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesRadioSwitch._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesRadioSwitch.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesLocation._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesLocation.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesWifi._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesWifi.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesBluetooth._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesBluetooth.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesMobileCells._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesMobileCells.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesPeripherals._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesPeripherals.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesScreen._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesScreen.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesNotification._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesNotification.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesApplication._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesApplication.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesOrientation._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesOrientation.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesNFC._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesNFC.getPreferencesDescription(true, addPassStatus, context); if (_eventPreferencesAlarmClock._enabled && (!description.isEmpty())) description = description + "<br>"; //"\n"; description = description + _eventPreferencesAlarmClock.getPreferencesDescription(true, addPassStatus, context); //description = description.replace(' ', '\u00A0'); return description; } public void checkPreferences(PreferenceManager prefMng, Context context) { _eventPreferencesTime.checkPreferences(prefMng, context); _eventPreferencesBattery.checkPreferences(prefMng, context); _eventPreferencesCall.checkPreferences(prefMng, context); _eventPreferencesPeripherals.checkPreferences(prefMng, context); _eventPreferencesCalendar.checkPreferences(prefMng, context); _eventPreferencesWifi.checkPreferences(prefMng, context); _eventPreferencesScreen.checkPreferences(prefMng, context); _eventPreferencesBluetooth.checkPreferences(prefMng, context); _eventPreferencesSMS.checkPreferences(prefMng, context); _eventPreferencesNotification.checkPreferences(prefMng, context); _eventPreferencesApplication.checkPreferences(prefMng, context); _eventPreferencesLocation.checkPreferences(prefMng, context); _eventPreferencesOrientation.checkPreferences(prefMng, context); _eventPreferencesMobileCells.checkPreferences(prefMng, context); _eventPreferencesNFC.checkPreferences(prefMng, context); _eventPreferencesRadioSwitch.checkPreferences(prefMng, context); _eventPreferencesAlarmClock.checkPreferences(prefMng, context); } /* private boolean canActivateReturnProfile() { return true; } */ private int getEventTimelinePosition(List<EventTimeline> eventTimelineList) { boolean exists = false; int eventPosition = -1; for (EventTimeline eventTimeline : eventTimelineList) { eventPosition++; if (eventTimeline._fkEvent == this._id) { exists = true; break; } } if (exists) return eventPosition; else return -1; } private void addEventTimeline(DataWrapper dataWrapper, List<EventTimeline> eventTimelineList/*, Profile mergedProfile*/) { EventTimeline eventTimeline = new EventTimeline(); eventTimeline._fkEvent = this._id; eventTimeline._eorder = 0; if (eventTimelineList.size() == 0) { Profile profile = dataWrapper.getActivatedProfile(false, false); if (profile != null) eventTimeline._fkProfileEndActivated = profile._id; else eventTimeline._fkProfileEndActivated = 0; } else { eventTimeline._fkProfileEndActivated = 0; EventTimeline _eventTimeline = eventTimelineList.get(eventTimelineList.size()-1); if (_eventTimeline != null) { Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); if (event != null) eventTimeline._fkProfileEndActivated = event._fkProfileStart; } } DatabaseHandler.getInstance(dataWrapper.context).addEventTimeline(eventTimeline); eventTimelineList.add(eventTimeline); } void startEvent(DataWrapper dataWrapper, List<EventTimeline> eventTimelineList, //boolean ignoreGlobalPref, //boolean interactive, boolean reactivate, //boolean log, Profile mergedProfile) { // remove delay alarm removeDelayStartAlarm(dataWrapper); // for start delay removeDelayEndAlarm(dataWrapper); // for end delay if ((!getGlobalEventsRunning(dataWrapper.context))/* && (!ignoreGlobalPref)*/) // events are globally stopped return; if (!this.isRunnable(dataWrapper.context, true)) // event is not runnable, no pause it return; if (getEventsBlocked(dataWrapper.context)) { // blocked by manual profile activation PPApplication.logE("Event.startEvent","event_id="+this._id+" events blocked"); PPApplication.logE("Event.startEvent","event_id="+this._id+" forceRun="+_forceRun); PPApplication.logE("Event.startEvent","event_id="+this._id+" blocked="+_blocked); if (!_forceRun) // event is not forceRun return; if (_blocked) // forceRun event is temporary blocked return; } // check activated profile if (!_startWhenActivatedProfile.isEmpty()) { Profile activatedProfile = dataWrapper.getActivatedProfile(false, false); if (activatedProfile != null) { boolean found = false; String[] splits = _startWhenActivatedProfile.split("\\|"); for (String split : splits) { if (activatedProfile._id == Long.valueOf(split)) { found = true; break; } } if (!found) // if activated profile is not _startWhenActivatedProfile, not start event return; } } // search for running event with higher priority for (EventTimeline eventTimeline : eventTimelineList) { Event event = dataWrapper.getEventById(eventTimeline._fkEvent); if ((event != null) && ApplicationPreferences.applicationEventUsePriority(dataWrapper.context) && (event._priority > this._priority)) // is running event with higher priority return; } if (_forceRun) setForceRunEventRunning(dataWrapper.context, true); PPApplication.logE("@@@ Event.startEvent","event_id="+this._id+"-----------------------------------"); PPApplication.logE("@@@ Event.startEvent","-- event_name="+this._name); EventTimeline eventTimeline; /////// delete duplicate from timeline boolean exists = true; while (exists) { //exists = false; int timeLineSize = eventTimelineList.size(); // test whenever event exists in timeline eventTimeline = null; int eventPosition = getEventTimelinePosition(eventTimelineList); PPApplication.logE("Event.startEvent","eventPosition="+eventPosition); if (eventPosition != -1) eventTimeline = eventTimelineList.get(eventPosition); exists = eventPosition != -1; if (exists) { // remove event from timeline eventTimelineList.remove(eventTimeline); DatabaseHandler.getInstance(dataWrapper.context).deleteEventTimeline(eventTimeline); if (eventPosition < (timeLineSize-1)) { if (eventPosition > 0) { EventTimeline _eventTimeline = eventTimelineList.get(eventPosition-1); Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); if (event != null) eventTimelineList.get(eventPosition)._fkProfileEndActivated = event._fkProfileStart; else eventTimelineList.get(eventPosition)._fkProfileEndActivated = 0; } else { eventTimelineList.get(eventPosition)._fkProfileEndActivated = eventTimeline._fkProfileEndActivated; } } } } ////////////////////////////////// addEventTimeline(dataWrapper, eventTimelineList/*, mergedProfile*/); setSystemEvent(dataWrapper.context, ESTATUS_RUNNING); int status = this._status; this._status = ESTATUS_RUNNING; DatabaseHandler.getInstance(dataWrapper.context).updateEventStatus(this); if (/*log && */(status != this._status)) { dataWrapper.addActivityLog(DatabaseHandler.ALTYPE_EVENTSTART, _name, null, null, 0); } long activatedProfileId = 0; Profile activatedProfile = dataWrapper.getActivatedProfile(false, false); if (activatedProfile != null) activatedProfileId = activatedProfile._id; if ((this._fkProfileStart != activatedProfileId) || this._manualProfileActivation || reactivate) { // no activate profile, when is already activated PPApplication.logE("Event.startEvent","event_id="+this._id+" activate profile id="+this._fkProfileStart); if (mergedProfile == null) dataWrapper.activateProfileFromEvent(this._fkProfileStart, /*interactive,*/ false, false); else { mergedProfile.mergeProfiles(this._fkProfileStart, dataWrapper, true); if (this._manualProfileActivation) { DatabaseHandler.getInstance(dataWrapper.context).saveMergedProfile(mergedProfile); dataWrapper.activateProfileFromEvent(mergedProfile._id, /*interactive,*/ true, true); mergedProfile._id = 0; } } } else { dataWrapper.updateNotificationAndWidgets(); } //return; } private void doActivateEndProfile(DataWrapper dataWrapper, int eventPosition, int timeLineSize, List<EventTimeline> eventTimelineList, EventTimeline eventTimeline, boolean activateReturnProfile, Profile mergedProfile, boolean allowRestart) { if (!(eventPosition == (timeLineSize-1))) { // event is not in end of timeline // check whether events behind have set _fkProfileEnd or _undoProfile // when true, no activate "end profile" /*for (int i = eventPosition; i < (timeLineSize-1); i++) { if (_fkProfileEnd != Event.PROFILE_END_NO_ACTIVATE) return; if (_undoneProfile) return; }*/ return; } boolean profileActivated = false; Profile activatedProfile = dataWrapper.getActivatedProfile(false, false); // activate profile only when profile not already activated //noinspection ConstantConditions if (activateReturnProfile/* && canActivateReturnProfile()*/) { long activatedProfileId = 0; if (activatedProfile != null) activatedProfileId = activatedProfile._id; // first activate _fkProfileEnd if (_fkProfileEnd != Profile.PROFILE_NO_ACTIVATE) { if (_fkProfileEnd != activatedProfileId) { PPApplication.logE("Event.pauseEvent","activate end profile"); if (mergedProfile == null) dataWrapper.activateProfileFromEvent(_fkProfileEnd, /*false,*/ false, false); else mergedProfile.mergeProfiles(_fkProfileEnd, dataWrapper, false); activatedProfileId = _fkProfileEnd; profileActivated = true; } } // second activate when undone profile is set if (_atEndDo == EATENDDO_UNDONE_PROFILE) { // when in timeline list is event, get start profile from last event in timeline list // because last event in timeline list may be changed if (eventTimelineList.size() > 0) { EventTimeline _eventTimeline = eventTimelineList.get(eventTimelineList.size() - 1); if (_eventTimeline != null) { Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); if (event != null) eventTimeline._fkProfileEndActivated = event._fkProfileStart; } } if (eventTimeline._fkProfileEndActivated != activatedProfileId) { PPApplication.logE("Event.pauseEvent","undone profile"); PPApplication.logE("Event.pauseEvent","_fkProfileEndActivated="+eventTimeline._fkProfileEndActivated); if (eventTimeline._fkProfileEndActivated != 0) { if (mergedProfile == null) dataWrapper.activateProfileFromEvent(eventTimeline._fkProfileEndActivated, /*false,*/ false, false); else mergedProfile.mergeProfiles(eventTimeline._fkProfileEndActivated, dataWrapper, false); profileActivated = true; } } } // restart events when is set if ((_atEndDo == EATENDDO_RESTART_EVENTS) && allowRestart) { PPApplication.logE("Event.pauseEvent","restart events"); dataWrapper.restartEventsWithDelay(5, true, true, DatabaseHandler.ALTYPE_UNDEFINED); profileActivated = true; } } if (!profileActivated) { dataWrapper.updateNotificationAndWidgets(); } } void pauseEvent(DataWrapper dataWrapper, List<EventTimeline> eventTimelineList, boolean activateReturnProfile, boolean ignoreGlobalPref, boolean noSetSystemEvent, //boolean log, Profile mergedProfile, boolean allowRestart) { // remove delay alarm removeDelayStartAlarm(dataWrapper); // for start delay removeDelayEndAlarm(dataWrapper); // for end delay if ((!getGlobalEventsRunning(dataWrapper.context)) && (!ignoreGlobalPref)) // events are globally stopped return; if (!this.isRunnable(dataWrapper.context, true)) // event is not runnable, no pause it return; /* if (PPApplication.getEventsBlocked(dataWrapper.context)) { // blocked by manual profile activation PPApplication.logE("Event.pauseEvent","event_id="+this._id+" events blocked"); if (!_forceRun) // event is not forceRun return; } */ // unblock event when paused dataWrapper.setEventBlocked(this, false); PPApplication.logE("@@@ Event.pauseEvent","event_id="+this._id+"-----------------------------------"); PPApplication.logE("@@@ Event.pauseEvent","-- event_name="+this._name); int timeLineSize = eventTimelineList.size(); // test whenever event exists in timeline int eventPosition = getEventTimelinePosition(eventTimelineList); PPApplication.logE("Event.pauseEvent","eventPosition="+eventPosition); boolean exists = eventPosition != -1; EventTimeline eventTimeline = null; if (exists) { // clear start event notification if (_repeatNotification) { boolean clearNotification = true; for (int i = eventTimelineList.size()-1; i > 0; i--) { EventTimeline _eventTimeline = eventTimelineList.get(i); Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); if ((event != null) && (event._repeatNotification) && (event._id != this._id)) { // not clear, notification is from another event clearNotification = false; break; } } if (clearNotification) { NotificationManager notificationManager = (NotificationManager) dataWrapper.context.getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager != null) notificationManager.cancel(PPApplication.EVENT_START_NOTIFICATION_ID); StartEventNotificationBroadcastReceiver.removeAlarm(dataWrapper.context); } } eventTimeline = eventTimelineList.get(eventPosition); // remove event from timeline eventTimelineList.remove(eventTimeline); DatabaseHandler.getInstance(dataWrapper.context).deleteEventTimeline(eventTimeline); if (eventPosition < (timeLineSize-1)) // event is not in end of timeline and no only one event in timeline { if (eventPosition > 0) // event is not in start of timeline { // get event prior deleted event EventTimeline _eventTimeline = eventTimelineList.get(eventPosition-1); Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); // set _fkProfileEndActivated for event behind deleted event with _fkProfileStart of deleted event if (event != null) eventTimelineList.get(eventPosition)._fkProfileEndActivated = event._fkProfileStart; else eventTimelineList.get(eventPosition)._fkProfileEndActivated = 0; } else // event is in start of timeline { // set _fkProfileEndActivated of first event with _fkProfileEndActivated of deleted event eventTimelineList.get(eventPosition)._fkProfileEndActivated = eventTimeline._fkProfileEndActivated; } } } if (!noSetSystemEvent) setSystemEvent(dataWrapper.context, ESTATUS_PAUSE); int status = this._status; PPApplication.logE("@@@ Event.pauseEvent","-- old status="+this._status); this._status = ESTATUS_PAUSE; PPApplication.logE("@@@ Event.pauseEvent","-- new status="+this._status); DatabaseHandler.getInstance(dataWrapper.context).updateEventStatus(this); if (/*log &&*/ (status != this._status)) { doLogForPauseEvent(dataWrapper, allowRestart); } //if (_forceRun) //{ look for forceRun events always, not only when forceRun event is paused boolean forceRunRunning = false; for (EventTimeline _eventTimeline : eventTimelineList) { Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); if ((event != null) && (event._forceRun)) { forceRunRunning = true; break; } } if (!forceRunRunning) setForceRunEventRunning(dataWrapper.context, false); //} if (exists) { doActivateEndProfile(dataWrapper, eventPosition, timeLineSize, eventTimelineList, eventTimeline, activateReturnProfile, mergedProfile, allowRestart); } //return; } void doLogForPauseEvent(DataWrapper dataWrapper, boolean allowRestart) { int alType = DatabaseHandler.ALTYPE_EVENTEND_NONE; if ((_atEndDo == EATENDDO_UNDONE_PROFILE) && (_fkProfileEnd != Profile.PROFILE_NO_ACTIVATE)) alType = DatabaseHandler.ALTYPE_EVENTEND_ACTIVATEPROFILE_UNDOPROFILE; if ((_atEndDo == EATENDDO_RESTART_EVENTS) && (_fkProfileEnd != Profile.PROFILE_NO_ACTIVATE)) { if (allowRestart) alType = DatabaseHandler.ALTYPE_EVENTEND_ACTIVATEPROFILE_RESTARTEVENTS; else alType = DatabaseHandler.ALTYPE_EVENTEND_ACTIVATEPROFILE; } else if (_atEndDo == EATENDDO_UNDONE_PROFILE) alType = DatabaseHandler.ALTYPE_EVENTEND_UNDOPROFILE; else if (_atEndDo == EATENDDO_RESTART_EVENTS) { if (allowRestart) alType = DatabaseHandler.ALTYPE_EVENTEND_RESTARTEVENTS; } else if (_fkProfileEnd != Profile.PROFILE_NO_ACTIVATE) alType = DatabaseHandler.ALTYPE_EVENTEND_ACTIVATEPROFILE; dataWrapper.addActivityLog(alType, _name, null, null, 0); } void stopEvent(DataWrapper dataWrapper, List<EventTimeline> eventTimelineList, boolean activateReturnProfile, boolean ignoreGlobalPref, boolean saveEventStatus) //boolean log) //boolean allowRestart) { // remove delay alarm removeDelayStartAlarm(dataWrapper); // for start delay removeDelayEndAlarm(dataWrapper); // for end delay if ((!getGlobalEventsRunning(dataWrapper.context)) && (!ignoreGlobalPref)) // events are globally stopped return; PPApplication.logE("@@@ Event.stopEvent","event_id="+this._id+"-----------------------------------"); PPApplication.logE("@@@ Event.stopEvent", "-- event_name=" + this._name); if (this._status != ESTATUS_STOP) { pauseEvent(dataWrapper, eventTimelineList, activateReturnProfile, ignoreGlobalPref, true, /*false,*/ null, false/*allowRestart*/); } setSystemEvent(dataWrapper.context, ESTATUS_STOP); int status = this._status; PPApplication.logE("@@@ Event.stopEvent","-- old status="+this._status); this._status = ESTATUS_STOP; PPApplication.logE("@@@ Event.stopEvent","-- new status="+this._status); if (saveEventStatus) DatabaseHandler.getInstance(dataWrapper.context).updateEventStatus(this); if (/*log &&*/ (status != this._status)) { dataWrapper.addActivityLog(DatabaseHandler.ALTYPE_EVENTSTOP, _name, null, null, 0); } //return; } public int getStatus() { return _status; } int getStatusFromDB(Context context) { return DatabaseHandler.getInstance(context).getEventStatus(this); } public void setStatus(int status) { _status = status; } private void setSystemEvent(Context context, int forStatus) { if (forStatus == ESTATUS_PAUSE) { // event paused // setup system event for next running status _eventPreferencesTime.setSystemEventForStart(context); _eventPreferencesBattery.setSystemEventForStart(context); _eventPreferencesCall.setSystemEventForStart(context); _eventPreferencesPeripherals.setSystemEventForStart(context); _eventPreferencesCalendar.setSystemEventForStart(context); _eventPreferencesWifi.setSystemEventForStart(context); _eventPreferencesScreen.setSystemEventForStart(context); _eventPreferencesBluetooth.setSystemEventForStart(context); _eventPreferencesSMS.setSystemEventForStart(context); _eventPreferencesNotification.setSystemEventForStart(context); _eventPreferencesApplication.setSystemEventForStart(context); _eventPreferencesLocation.setSystemEventForStart(context); _eventPreferencesOrientation.setSystemEventForStart(context); _eventPreferencesMobileCells.setSystemEventForStart(context); _eventPreferencesNFC.setSystemEventForStart(context); _eventPreferencesRadioSwitch.setSystemEventForStart(context); _eventPreferencesAlarmClock.setSystemEventForStart(context); } else if (forStatus == ESTATUS_RUNNING) { // event started // setup system event for pause status _eventPreferencesTime.setSystemEventForPause(context); _eventPreferencesBattery.setSystemEventForPause(context); _eventPreferencesCall.setSystemEventForPause(context); _eventPreferencesPeripherals.setSystemEventForPause(context); _eventPreferencesCalendar.setSystemEventForPause(context); _eventPreferencesWifi.setSystemEventForPause(context); _eventPreferencesScreen.setSystemEventForPause(context); _eventPreferencesBluetooth.setSystemEventForPause(context); _eventPreferencesSMS.setSystemEventForPause(context); _eventPreferencesNotification.setSystemEventForPause(context); _eventPreferencesApplication.setSystemEventForPause(context); _eventPreferencesLocation.setSystemEventForPause(context); _eventPreferencesOrientation.setSystemEventForPause(context); _eventPreferencesMobileCells.setSystemEventForPause(context); _eventPreferencesNFC.setSystemEventForPause(context); _eventPreferencesRadioSwitch.setSystemEventForPause(context); _eventPreferencesAlarmClock.setSystemEventForPause(context); } else if (forStatus == ESTATUS_STOP) { // event stopped // remove all system events _eventPreferencesTime.removeSystemEvent(context); _eventPreferencesBattery.removeSystemEvent(context); _eventPreferencesCall.removeSystemEvent(context); _eventPreferencesPeripherals.removeSystemEvent(context); _eventPreferencesCalendar.removeSystemEvent(context); _eventPreferencesWifi.removeSystemEvent(context); _eventPreferencesScreen.removeSystemEvent(context); _eventPreferencesBluetooth.removeSystemEvent(context); _eventPreferencesSMS.removeSystemEvent(context); _eventPreferencesNotification.removeSystemEvent(context); _eventPreferencesApplication.removeSystemEvent(context); _eventPreferencesLocation.removeSystemEvent(context); _eventPreferencesOrientation.removeSystemEvent(context); _eventPreferencesMobileCells.removeSystemEvent(context); _eventPreferencesNFC.removeSystemEvent(context); _eventPreferencesRadioSwitch.removeSystemEvent(context); _eventPreferencesAlarmClock.removeSystemEvent(context); } } @SuppressLint({"SimpleDateFormat", "NewApi"}) void setDelayStartAlarm(DataWrapper dataWrapper) { removeDelayStartAlarm(dataWrapper); if (!getGlobalEventsRunning(dataWrapper.context)) // events are globally stopped return; if (!this.isRunnable(dataWrapper.context, true)) // event is not runnable, no pause it return; if (getEventsBlocked(dataWrapper.context)) { // blocked by manual profile activation PPApplication.logE("Event.setDelayStartAlarm","event_id="+this._id+" events blocked"); if (!_forceRun) // event is not forceRun return; if (_blocked) // forceRun event is temporary blocked return; } PPApplication.logE("@@@ Event.setDelayStartAlarm","event_id="+this._id+"-----------------------------------"); PPApplication.logE("@@@ Event.setDelayStartAlarm","-- event_name="+this._name); PPApplication.logE("@@@ Event.setDelayStartAlarm","-- delay="+this._delayStart); if (this._delayStart > 0) { Context _context = dataWrapper.context; if (PhoneProfilesService.getInstance() != null) _context = PhoneProfilesService.getInstance(); // delay for start is > 0 // set alarm Calendar now = Calendar.getInstance(); now.add(Calendar.SECOND, this._delayStart); long alarmTime = now.getTimeInMillis(); // + 1000 * /* 60 * */ this._delayStart; if (PPApplication.logEnabled()) { SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S"); String result = sdf.format(alarmTime); PPApplication.logE("Event.setDelayStartAlarm", "startTime=" + result); } //Intent intent = new Intent(_context, EventDelayStartBroadcastReceiver.class); Intent intent = new Intent(); intent.setAction(PhoneProfilesService.ACTION_EVENT_DELAY_START_BROADCAST_RECEIVER); //intent.setClass(context, EventDelayStartBroadcastReceiver.class); //intent.putExtra(PPApplication.EXTRA_EVENT_ID, this._id); PendingIntent pendingIntent = PendingIntent.getBroadcast(_context, (int) this._id, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE); if (alarmManager != null) { if ((android.os.Build.VERSION.SDK_INT >= 21) && ApplicationPreferences.applicationUseAlarmClock(_context)) { Intent editorIntent = new Intent(_context, EditorProfilesActivity.class); PendingIntent infoPendingIntent = PendingIntent.getActivity(_context, 1000, editorIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(alarmTime, infoPendingIntent); alarmManager.setAlarmClock(clockInfo, pendingIntent); } else { if (android.os.Build.VERSION.SDK_INT >= 23) alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent); else /*if (android.os.Build.VERSION.SDK_INT >= 19)*/ alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent); //else // alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent); } now = Calendar.getInstance(); int gmtOffset = 0; //TimeZone.getDefault().getRawOffset(); this._startStatusTime = now.getTimeInMillis() - gmtOffset; this._isInDelayStart = true; } else { this._startStatusTime = 0; this._isInDelayStart = false; } } else { this._startStatusTime = 0; this._isInDelayStart = false; } DatabaseHandler.getInstance(dataWrapper.context).updateEventInDelayStart(this); if (_isInDelayStart) { dataWrapper.addActivityLog(DatabaseHandler.ALTYPE_EVENTSTARTDELAY, _name, null, null, _delayStart); } //return; } void checkDelayStart(/*DataWrapper dataWrapper*/) { if (this._startStatusTime == 0) { this._isInDelayStart = false; return; } Calendar now = Calendar.getInstance(); int gmtOffset = 0; //TimeZone.getDefault().getRawOffset(); long nowTime = now.getTimeInMillis() - gmtOffset; now.add(Calendar.SECOND, this._delayStart); long delayTime = now.getTimeInMillis() - gmtOffset; if (nowTime > delayTime) this._isInDelayStart = false; } void removeDelayStartAlarm(DataWrapper dataWrapper) { Context _context = dataWrapper.context; if (PhoneProfilesService.getInstance() != null) _context = PhoneProfilesService.getInstance(); AlarmManager alarmManager = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE); if (alarmManager != null) { //Intent intent = new Intent(_context, EventDelayStartBroadcastReceiver.class); Intent intent = new Intent(); intent.setAction(PhoneProfilesService.ACTION_EVENT_DELAY_START_BROADCAST_RECEIVER); //intent.setClass(context, EventDelayStartBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(_context, (int) this._id, intent, PendingIntent.FLAG_NO_CREATE); if (pendingIntent != null) { PPApplication.logE("Event.removeDelayStartAlarm", "alarm found"); alarmManager.cancel(pendingIntent); pendingIntent.cancel(); } } this._isInDelayStart = false; this._startStatusTime = 0; DatabaseHandler.getInstance(dataWrapper.context).updateEventInDelayStart(this); } @SuppressLint({"SimpleDateFormat", "NewApi"}) void setDelayEndAlarm(DataWrapper dataWrapper) { removeDelayEndAlarm(dataWrapper); if (!getGlobalEventsRunning(dataWrapper.context)) // events are globally stopped return; if (!this.isRunnable(dataWrapper.context, true)) // event is not runnable, no pause it return; if (getEventsBlocked(dataWrapper.context)) { // blocked by manual profile activation PPApplication.logE("Event.setDelayEndAlarm","event_id="+this._id+" events blocked"); if (!_forceRun) // event is not forceRun return; if (_blocked) // forceRun event is temporary blocked return; } PPApplication.logE("@@@ Event.setDelayEndAlarm","event_id="+this._id+"-----------------------------------"); PPApplication.logE("@@@ Event.setDelayEndAlarm","-- event_name="+this._name); PPApplication.logE("@@@ Event.setDelayEndAlarm","-- delay="+this._delayEnd); if (this._delayEnd > 0) { Context _context = dataWrapper.context; if (PhoneProfilesService.getInstance() != null) _context = PhoneProfilesService.getInstance(); // delay for end is > 0 // set alarm Calendar now = Calendar.getInstance(); now.add(Calendar.SECOND, this._delayEnd); long alarmTime = now.getTimeInMillis(); // + 1000 * /* 60 * */ this._delayEnd; if (PPApplication.logEnabled()) { SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S"); String result = sdf.format(alarmTime); PPApplication.logE("Event.setDelayEndAlarm", "endTime=" + result); } //Intent intent = new Intent(_context, EventDelayEndBroadcastReceiver.class); Intent intent = new Intent(); intent.setAction(PhoneProfilesService.ACTION_EVENT_DELAY_END_BROADCAST_RECEIVER); //intent.setClass(context, EventDelayEndBroadcastReceiver.class); //intent.putExtra(PPApplication.EXTRA_EVENT_ID, this._id); PendingIntent pendingIntent = PendingIntent.getBroadcast(_context, (int) this._id, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE); if (alarmManager != null) { if ((android.os.Build.VERSION.SDK_INT >= 21) && ApplicationPreferences.applicationUseAlarmClock(_context)) { Intent editorIntent = new Intent(_context, EditorProfilesActivity.class); PendingIntent infoPendingIntent = PendingIntent.getActivity(_context, 1000, editorIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(alarmTime, infoPendingIntent); alarmManager.setAlarmClock(clockInfo, pendingIntent); } else { if (android.os.Build.VERSION.SDK_INT >= 23) alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent); else /*if (android.os.Build.VERSION.SDK_INT >= 19)*/ alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent); //else // alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent); } now = Calendar.getInstance(); int gmtOffset = 0; //TimeZone.getDefault().getRawOffset(); this._pauseStatusTime = now.getTimeInMillis() - gmtOffset; this._isInDelayEnd = true; } else { this._pauseStatusTime = 0; this._isInDelayEnd = false; } } else { this._pauseStatusTime = 0; this._isInDelayEnd = false; } DatabaseHandler.getInstance(dataWrapper.context).updateEventInDelayEnd(this); if (_isInDelayEnd) { dataWrapper.addActivityLog(DatabaseHandler.ALTYPE_EVENTENDDELAY, _name, null, null, _delayEnd); } //return; } void checkDelayEnd(/*DataWrapper dataWrapper*/) { //PPApplication.logE("Event.checkDelayEnd","this._pauseStatusTime="+this._pauseStatusTime); //PPApplication.logE("Event.checkDelayEnd","this._isInDelayEnd="+this._isInDelayEnd); //PPApplication.logE("Event.checkDelayEnd","this._delayEnd="+this._delayEnd); if (this._pauseStatusTime == 0) { this._isInDelayEnd = false; return; } Calendar now = Calendar.getInstance(); int gmtOffset = 0; //TimeZone.getDefault().getRawOffset(); long nowTime = now.getTimeInMillis() - gmtOffset; now.add(Calendar.SECOND, this._delayEnd); long delayTime = now.getTimeInMillis() - gmtOffset; /* SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S"); String result = sdf.format(nowTime); PPApplication.logE("Event.checkDelayEnd","nowTime="+result); result = sdf.format(this._pauseStatusTime); PPApplication.logE("Event.checkDelayEnd","pauseStatusTime="+result); result = sdf.format(delayTime); PPApplication.logE("Event.checkDelayEnd","delayTime="+result); */ if (nowTime > delayTime) this._isInDelayEnd = false; //PPApplication.logE("Event.checkDelayEnd","this._isInDelayEnd="+this._isInDelayEnd); } void removeDelayEndAlarm(DataWrapper dataWrapper) { Context _context = dataWrapper.context; if (PhoneProfilesService.getInstance() != null) _context = PhoneProfilesService.getInstance(); AlarmManager alarmManager = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE); if (alarmManager != null) { //Intent intent = new Intent(_context, EventDelayEndBroadcastReceiver.class); Intent intent = new Intent(); intent.setAction(PhoneProfilesService.ACTION_EVENT_DELAY_END_BROADCAST_RECEIVER); //intent.setClass(context, EventDelayEndBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(_context, (int) this._id, intent, PendingIntent.FLAG_NO_CREATE); if (pendingIntent != null) { PPApplication.logE("Event.removeDelayEndAlarm", "alarm found"); alarmManager.cancel(pendingIntent); pendingIntent.cancel(); } } this._isInDelayEnd = false; DatabaseHandler.getInstance(dataWrapper.context).updateEventInDelayEnd(this); } static PreferenceAllowed isEventPreferenceAllowed(String preferenceKey, Context context) { PreferenceAllowed preferenceAllowed = new PreferenceAllowed(); preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_NOT_ALLOWED; boolean checked = false; if (preferenceKey.equals(EventPreferencesWifi.PREF_EVENT_WIFI_ENABLED)) { if (PPApplication.hasSystemFeature(context, PackageManager.FEATURE_WIFI)) // device has Wifi preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_ALLOWED; else preferenceAllowed.notAllowedReason = PreferenceAllowed.PREFERENCE_NOT_ALLOWED_NO_HARDWARE; checked = true; } if (checked) return preferenceAllowed; if (preferenceKey.equals(EventPreferencesBluetooth.PREF_EVENT_BLUETOOTH_ENABLED)) { if (PPApplication.hasSystemFeature(context, PackageManager.FEATURE_BLUETOOTH)) // device has bluetooth preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_ALLOWED; else preferenceAllowed.notAllowedReason = PreferenceAllowed.PREFERENCE_NOT_ALLOWED_NO_HARDWARE; checked = true; } if (checked) return preferenceAllowed; if (preferenceKey.equals(EventPreferencesNotification.PREF_EVENT_NOTIFICATION_ENABLED)) { //if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_ALLOWED; /*else { PPApplication.notAllowedReason = PreferenceAllowed.PREFERENCE_NOT_ALLOWED_NOT_SUPPORTED_BY_SYSTEM; PPApplication.notAllowedReasonDetail = context.getString(R.string.preference_not_allowed_reason_detail_old_android); }*/ checked = true; } if (checked) return preferenceAllowed; if (preferenceKey.equals(EventPreferencesApplication.PREF_EVENT_APPLICATION_ENABLED)) { //if (AccessibilityServiceBroadcastReceiver.isExtenderInstalled(context.getApplicationContext())) preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_ALLOWED; //else // PPApplication.notAllowedReason = PPApplication.PREFERENCE_NOT_ALLOWED_NO_EXTENDER_INSTALLED; checked = true; } if (checked) return preferenceAllowed; if (preferenceKey.equals(EventPreferencesOrientation.PREF_EVENT_ORIENTATION_ENABLED)) { boolean enabled = (PhoneProfilesService.getAccelerometerSensor(context.getApplicationContext()) != null) && (PhoneProfilesService.getMagneticFieldSensor(context.getApplicationContext()) != null) && (PhoneProfilesService.getAccelerometerSensor(context.getApplicationContext()) != null); if (enabled) { //if (AccessibilityServiceBroadcastReceiver.isExtenderInstalled(context.getApplicationContext())) preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_ALLOWED; //else // PPApplication.notAllowedReason = PPApplication.PREFERENCE_NOT_ALLOWED_NO_EXTENDER_INSTALLED; } else preferenceAllowed.notAllowedReason = PreferenceAllowed.PREFERENCE_NOT_ALLOWED_NO_HARDWARE; checked = true; } if (checked) return preferenceAllowed; if (preferenceKey.equals(EventPreferencesMobileCells.PREF_EVENT_MOBILE_CELLS_ENABLED)) { if (PPApplication.hasSystemFeature(context, PackageManager.FEATURE_TELEPHONY)) // device has telephony preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_ALLOWED; else preferenceAllowed.notAllowedReason = PreferenceAllowed.PREFERENCE_NOT_ALLOWED_NO_HARDWARE; checked = true; } if (checked) return preferenceAllowed; if (preferenceKey.equals(EventPreferencesNFC.PREF_EVENT_NFC_ENABLED)) { if (PPApplication.hasSystemFeature(context, PackageManager.FEATURE_NFC)) // device has nfc preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_ALLOWED; else preferenceAllowed.notAllowedReason = PreferenceAllowed.PREFERENCE_NOT_ALLOWED_NO_HARDWARE; checked = true; } if (checked) return preferenceAllowed; preferenceAllowed.allowed = PreferenceAllowed.PREFERENCE_ALLOWED; return preferenceAllowed; } static public boolean getGlobalEventsRunning(Context context) { ApplicationPreferences.getSharedPreferences(context); return ApplicationPreferences.preferences.getBoolean(PREF_GLOBAL_EVENTS_RUN_STOP, true); } static void setGlobalEventsRunning(Context context, boolean globalEventsRunning) { ApplicationPreferences.getSharedPreferences(context); Editor editor = ApplicationPreferences.preferences.edit(); editor.putBoolean(PREF_GLOBAL_EVENTS_RUN_STOP, globalEventsRunning); editor.apply(); } static boolean getEventsBlocked(Context context) { ApplicationPreferences.getSharedPreferences(context); return ApplicationPreferences.preferences.getBoolean(PREF_EVENTS_BLOCKED, false); } static void setEventsBlocked(Context context, boolean eventsBlocked) { ApplicationPreferences.getSharedPreferences(context); Editor editor = ApplicationPreferences.preferences.edit(); editor.putBoolean(PREF_EVENTS_BLOCKED, eventsBlocked); editor.apply(); } static boolean getForceRunEventRunning(Context context) { ApplicationPreferences.getSharedPreferences(context); return ApplicationPreferences.preferences.getBoolean(PREF_FORCE_RUN_EVENT_RUNNING, false); } static void setForceRunEventRunning(Context context, boolean forceRunEventRunning) { ApplicationPreferences.getSharedPreferences(context); Editor editor = ApplicationPreferences.preferences.edit(); editor.putBoolean(PREF_FORCE_RUN_EVENT_RUNNING, forceRunEventRunning); editor.apply(); } //---------------------------------- boolean notifyEventStart(Context context) { String notificationSound = _notificationSound; boolean notificationVibrate = _notificationVibrate; if (!notificationSound.isEmpty() || notificationVibrate) { PPApplication.logE("Event.notifyEventStart", "event._id="+_id); if (_repeatNotification) { NotificationCompat.Builder mBuilder; String nTitle = context.getString(R.string.start_event_notification_title); String nText = context.getString(R.string.start_event_notification_text1); nText = nText + ": " + _name; nText = nText + ". " + context.getString(R.string.start_event_notification_text2); if (android.os.Build.VERSION.SDK_INT < 24) { nTitle = context.getString(R.string.app_name); nText = context.getString(R.string.start_event_notification_title) + ": " + nText; } PPApplication.createNotifyEventStartNotificationChannel(context); mBuilder = new NotificationCompat.Builder(context, PPApplication.NOTIFY_EVENT_START_NOTIFICATION_CHANNEL) .setColor(ContextCompat.getColor(context, R.color.primary)) .setSmallIcon(R.drawable.ic_exclamation_notify) // notification icon .setContentTitle(nTitle) // title for notification .setContentText(nText) .setStyle(new NotificationCompat.BigTextStyle().bigText(nText)) .setAutoCancel(false); // clear notification after click PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pi); mBuilder.setPriority(Notification.PRIORITY_MAX); if (android.os.Build.VERSION.SDK_INT >= 21) { mBuilder.setCategory(Notification.CATEGORY_EVENT); mBuilder.setVisibility(Notification.VISIBILITY_PUBLIC); } Intent deleteIntent = new Intent(StartEventNotificationDeletedReceiver.START_EVENT_NOTIFICATION_DELETED_ACTION); PendingIntent deletePendingIntent = PendingIntent.getBroadcast(context, 0, deleteIntent, 0); mBuilder.setDeleteIntent(deletePendingIntent); NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (mNotificationManager != null) mNotificationManager.notify(PPApplication.EVENT_START_NOTIFICATION_ID, mBuilder.build()); StartEventNotificationBroadcastReceiver.setAlarm(this, context); } if (PhoneProfilesService.getInstance() != null) PhoneProfilesService.getInstance().playNotificationSound(notificationSound, notificationVibrate); return true; } return false; } }
Used is ELAPSED_REALTIME for some alarms. (3)
phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/Event.java
Used is ELAPSED_REALTIME for some alarms. (3)
Java
apache-2.0
6806410abdb9d0d30c8d725473cc5f97f9bc0502
0
OopsOutOfMemory/helix,lei-xia/helix,AyolaJayamaha/helix,dasahcc/helix,brandtg/helix,AyolaJayamaha/helix,brandtg/helix,dasahcc/helix,jzmq/helix,Teino1978-Corp/Teino1978-Corp-helix,Teino1978-Corp/Teino1978-Corp-helix,OopsOutOfMemory/helix,apache/helix,hdatas/helix,lei-xia/helix,dasahcc/helix,lei-xia/helix,brandtg/helix,lei-xia/helix,fx19880617/helix,apache/helix,Teino1978-Corp/Teino1978-Corp-helix,AyolaJayamaha/helix,fx19880617/helix,kongweihan/helix,dasahcc/helix,apache/helix,hdatas/helix,hdatas/helix,apache/helix,Teino1978-Corp/Teino1978-Corp-helix,OopsOutOfMemory/helix,kongweihan/helix,jzmq/helix,AyolaJayamaha/helix,fx19880617/helix,dasahcc/helix,fx19880617/helix,brandtg/helix,lei-xia/helix,kongweihan/helix,dasahcc/helix,apache/helix,jzmq/helix,OopsOutOfMemory/helix,jzmq/helix,lei-xia/helix,apache/helix
/** * Copyright (C) 2012 LinkedIn Inc <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.helix.manager.zk; import static com.linkedin.helix.HelixConstants.ChangeType.CONFIG; import static com.linkedin.helix.HelixConstants.ChangeType.CURRENT_STATE; import static com.linkedin.helix.HelixConstants.ChangeType.EXTERNAL_VIEW; import static com.linkedin.helix.HelixConstants.ChangeType.HEALTH; import static com.linkedin.helix.HelixConstants.ChangeType.IDEAL_STATE; import static com.linkedin.helix.HelixConstants.ChangeType.LIVE_INSTANCE; import static com.linkedin.helix.HelixConstants.ChangeType.MESSAGE; import static com.linkedin.helix.HelixConstants.ChangeType.MESSAGES_CONTROLLER; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Timer; import java.util.concurrent.TimeUnit; import org.I0Itec.zkclient.ZkConnection; import org.I0Itec.zkclient.serialize.ZkSerializer; import org.apache.log4j.Logger; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; import com.linkedin.helix.ClusterMessagingService; import com.linkedin.helix.ConfigAccessor; import com.linkedin.helix.ConfigChangeListener; import com.linkedin.helix.ConfigScope.ConfigScopeProperty; import com.linkedin.helix.ControllerChangeListener; import com.linkedin.helix.CurrentStateChangeListener; import com.linkedin.helix.DataAccessor; import com.linkedin.helix.ExternalViewChangeListener; import com.linkedin.helix.HealthStateChangeListener; import com.linkedin.helix.HelixAdmin; import com.linkedin.helix.HelixConstants.ChangeType; import com.linkedin.helix.HelixDataAccessor; import com.linkedin.helix.HelixException; import com.linkedin.helix.HelixManager; import com.linkedin.helix.HelixTimerTask; import com.linkedin.helix.IdealStateChangeListener; import com.linkedin.helix.InstanceType; import com.linkedin.helix.LiveInstanceChangeListener; import com.linkedin.helix.MessageListener; import com.linkedin.helix.PreConnectCallback; import com.linkedin.helix.PropertyKey.Builder; import com.linkedin.helix.PropertyPathConfig; import com.linkedin.helix.PropertyType; import com.linkedin.helix.ZNRecord; import com.linkedin.helix.healthcheck.HealthStatsAggregationTask; import com.linkedin.helix.healthcheck.ParticipantHealthReportCollector; import com.linkedin.helix.healthcheck.ParticipantHealthReportCollectorImpl; import com.linkedin.helix.messaging.DefaultMessagingService; import com.linkedin.helix.messaging.handling.MessageHandlerFactory; import com.linkedin.helix.model.CurrentState; import com.linkedin.helix.model.LiveInstance; import com.linkedin.helix.model.Message.MessageType; import com.linkedin.helix.model.StateModelDefinition; import com.linkedin.helix.monitoring.ZKPathDataDumpTask; import com.linkedin.helix.participant.DistClusterControllerElection; import com.linkedin.helix.participant.HelixStateMachineEngine; import com.linkedin.helix.participant.StateMachineEngine; import com.linkedin.helix.store.PropertyStore; import com.linkedin.helix.store.ZNRecordJsonSerializer; import com.linkedin.helix.store.zk.ZKPropertyStore; import com.linkedin.helix.tools.PropertiesReader; public class ZKHelixManager implements HelixManager { private static Logger logger = Logger.getLogger(ZKHelixManager.class); private static final int RETRY_LIMIT = 3; private static final int CONNECTIONTIMEOUT = 10000; private final String _clusterName; private final String _instanceName; private final String _zkConnectString; private static final int DEFAULT_SESSION_TIMEOUT = 30000; private ZKDataAccessor _accessor; private ZKHelixDataAccessor _helixAccessor; private ConfigAccessor _configAccessor; protected ZkClient _zkClient; private final List<CallbackHandler> _handlers; private final ZkStateChangeListener _zkStateChangeListener; private final InstanceType _instanceType; private String _sessionId; private Timer _timer; private CallbackHandler _leaderElectionHandler; private ParticipantHealthReportCollectorImpl _participantHealthCheckInfoCollector; private final DefaultMessagingService _messagingService; private ZKHelixAdmin _managementTool; private final String _version; private final StateMachineEngine _stateMachEngine; private int _sessionTimeout; private PropertyStore<ZNRecord> _propertyStore; private final List<HelixTimerTask> _controllerTimerTasks; private ZkBaseDataAccessor<ZNRecord> _baseDataAccessor; List<PreConnectCallback> _preConnectCallbacks = new LinkedList<PreConnectCallback>(); public ZKHelixManager(String clusterName, String instanceName, InstanceType instanceType, String zkConnectString) throws Exception { logger.info("Create a zk-based cluster manager. clusterName:" + clusterName + ", instanceName:" + instanceName + ", type:" + instanceType + ", zkSvr:" + zkConnectString); int sessionTimeoutInt = -1; try { sessionTimeoutInt = Integer.parseInt(System.getProperty("zk.session.timeout", "" + DEFAULT_SESSION_TIMEOUT)); } catch (NumberFormatException e) { logger.warn("Exception while parsing session timeout: " + System.getProperty("zk.session.timeout", "" + DEFAULT_SESSION_TIMEOUT)); } if (sessionTimeoutInt > 0) { _sessionTimeout = sessionTimeoutInt; } else { _sessionTimeout = DEFAULT_SESSION_TIMEOUT; } if (instanceName == null) { try { instanceName = InetAddress.getLocalHost().getCanonicalHostName() + "-" + instanceType.toString(); } catch (UnknownHostException e) { // can ignore it logger.info("Unable to get host name. Will set it to UNKNOWN, mostly ignorable", e); instanceName = "UNKNOWN"; } } _clusterName = clusterName; _instanceName = instanceName; _instanceType = instanceType; _zkConnectString = zkConnectString; _zkStateChangeListener = new ZkStateChangeListener(this); _timer = null; _handlers = new ArrayList<CallbackHandler>(); _messagingService = new DefaultMessagingService(this); _version = new PropertiesReader("cluster-manager-version.properties").getProperty("clustermanager.version"); _stateMachEngine = new HelixStateMachineEngine(this); // add all timer tasks _controllerTimerTasks = new ArrayList<HelixTimerTask>(); if (_instanceType == InstanceType.CONTROLLER) { _controllerTimerTasks.add(new HealthStatsAggregationTask(this)); } } private boolean isInstanceSetup() { if (_instanceType == InstanceType.PARTICIPANT || _instanceType == InstanceType.CONTROLLER_PARTICIPANT) { boolean isValid = _zkClient.exists(PropertyPathConfig.getPath(PropertyType.CONFIGS, _clusterName, ConfigScopeProperty.PARTICIPANT.toString(), _instanceName)) && _zkClient.exists(PropertyPathConfig.getPath(PropertyType.MESSAGES, _clusterName, _instanceName)) && _zkClient.exists(PropertyPathConfig.getPath(PropertyType.CURRENTSTATES, _clusterName, _instanceName)) && _zkClient.exists(PropertyPathConfig.getPath(PropertyType.STATUSUPDATES, _clusterName, _instanceName)) && _zkClient.exists(PropertyPathConfig.getPath(PropertyType.ERRORS, _clusterName, _instanceName)); return isValid; } return true; } @Override public void addIdealStateChangeListener(final IdealStateChangeListener listener) throws Exception { logger.info("ClusterManager.addIdealStateChangeListener()"); checkConnected(); final String path = PropertyPathConfig.getPath(PropertyType.IDEALSTATES, _clusterName); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeDataChanged, EventType.NodeDeleted, EventType.NodeCreated }, IDEAL_STATE); // _handlers.add(callbackHandler); addListener(callbackHandler); } @Override public void addLiveInstanceChangeListener(LiveInstanceChangeListener listener) throws Exception { logger.info("ClusterManager.addLiveInstanceChangeListener()"); checkConnected(); final String path = _helixAccessor.keyBuilder().liveInstances().getPath(); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }, LIVE_INSTANCE); // _handlers.add(callbackHandler); addListener(callbackHandler); } @Override public void addConfigChangeListener(ConfigChangeListener listener) { logger.info("ClusterManager.addConfigChangeListener()"); checkConnected(); // final String path = HelixUtil.getConfigPath(_clusterName); final String path = PropertyPathConfig.getPath(PropertyType.CONFIGS, _clusterName, ConfigScopeProperty.PARTICIPANT.toString()); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeChildrenChanged }, CONFIG); // _handlers.add(callbackHandler); addListener(callbackHandler); } // TODO: Decide if do we still need this since we are exposing // ClusterMessagingService @Override public void addMessageListener(MessageListener listener, String instanceName) { logger.info("ClusterManager.addMessageListener() " + instanceName); checkConnected(); final String path = _helixAccessor.keyBuilder().messages(instanceName).getPath(); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }, MESSAGE); // _handlers.add(callbackHandler); addListener(callbackHandler); } void addControllerMessageListener(MessageListener listener) { logger.info("ClusterManager.addControllerMessageListener()"); checkConnected(); final String path = _helixAccessor.keyBuilder().controllerMessages().getPath(); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }, MESSAGES_CONTROLLER); // _handlers.add(callbackHandler); addListener(callbackHandler); } @Override public void addCurrentStateChangeListener(CurrentStateChangeListener listener, String instanceName, String sessionId) { logger.info("ClusterManager.addCurrentStateChangeListener() " + instanceName + " " + sessionId); checkConnected(); final String path = _helixAccessor.keyBuilder().currentStates(instanceName, sessionId).getPath(); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }, CURRENT_STATE); // _handlers.add(callbackHandler); addListener(callbackHandler); } @Override public void addHealthStateChangeListener(HealthStateChangeListener listener, String instanceName) { // System.out.println("ZKClusterManager.addHealthStateChangeListener()"); // TODO: re-form this for stats checking logger.info("ClusterManager.addHealthStateChangeListener()" + instanceName); checkConnected(); final String path = _helixAccessor.keyBuilder().healthReports(instanceName).getPath(); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDataChanged, EventType.NodeDeleted, EventType.NodeCreated }, HEALTH); // _handlers.add(callbackHandler); addListener(callbackHandler); } @Override public void addExternalViewChangeListener(ExternalViewChangeListener listener) { logger.info("ClusterManager.addExternalViewChangeListener()"); checkConnected(); final String path = _helixAccessor.keyBuilder().externalViews().getPath(); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeDataChanged, EventType.NodeDeleted, EventType.NodeCreated }, EXTERNAL_VIEW); // _handlers.add(callbackHandler); addListener(callbackHandler); } @Override public DataAccessor getDataAccessor() { checkConnected(); return _accessor; } @Override public HelixDataAccessor getHelixDataAccessor() { checkConnected(); return _helixAccessor; } @Override public ConfigAccessor getConfigAccessor() { checkConnected(); return _configAccessor; } @Override public String getClusterName() { return _clusterName; } @Override public String getInstanceName() { return _instanceName; } @Override public void connect() throws Exception { logger.info("ClusterManager.connect()"); if (_zkStateChangeListener.isConnected()) { logger.warn("Cluster manager " + _clusterName + " " + _instanceName + " already connected"); return; } try { createClient(_zkConnectString); _messagingService.registerMessageHandlerFactory(MessageType.STATE_TRANSITION.toString(), _stateMachEngine); } catch (Exception e) { logger.error(e); disconnect(); throw e; } } @Override public void disconnect() { if (!isConnected()) { logger.warn("ClusterManager " + _instanceName + " already disconnected"); return; } logger.info("disconnect " + _instanceName + "(" + _instanceType + ") from " + _clusterName); /** * shutdown thread pool first to avoid reset() being invoked in the middle of state * transition */ _messagingService.getExecutor().shutDown(); resetHandlers(); if (_leaderElectionHandler != null) { _leaderElectionHandler.reset(); } if (_participantHealthCheckInfoCollector != null) { _participantHealthCheckInfoCollector.stop(); } if (_timer != null) { _timer.cancel(); _timer = null; } if (_instanceType == InstanceType.CONTROLLER) { stopTimerTasks(); } _zkClient.close(); // HACK seems that zkClient is not sending DISCONNECT event _zkStateChangeListener.disconnect(); logger.info("Cluster manager: " + _instanceName + " disconnected"); } @Override public String getSessionId() { checkConnected(); return _sessionId; } @Override public boolean isConnected() { return _zkStateChangeListener.isConnected(); } @Override public long getLastNotificationTime() { return -1; } @Override public void addControllerListener(ControllerChangeListener listener) { checkConnected(); final String path = _helixAccessor.keyBuilder().controller().getPath(); logger.info("Add controller listener at: " + path); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }, ChangeType.CONTROLLER); // System.out.println("add controller listeners to " + _instanceName + // " for " + _clusterName); // _handlers.add(callbackHandler); addListener(callbackHandler); } @Override public boolean removeListener(Object listener) { logger.info("remove listener: " + listener + " from " + _instanceName); synchronized (this) { Iterator<CallbackHandler> iterator = _handlers.iterator(); while (iterator.hasNext()) { CallbackHandler handler = iterator.next(); // simply compare reference if (handler.getListener().equals(listener)) { handler.reset(); iterator.remove(); } } } return true; } private void addLiveInstance() { LiveInstance liveInstance = new LiveInstance(_instanceName); liveInstance.setSessionId(_sessionId); liveInstance.setHelixVersion(_version); liveInstance.setLiveInstance(ManagementFactory.getRuntimeMXBean().getName()); logger.info("Add live instance: InstanceName: " + _instanceName + " Session id:" + _sessionId); // if (!_accessor.setProperty(PropertyType.LIVEINSTANCES, liveInstance, // _instanceName)) Builder keyBuilder = _helixAccessor.keyBuilder(); if (!_helixAccessor.createProperty(keyBuilder.liveInstance(_instanceName), liveInstance)) { String errorMsg = "Fail to create live instance node after waiting, so quit. instance:" + _instanceName; logger.warn(errorMsg); throw new HelixException(errorMsg); } String currentStatePathParent = PropertyPathConfig.getPath(PropertyType.CURRENTSTATES, _clusterName, _instanceName, getSessionId()); if (!_zkClient.exists(currentStatePathParent)) { _zkClient.createPersistent(currentStatePathParent); logger.info("Creating current state path " + currentStatePathParent); } } private void startStatusUpdatedumpTask() { long initialDelay = 30 * 60 * 1000; long period = 120 * 60 * 1000; int timeThresholdNoChange = 180 * 60 * 1000; if (_timer == null) { _timer = new Timer(); _timer.scheduleAtFixedRate(new ZKPathDataDumpTask(this, _zkClient, timeThresholdNoChange), initialDelay, period); } } private void createClient(String zkServers) throws Exception { ZkSerializer zkSerializer = new ZNRecordSerializer(); _zkClient = new ZkClient(zkServers, _sessionTimeout, CONNECTIONTIMEOUT, zkSerializer); _accessor = new ZKDataAccessor(_clusterName, _zkClient); _baseDataAccessor = new ZkBaseDataAccessor<ZNRecord>(_zkClient); _helixAccessor = new ZKHelixDataAccessor(_clusterName, _baseDataAccessor); _configAccessor = new ConfigAccessor(_zkClient); int retryCount = 0; _zkClient.subscribeStateChanges(_zkStateChangeListener); while (retryCount < RETRY_LIMIT) { try { _zkClient.waitUntilConnected(_sessionTimeout, TimeUnit.MILLISECONDS); _zkStateChangeListener.handleStateChanged(KeeperState.SyncConnected); _zkStateChangeListener.handleNewSession(); break; } catch (HelixException e) { logger.error("fail to createClient.", e); throw e; } catch (Exception e) { retryCount++; logger.error("fail to createClient. retry " + retryCount, e); if (retryCount == RETRY_LIMIT) { throw e; } } } } private CallbackHandler createCallBackHandler(String path, Object listener, EventType[] eventTypes, ChangeType changeType) { if (listener == null) { throw new HelixException("Listener cannot be null"); } return new CallbackHandler(this, _zkClient, path, listener, eventTypes, changeType); } /** * This will be invoked when ever a new session is created<br/> * * case 1: the cluster manager was a participant carry over current state, add live * instance, and invoke message listener; case 2: the cluster manager was controller and * was a leader before do leader election, and if it becomes leader again, invoke ideal * state listener, current state listener, etc. if it fails to become leader in the new * session, then becomes standby; case 3: the cluster manager was controller and was NOT * a leader before do leader election, and if it becomes leader, instantiate and invoke * ideal state listener, current state listener, etc. if if fails to become leader in * the new session, stay as standby */ protected void handleNewSession() { ZkConnection zkConnection = ((ZkConnection) _zkClient.getConnection()); _sessionId = Long.toHexString(zkConnection.getZookeeper().getSessionId()); // UUID.randomUUID().toString(); _accessor.reset(); resetHandlers(); logger.info("Handling new session, session id:" + _sessionId + ", instance:" + _instanceName); if (!ZKUtil.isClusterSetup(_clusterName, _zkClient)) { throw new HelixException("Initial cluster structure is not set up for cluster:" + _clusterName); } if (!isInstanceSetup()) { throw new HelixException("Initial cluster structure is not set up for instance:" + _instanceName + " instanceType:" + _instanceType); } if (_instanceType == InstanceType.PARTICIPANT || _instanceType == InstanceType.CONTROLLER_PARTICIPANT) { handleNewSessionAsParticipant(); } if (_instanceType == InstanceType.CONTROLLER || _instanceType == InstanceType.CONTROLLER_PARTICIPANT) { addControllerMessageListener(_messagingService.getExecutor()); MessageHandlerFactory defaultControllerMsgHandlerFactory = new DefaultControllerMessageHandlerFactory(); _messagingService.getExecutor() .registerMessageHandlerFactory(defaultControllerMsgHandlerFactory.getMessageType(), defaultControllerMsgHandlerFactory); MessageHandlerFactory defaultSchedulerMsgHandlerFactory = new DefaultSchedulerMessageHandlerFactory(this); _messagingService.getExecutor() .registerMessageHandlerFactory(defaultSchedulerMsgHandlerFactory.getMessageType(), defaultSchedulerMsgHandlerFactory); startStatusUpdatedumpTask(); if (_leaderElectionHandler == null) { final String path = PropertyPathConfig.getPath(PropertyType.CONTROLLER, _clusterName); _leaderElectionHandler = createCallBackHandler(path, new DistClusterControllerElection(_zkConnectString), new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }, ChangeType.CONTROLLER); } else { _leaderElectionHandler.init(); } } if (_instanceType == InstanceType.PARTICIPANT || _instanceType == InstanceType.CONTROLLER_PARTICIPANT || (_instanceType == InstanceType.CONTROLLER && isLeader())) { initHandlers(); } } private void handleNewSessionAsParticipant() { // In case there is a live instance record on zookeeper Builder keyBuilder = _helixAccessor.keyBuilder(); if (_helixAccessor.getProperty(keyBuilder.liveInstance(_instanceName)) != null) { logger.warn("Found another instance with same instanceName: " + _instanceName + " in cluster " + _clusterName); // Wait for a while, in case previous storage node exits unexpectedly // and its liveinstance // still hangs around until session timeout happens try { Thread.sleep(_sessionTimeout + 5000); } catch (InterruptedException e) { logger.warn("Sleep interrupted while waiting for previous liveinstance to go away.", e); } if (_helixAccessor.getProperty(keyBuilder.liveInstance(_instanceName)) != null) { String errorMessage = "instance " + _instanceName + " already has a liveinstance in cluster " + _clusterName; logger.error(errorMessage); throw new HelixException(errorMessage); } } // Invoke the PreConnectCallbacks for (PreConnectCallback callback : _preConnectCallbacks) { callback.onPreConnect(); } addLiveInstance(); carryOverPreviousCurrentState(); // In case the cluster manager is running as a participant, setup message // listener addMessageListener(_messagingService.getExecutor(), _instanceName); if (_participantHealthCheckInfoCollector == null) { _participantHealthCheckInfoCollector = new ParticipantHealthReportCollectorImpl(this, _instanceName); _participantHealthCheckInfoCollector.start(); } // start the participant health check timer, also create zk path for health // check info String healthCheckInfoPath = _helixAccessor.keyBuilder().healthReports(_instanceName).getPath(); if (!_zkClient.exists(healthCheckInfoPath)) { _zkClient.createPersistent(healthCheckInfoPath); logger.info("Creating healthcheck info path " + healthCheckInfoPath); } } @Override public void addPreConnectCallback(PreConnectCallback callback) { logger.info("Adding preconnect callback"); _preConnectCallbacks.add(callback); } private void resetHandlers() { synchronized (this) { for (CallbackHandler handler : _handlers) { handler.reset(); logger.info("reset handler: " + handler.getPath() + " by " + Thread.currentThread().getName()); } } } private void initHandlers() { synchronized (this) { for (CallbackHandler handler : _handlers) { handler.init(); } } } private void addListener(CallbackHandler handler) { synchronized (this) { _handlers.add(handler); logger.info("add handler: " + handler.getPath() + " by " + Thread.currentThread().getName()); } } @Override public boolean isLeader() { if (!isConnected()) { return false; } if (_instanceType != InstanceType.CONTROLLER) { return false; } Builder keyBuilder = _helixAccessor.keyBuilder(); LiveInstance leader = _helixAccessor.getProperty(keyBuilder.controllerLeader()); if (leader == null) { return false; } else { String leaderName = leader.getInstanceName(); // TODO need check sessionId also, but in distributed mode, leader's // sessionId is // not equal to // the leader znode's sessionId field which is the sessionId of the // controller_participant that // successfully creates the leader node if (leaderName == null || !leaderName.equals(_instanceName)) { return false; } } return true; } private void carryOverPreviousCurrentState() { Builder keyBuilder = _helixAccessor.keyBuilder(); List<String> subPaths = _helixAccessor.getChildNames(keyBuilder.sessions(_instanceName)); for (String previousSessionId : subPaths) { List<CurrentState> previousCurrentStates = _helixAccessor.getChildValues(keyBuilder.currentStates(_instanceName, previousSessionId)); for (CurrentState previousCurrentState : previousCurrentStates) { if (!previousSessionId.equalsIgnoreCase(_sessionId)) { logger.info("Carrying over old session:" + previousSessionId + " resource " + previousCurrentState.getId() + " to new session:" + _sessionId); String stateModelDefRef = previousCurrentState.getStateModelDefRef(); if (stateModelDefRef == null) { logger.error("pervious current state doesn't have a state model def. skip it. prevCS: " + previousCurrentState); continue; } StateModelDefinition stateModel = _helixAccessor.getProperty(keyBuilder.stateModelDef(stateModelDefRef)); for (String partitionName : previousCurrentState.getPartitionStateMap() .keySet()) { previousCurrentState.setState(partitionName, stateModel.getInitialState()); } previousCurrentState.setSessionId(_sessionId); _helixAccessor.setProperty(keyBuilder.currentState(_instanceName, _sessionId, previousCurrentState.getId()), previousCurrentState); } } } // Deleted old current state for (String previousSessionId : subPaths) { if (!previousSessionId.equalsIgnoreCase(_sessionId)) { String path = _helixAccessor.keyBuilder() .currentStates(_instanceName, previousSessionId) .getPath(); logger.info("Deleting previous current state. path: " + path + "/" + previousSessionId); _zkClient.deleteRecursive(path); } } } @Override public synchronized PropertyStore<ZNRecord> getPropertyStore() { checkConnected(); if (_propertyStore == null) { String path = PropertyPathConfig.getPath(PropertyType.PROPERTYSTORE, _clusterName); // property store uses a different serializer ZkClient zkClient = new ZkClient(_zkConnectString, CONNECTIONTIMEOUT); _propertyStore = new ZKPropertyStore<ZNRecord>(zkClient, new ZNRecordJsonSerializer(), path); } return _propertyStore; } @Override public synchronized HelixAdmin getClusterManagmentTool() { checkConnected(); if (_zkClient != null) { _managementTool = new ZKHelixAdmin(_zkClient); } else { logger.error("Couldn't get ZKClusterManagementTool because zkClient is null"); } return _managementTool; } @Override public ClusterMessagingService getMessagingService() { checkConnected(); return _messagingService; } @Override public ParticipantHealthReportCollector getHealthReportCollector() { checkConnected(); return _participantHealthCheckInfoCollector; } @Override public InstanceType getInstanceType() { return _instanceType; } private void checkConnected() { if (!isConnected()) { throw new HelixException("ClusterManager not connected. Call clusterManager.connect()"); } } @Override public String getVersion() { return _version; } @Override public StateMachineEngine getStateMachineEngine() { return _stateMachEngine; } protected List<CallbackHandler> getHandlers() { return _handlers; } @Override public void startTimerTasks() { for (HelixTimerTask task : _controllerTimerTasks) { task.start(); } } @Override public void stopTimerTasks() { for (HelixTimerTask task : _controllerTimerTasks) { task.stop(); } } }
helix-core/src/main/java/com/linkedin/helix/manager/zk/ZKHelixManager.java
/** * Copyright (C) 2012 LinkedIn Inc <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.helix.manager.zk; import static com.linkedin.helix.HelixConstants.ChangeType.CONFIG; import static com.linkedin.helix.HelixConstants.ChangeType.CURRENT_STATE; import static com.linkedin.helix.HelixConstants.ChangeType.EXTERNAL_VIEW; import static com.linkedin.helix.HelixConstants.ChangeType.HEALTH; import static com.linkedin.helix.HelixConstants.ChangeType.IDEAL_STATE; import static com.linkedin.helix.HelixConstants.ChangeType.LIVE_INSTANCE; import static com.linkedin.helix.HelixConstants.ChangeType.MESSAGE; import static com.linkedin.helix.HelixConstants.ChangeType.MESSAGES_CONTROLLER; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Timer; import java.util.concurrent.TimeUnit; import org.I0Itec.zkclient.ZkConnection; import org.I0Itec.zkclient.serialize.ZkSerializer; import org.apache.log4j.Logger; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; import com.linkedin.helix.ClusterMessagingService; import com.linkedin.helix.ConfigAccessor; import com.linkedin.helix.ConfigChangeListener; import com.linkedin.helix.ConfigScope.ConfigScopeProperty; import com.linkedin.helix.ControllerChangeListener; import com.linkedin.helix.CurrentStateChangeListener; import com.linkedin.helix.DataAccessor; import com.linkedin.helix.ExternalViewChangeListener; import com.linkedin.helix.HealthStateChangeListener; import com.linkedin.helix.HelixAdmin; import com.linkedin.helix.HelixConstants.ChangeType; import com.linkedin.helix.HelixDataAccessor; import com.linkedin.helix.HelixException; import com.linkedin.helix.HelixManager; import com.linkedin.helix.HelixTimerTask; import com.linkedin.helix.IdealStateChangeListener; import com.linkedin.helix.InstanceType; import com.linkedin.helix.LiveInstanceChangeListener; import com.linkedin.helix.MessageListener; import com.linkedin.helix.PreConnectCallback; import com.linkedin.helix.PropertyKey.Builder; import com.linkedin.helix.PropertyPathConfig; import com.linkedin.helix.PropertyType; import com.linkedin.helix.ZNRecord; import com.linkedin.helix.healthcheck.HealthStatsAggregationTask; import com.linkedin.helix.healthcheck.ParticipantHealthReportCollector; import com.linkedin.helix.healthcheck.ParticipantHealthReportCollectorImpl; import com.linkedin.helix.messaging.DefaultMessagingService; import com.linkedin.helix.messaging.handling.MessageHandlerFactory; import com.linkedin.helix.model.CurrentState; import com.linkedin.helix.model.LiveInstance; import com.linkedin.helix.model.Message.MessageType; import com.linkedin.helix.model.StateModelDefinition; import com.linkedin.helix.monitoring.ZKPathDataDumpTask; import com.linkedin.helix.participant.DistClusterControllerElection; import com.linkedin.helix.participant.HelixStateMachineEngine; import com.linkedin.helix.participant.StateMachineEngine; import com.linkedin.helix.store.PropertyStore; import com.linkedin.helix.store.ZNRecordJsonSerializer; import com.linkedin.helix.store.zk.ZKPropertyStore; import com.linkedin.helix.tools.PropertiesReader; public class ZKHelixManager implements HelixManager { private static Logger logger = Logger.getLogger(ZKHelixManager.class); private static final int RETRY_LIMIT = 3; private static final int CONNECTIONTIMEOUT = 10000; private final String _clusterName; private final String _instanceName; private final String _zkConnectString; private static final int DEFAULT_SESSION_TIMEOUT = 30000; private ZKDataAccessor _accessor; private ZKHelixDataAccessor _helixAccessor; private ConfigAccessor _configAccessor; protected ZkClient _zkClient; private final List<CallbackHandler> _handlers; private final ZkStateChangeListener _zkStateChangeListener; private final InstanceType _instanceType; private String _sessionId; private Timer _timer; private CallbackHandler _leaderElectionHandler; private ParticipantHealthReportCollectorImpl _participantHealthCheckInfoCollector; private final DefaultMessagingService _messagingService; private ZKHelixAdmin _managementTool; private final String _version; private final StateMachineEngine _stateMachEngine; private int _sessionTimeout; private PropertyStore<ZNRecord> _propertyStore; private final List<HelixTimerTask> _controllerTimerTasks; private ZkBaseDataAccessor<ZNRecord> _baseDataAccessor; List<PreConnectCallback> _preConnectCallbacks = new LinkedList<PreConnectCallback>(); public ZKHelixManager(String clusterName, String instanceName, InstanceType instanceType, String zkConnectString) throws Exception { logger.info("Create a zk-based cluster manager. clusterName:" + clusterName + ", instanceName:" + instanceName + ", type:" + instanceType + ", zkSvr:" + zkConnectString); int sessionTimeoutInt = -1; try { sessionTimeoutInt = Integer.parseInt(System.getProperty("zk.session.timeout", "" + DEFAULT_SESSION_TIMEOUT)); } catch (NumberFormatException e) { logger.warn("Exception while parsing session timeout: " + System.getProperty("zk.session.timeout", "" + DEFAULT_SESSION_TIMEOUT)); } if (sessionTimeoutInt > 0) { _sessionTimeout = sessionTimeoutInt; } else { _sessionTimeout = DEFAULT_SESSION_TIMEOUT; } if (instanceName == null) { try { instanceName = InetAddress.getLocalHost().getCanonicalHostName() + "-" + instanceType.toString(); } catch (UnknownHostException e) { // can ignore it logger.info("Unable to get host name. Will set it to UNKNOWN, mostly ignorable", e); instanceName = "UNKNOWN"; } } _clusterName = clusterName; _instanceName = instanceName; _instanceType = instanceType; _zkConnectString = zkConnectString; _zkStateChangeListener = new ZkStateChangeListener(this); _timer = null; _handlers = new ArrayList<CallbackHandler>(); _messagingService = new DefaultMessagingService(this); _version = new PropertiesReader("cluster-manager-version.properties").getProperty("clustermanager.version"); _stateMachEngine = new HelixStateMachineEngine(this); // add all timer tasks _controllerTimerTasks = new ArrayList<HelixTimerTask>(); if (_instanceType == InstanceType.CONTROLLER) { _controllerTimerTasks.add(new HealthStatsAggregationTask(this)); } } private boolean isInstanceSetup() { if (_instanceType == InstanceType.PARTICIPANT || _instanceType == InstanceType.CONTROLLER_PARTICIPANT) { boolean isValid = _zkClient.exists(PropertyPathConfig.getPath(PropertyType.CONFIGS, _clusterName, ConfigScopeProperty.PARTICIPANT.toString(), _instanceName)) && _zkClient.exists(PropertyPathConfig.getPath(PropertyType.MESSAGES, _clusterName, _instanceName)) && _zkClient.exists(PropertyPathConfig.getPath(PropertyType.CURRENTSTATES, _clusterName, _instanceName)) && _zkClient.exists(PropertyPathConfig.getPath(PropertyType.STATUSUPDATES, _clusterName, _instanceName)) && _zkClient.exists(PropertyPathConfig.getPath(PropertyType.ERRORS, _clusterName, _instanceName)); return isValid; } return true; } @Override public void addIdealStateChangeListener(final IdealStateChangeListener listener) throws Exception { logger.info("ClusterManager.addIdealStateChangeListener()"); checkConnected(); final String path = PropertyPathConfig.getPath(PropertyType.IDEALSTATES, _clusterName); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeDataChanged, EventType.NodeDeleted, EventType.NodeCreated }, IDEAL_STATE); // _handlers.add(callbackHandler); addListener(callbackHandler); } @Override public void addLiveInstanceChangeListener(LiveInstanceChangeListener listener) throws Exception { logger.info("ClusterManager.addLiveInstanceChangeListener()"); checkConnected(); final String path = _helixAccessor.keyBuilder().liveInstances().getPath(); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }, LIVE_INSTANCE); // _handlers.add(callbackHandler); addListener(callbackHandler); } @Override public void addConfigChangeListener(ConfigChangeListener listener) { logger.info("ClusterManager.addConfigChangeListener()"); checkConnected(); // final String path = HelixUtil.getConfigPath(_clusterName); final String path = PropertyPathConfig.getPath(PropertyType.CONFIGS, _clusterName, ConfigScopeProperty.PARTICIPANT.toString()); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeChildrenChanged }, CONFIG); // _handlers.add(callbackHandler); addListener(callbackHandler); } // TODO: Decide if do we still need this since we are exposing // ClusterMessagingService @Override public void addMessageListener(MessageListener listener, String instanceName) { logger.info("ClusterManager.addMessageListener() " + instanceName); checkConnected(); final String path = _helixAccessor.keyBuilder().messages(instanceName).getPath(); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }, MESSAGE); // _handlers.add(callbackHandler); addListener(callbackHandler); } void addControllerMessageListener(MessageListener listener) { logger.info("ClusterManager.addControllerMessageListener()"); checkConnected(); final String path = _helixAccessor.keyBuilder().controllerMessages().getPath(); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }, MESSAGES_CONTROLLER); // _handlers.add(callbackHandler); addListener(callbackHandler); } @Override public void addCurrentStateChangeListener(CurrentStateChangeListener listener, String instanceName, String sessionId) { logger.info("ClusterManager.addCurrentStateChangeListener() " + instanceName + " " + sessionId); checkConnected(); final String path = _helixAccessor.keyBuilder().currentStates(instanceName, sessionId).getPath(); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }, CURRENT_STATE); // _handlers.add(callbackHandler); addListener(callbackHandler); } @Override public void addHealthStateChangeListener(HealthStateChangeListener listener, String instanceName) { // System.out.println("ZKClusterManager.addHealthStateChangeListener()"); // TODO: re-form this for stats checking logger.info("ClusterManager.addHealthStateChangeListener()" + instanceName); checkConnected(); final String path = _helixAccessor.keyBuilder().healthReports(instanceName).getPath(); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDataChanged, EventType.NodeDeleted, EventType.NodeCreated }, HEALTH); // _handlers.add(callbackHandler); addListener(callbackHandler); } @Override public void addExternalViewChangeListener(ExternalViewChangeListener listener) { logger.info("ClusterManager.addExternalViewChangeListener()"); checkConnected(); final String path = _helixAccessor.keyBuilder().externalViews().getPath(); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeDataChanged, EventType.NodeDeleted, EventType.NodeCreated }, EXTERNAL_VIEW); // _handlers.add(callbackHandler); addListener(callbackHandler); } @Override public DataAccessor getDataAccessor() { checkConnected(); return _accessor; } @Override public HelixDataAccessor getHelixDataAccessor() { checkConnected(); return _helixAccessor; } @Override public ConfigAccessor getConfigAccessor() { checkConnected(); return _configAccessor; } @Override public String getClusterName() { return _clusterName; } @Override public String getInstanceName() { return _instanceName; } @Override public void connect() throws Exception { logger.info("ClusterManager.connect()"); if (_zkStateChangeListener.isConnected()) { logger.warn("Cluster manager " + _clusterName + " " + _instanceName + " already connected"); return; } try { createClient(_zkConnectString); _messagingService.registerMessageHandlerFactory(MessageType.STATE_TRANSITION.toString(), _stateMachEngine); } catch (Exception e) { logger.error(e); disconnect(); throw e; } } @Override public void disconnect() { if (!isConnected()) { logger.warn("ClusterManager " + _instanceName + " already disconnected"); return; } logger.info("disconnect " + _instanceName + "(" + _instanceType + ") from " + _clusterName); /** * shutdown thread pool first to avoid reset() being invoked in the middle of state * transition */ _messagingService.getExecutor().shutDown(); resetHandlers(); if (_leaderElectionHandler != null) { _leaderElectionHandler.reset(); } if (_participantHealthCheckInfoCollector != null) { _participantHealthCheckInfoCollector.stop(); } if (_timer != null) { _timer.cancel(); _timer = null; } if (_instanceType == InstanceType.CONTROLLER) { stopTimerTasks(); } _zkClient.close(); // HACK seems that zkClient is not sending DISCONNECT event _zkStateChangeListener.disconnect(); logger.info("Cluster manager: " + _instanceName + " disconnected"); } @Override public String getSessionId() { checkConnected(); return _sessionId; } @Override public boolean isConnected() { return _zkStateChangeListener.isConnected(); } @Override public long getLastNotificationTime() { return -1; } @Override public void addControllerListener(ControllerChangeListener listener) { checkConnected(); final String path = _helixAccessor.keyBuilder().controller().getPath(); logger.info("Add controller listener at: " + path); CallbackHandler callbackHandler = createCallBackHandler(path, listener, new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }, ChangeType.CONTROLLER); // System.out.println("add controller listeners to " + _instanceName + // " for " + _clusterName); // _handlers.add(callbackHandler); addListener(callbackHandler); } @Override public boolean removeListener(Object listener) { logger.info("remove listener: " + listener + " from " + _instanceName); synchronized (this) { Iterator<CallbackHandler> iterator = _handlers.iterator(); while (iterator.hasNext()) { CallbackHandler handler = iterator.next(); // simply compare reference if (handler.getListener().equals(listener)) { handler.reset(); iterator.remove(); } } } return true; } private void addLiveInstance() { LiveInstance liveInstance = new LiveInstance(_instanceName); liveInstance.setSessionId(_sessionId); liveInstance.setHelixVersion(_version); liveInstance.setLiveInstance(ManagementFactory.getRuntimeMXBean().getName()); logger.info("Add live instance: InstanceName: " + _instanceName + " Session id:" + _sessionId); // if (!_accessor.setProperty(PropertyType.LIVEINSTANCES, liveInstance, // _instanceName)) Builder keyBuilder = _helixAccessor.keyBuilder(); if (!_helixAccessor.setProperty(keyBuilder.liveInstance(_instanceName), liveInstance)) { String errorMsg = "Fail to create live instance node after waiting, so quit. instance:" + _instanceName; logger.warn(errorMsg); throw new HelixException(errorMsg); } String currentStatePathParent = PropertyPathConfig.getPath(PropertyType.CURRENTSTATES, _clusterName, _instanceName, getSessionId()); if (!_zkClient.exists(currentStatePathParent)) { _zkClient.createPersistent(currentStatePathParent); logger.info("Creating current state path " + currentStatePathParent); } } private void startStatusUpdatedumpTask() { long initialDelay = 30 * 60 * 1000; long period = 120 * 60 * 1000; int timeThresholdNoChange = 180 * 60 * 1000; if (_timer == null) { _timer = new Timer(); _timer.scheduleAtFixedRate(new ZKPathDataDumpTask(this, _zkClient, timeThresholdNoChange), initialDelay, period); } } private void createClient(String zkServers) throws Exception { ZkSerializer zkSerializer = new ZNRecordSerializer(); _zkClient = new ZkClient(zkServers, _sessionTimeout, CONNECTIONTIMEOUT, zkSerializer); _accessor = new ZKDataAccessor(_clusterName, _zkClient); _baseDataAccessor = new ZkBaseDataAccessor<ZNRecord>(_zkClient); _helixAccessor = new ZKHelixDataAccessor(_clusterName, _baseDataAccessor); _configAccessor = new ConfigAccessor(_zkClient); int retryCount = 0; _zkClient.subscribeStateChanges(_zkStateChangeListener); while (retryCount < RETRY_LIMIT) { try { _zkClient.waitUntilConnected(_sessionTimeout, TimeUnit.MILLISECONDS); _zkStateChangeListener.handleStateChanged(KeeperState.SyncConnected); _zkStateChangeListener.handleNewSession(); break; } catch (HelixException e) { logger.error("fail to createClient.", e); throw e; } catch (Exception e) { retryCount++; logger.error("fail to createClient. retry " + retryCount, e); if (retryCount == RETRY_LIMIT) { throw e; } } } } private CallbackHandler createCallBackHandler(String path, Object listener, EventType[] eventTypes, ChangeType changeType) { if (listener == null) { throw new HelixException("Listener cannot be null"); } return new CallbackHandler(this, _zkClient, path, listener, eventTypes, changeType); } /** * This will be invoked when ever a new session is created<br/> * * case 1: the cluster manager was a participant carry over current state, add live * instance, and invoke message listener; case 2: the cluster manager was controller and * was a leader before do leader election, and if it becomes leader again, invoke ideal * state listener, current state listener, etc. if it fails to become leader in the new * session, then becomes standby; case 3: the cluster manager was controller and was NOT * a leader before do leader election, and if it becomes leader, instantiate and invoke * ideal state listener, current state listener, etc. if if fails to become leader in * the new session, stay as standby */ protected void handleNewSession() { ZkConnection zkConnection = ((ZkConnection) _zkClient.getConnection()); _sessionId = Long.toHexString(zkConnection.getZookeeper().getSessionId()); // UUID.randomUUID().toString(); _accessor.reset(); resetHandlers(); logger.info("Handling new session, session id:" + _sessionId + ", instance:" + _instanceName); if (!ZKUtil.isClusterSetup(_clusterName, _zkClient)) { throw new HelixException("Initial cluster structure is not set up for cluster:" + _clusterName); } if (!isInstanceSetup()) { throw new HelixException("Initial cluster structure is not set up for instance:" + _instanceName + " instanceType:" + _instanceType); } if (_instanceType == InstanceType.PARTICIPANT || _instanceType == InstanceType.CONTROLLER_PARTICIPANT) { handleNewSessionAsParticipant(); } if (_instanceType == InstanceType.CONTROLLER || _instanceType == InstanceType.CONTROLLER_PARTICIPANT) { addControllerMessageListener(_messagingService.getExecutor()); MessageHandlerFactory defaultControllerMsgHandlerFactory = new DefaultControllerMessageHandlerFactory(); _messagingService.getExecutor() .registerMessageHandlerFactory(defaultControllerMsgHandlerFactory.getMessageType(), defaultControllerMsgHandlerFactory); MessageHandlerFactory defaultSchedulerMsgHandlerFactory = new DefaultSchedulerMessageHandlerFactory(this); _messagingService.getExecutor() .registerMessageHandlerFactory(defaultSchedulerMsgHandlerFactory.getMessageType(), defaultSchedulerMsgHandlerFactory); startStatusUpdatedumpTask(); if (_leaderElectionHandler == null) { final String path = PropertyPathConfig.getPath(PropertyType.CONTROLLER, _clusterName); _leaderElectionHandler = createCallBackHandler(path, new DistClusterControllerElection(_zkConnectString), new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }, ChangeType.CONTROLLER); } else { _leaderElectionHandler.init(); } } if (_instanceType == InstanceType.PARTICIPANT || _instanceType == InstanceType.CONTROLLER_PARTICIPANT || (_instanceType == InstanceType.CONTROLLER && isLeader())) { initHandlers(); } } private void handleNewSessionAsParticipant() { // In case there is a live instance record on zookeeper Builder keyBuilder = _helixAccessor.keyBuilder(); if (_helixAccessor.getProperty(keyBuilder.liveInstance(_instanceName)) != null) { logger.warn("Found another instance with same instanceName: " + _instanceName + " in cluster " + _clusterName); // Wait for a while, in case previous storage node exits unexpectedly // and its liveinstance // still hangs around until session timeout happens try { Thread.sleep(_sessionTimeout + 5000); } catch (InterruptedException e) { logger.warn("Sleep interrupted while waiting for previous liveinstance to go away.", e); } if (_helixAccessor.getProperty(keyBuilder.liveInstance(_instanceName)) != null) { String errorMessage = "instance " + _instanceName + " already has a liveinstance in cluster " + _clusterName; logger.error(errorMessage); throw new HelixException(errorMessage); } } // Invoke the PreConnectCallbacks for (PreConnectCallback callback : _preConnectCallbacks) { callback.onPreConnect(); } addLiveInstance(); carryOverPreviousCurrentState(); // In case the cluster manager is running as a participant, setup message // listener addMessageListener(_messagingService.getExecutor(), _instanceName); if (_participantHealthCheckInfoCollector == null) { _participantHealthCheckInfoCollector = new ParticipantHealthReportCollectorImpl(this, _instanceName); _participantHealthCheckInfoCollector.start(); } // start the participant health check timer, also create zk path for health // check info String healthCheckInfoPath = _helixAccessor.keyBuilder().healthReports(_instanceName).getPath(); if (!_zkClient.exists(healthCheckInfoPath)) { _zkClient.createPersistent(healthCheckInfoPath); logger.info("Creating healthcheck info path " + healthCheckInfoPath); } } @Override public void addPreConnectCallback(PreConnectCallback callback) { logger.info("Adding preconnect callback"); _preConnectCallbacks.add(callback); } private void resetHandlers() { synchronized (this) { for (CallbackHandler handler : _handlers) { handler.reset(); logger.info("reset handler: " + handler.getPath() + " by " + Thread.currentThread().getName()); } } } private void initHandlers() { synchronized (this) { for (CallbackHandler handler : _handlers) { handler.init(); } } } private void addListener(CallbackHandler handler) { synchronized (this) { _handlers.add(handler); logger.info("add handler: " + handler.getPath() + " by " + Thread.currentThread().getName()); } } @Override public boolean isLeader() { if (!isConnected()) { return false; } if (_instanceType != InstanceType.CONTROLLER) { return false; } Builder keyBuilder = _helixAccessor.keyBuilder(); LiveInstance leader = _helixAccessor.getProperty(keyBuilder.controllerLeader()); if (leader == null) { return false; } else { String leaderName = leader.getInstanceName(); // TODO need check sessionId also, but in distributed mode, leader's // sessionId is // not equal to // the leader znode's sessionId field which is the sessionId of the // controller_participant that // successfully creates the leader node if (leaderName == null || !leaderName.equals(_instanceName)) { return false; } } return true; } private void carryOverPreviousCurrentState() { Builder keyBuilder = _helixAccessor.keyBuilder(); List<String> subPaths = _helixAccessor.getChildNames(keyBuilder.sessions(_instanceName)); for (String previousSessionId : subPaths) { List<CurrentState> previousCurrentStates = _helixAccessor.getChildValues(keyBuilder.currentStates(_instanceName, previousSessionId)); for (CurrentState previousCurrentState : previousCurrentStates) { if (!previousSessionId.equalsIgnoreCase(_sessionId)) { logger.info("Carrying over old session:" + previousSessionId + " resource " + previousCurrentState.getId() + " to new session:" + _sessionId); String stateModelDefRef = previousCurrentState.getStateModelDefRef(); if (stateModelDefRef == null) { logger.error("pervious current state doesn't have a state model def. skip it. prevCS: " + previousCurrentState); continue; } StateModelDefinition stateModel = _helixAccessor.getProperty(keyBuilder.stateModelDef(stateModelDefRef)); for (String partitionName : previousCurrentState.getPartitionStateMap() .keySet()) { previousCurrentState.setState(partitionName, stateModel.getInitialState()); } previousCurrentState.setSessionId(_sessionId); _helixAccessor.setProperty(keyBuilder.currentState(_instanceName, _sessionId, previousCurrentState.getId()), previousCurrentState); } } } // Deleted old current state for (String previousSessionId : subPaths) { if (!previousSessionId.equalsIgnoreCase(_sessionId)) { String path = _helixAccessor.keyBuilder() .currentStates(_instanceName, previousSessionId) .getPath(); logger.info("Deleting previous current state. path: " + path + "/" + previousSessionId); _zkClient.deleteRecursive(path); } } } @Override public synchronized PropertyStore<ZNRecord> getPropertyStore() { checkConnected(); if (_propertyStore == null) { String path = PropertyPathConfig.getPath(PropertyType.PROPERTYSTORE, _clusterName); // property store uses a different serializer ZkClient zkClient = new ZkClient(_zkConnectString, CONNECTIONTIMEOUT); _propertyStore = new ZKPropertyStore<ZNRecord>(zkClient, new ZNRecordJsonSerializer(), path); } return _propertyStore; } @Override public synchronized HelixAdmin getClusterManagmentTool() { checkConnected(); if (_zkClient != null) { _managementTool = new ZKHelixAdmin(_zkClient); } else { logger.error("Couldn't get ZKClusterManagementTool because zkClient is null"); } return _managementTool; } @Override public ClusterMessagingService getMessagingService() { checkConnected(); return _messagingService; } @Override public ParticipantHealthReportCollector getHealthReportCollector() { checkConnected(); return _participantHealthCheckInfoCollector; } @Override public InstanceType getInstanceType() { return _instanceType; } private void checkConnected() { if (!isConnected()) { throw new HelixException("ClusterManager not connected. Call clusterManager.connect()"); } } @Override public String getVersion() { return _version; } @Override public StateMachineEngine getStateMachineEngine() { return _stateMachEngine; } protected List<CallbackHandler> getHandlers() { return _handlers; } @Override public void startTimerTasks() { for (HelixTimerTask task : _controllerTimerTasks) { task.start(); } } @Override public void stopTimerTasks() { for (HelixTimerTask task : _controllerTimerTasks) { task.stop(); } } }
LiveInstance should use createProperty() instead of setProperty() after data accessor refactoring
helix-core/src/main/java/com/linkedin/helix/manager/zk/ZKHelixManager.java
LiveInstance should use createProperty() instead of setProperty() after data accessor refactoring
Java
apache-2.0
b27a14d6ece3f5094f47ebf824eb3ae7db76fd6d
0
nethergrim/bashorg
package com.nethergrim.bashorg.fragment; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.nethergrim.bashorg.R; import com.nethergrim.bashorg.adapter.QuoteCursorAdapter; import com.nethergrim.bashorg.loaders.LastQuotesCursorLoader; /** * Created by nethergrim on 01.12.2014. */ public class LastQuotesFragment extends AbstractFragment implements LoaderManager.LoaderCallbacks<Cursor>, SwipeRefreshLayout.OnRefreshListener { private SwipeRefreshLayout refreshLayout; private QuoteCursorAdapter adapter; private static final int LOADER_CODE = 117; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_last_quotes, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe); refreshLayout.setOnRefreshListener(this); refreshLayout.setColorSchemeResources(R.color.main_color, R.color.accent, R.color.main_color, R.color.accent); ListView listView = (ListView) view.findViewById(R.id.recycler_view); adapter = new QuoteCursorAdapter(getActivity(), null); listView.setAdapter(adapter); // listView.setOnScrollListener(new Scroller(onTopBarHeightListener)); loadData(); } private void loadData() { if (getLoaderManager().getLoader(LOADER_CODE) == null) { getLoaderManager().initLoader(LOADER_CODE, null, this); } getLoaderManager().getLoader(LOADER_CODE).forceLoad(); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new LastQuotesCursorLoader(getActivity()); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { adapter.swapCursor(data); refreshLayout.setRefreshing(false); } @Override public void onLoaderReset(Loader<Cursor> loader) { adapter.swapCursor(null); } @Override public void onRefresh() { loadData(); } }
app/src/main/java/com/nethergrim/bashorg/fragment/LastQuotesFragment.java
package com.nethergrim.bashorg.fragment; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.nethergrim.bashorg.R; import com.nethergrim.bashorg.adapter.QuoteCursorAdapter; import com.nethergrim.bashorg.loaders.LastQuotesCursorLoader; import com.nethergrim.bashorg.views.Scroller; /** * Created by nethergrim on 01.12.2014. */ public class LastQuotesFragment extends AbstractFragment implements LoaderManager.LoaderCallbacks<Cursor>, SwipeRefreshLayout.OnRefreshListener { private SwipeRefreshLayout refreshLayout; private QuoteCursorAdapter adapter; private static final int LOADER_CODE = 117; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_last_quotes, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe); refreshLayout.setOnRefreshListener(this); refreshLayout.setColorSchemeResources(R.color.main_color, R.color.accent, R.color.main_color, R.color.accent); ListView listView = (ListView) view.findViewById(R.id.recycler_view); adapter = new QuoteCursorAdapter(getActivity(), null); listView.setAdapter(adapter); listView.setOnScrollListener(new Scroller(onTopBarHeightListener)); loadData(); } private void loadData() { if (getLoaderManager().getLoader(LOADER_CODE) == null) { getLoaderManager().initLoader(LOADER_CODE, null, this); } getLoaderManager().getLoader(LOADER_CODE).forceLoad(); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new LastQuotesCursorLoader(getActivity()); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { adapter.swapCursor(data); refreshLayout.setRefreshing(false); } @Override public void onLoaderReset(Loader<Cursor> loader) { adapter.swapCursor(null); } @Override public void onRefresh() { loadData(); } }
removed scroller
app/src/main/java/com/nethergrim/bashorg/fragment/LastQuotesFragment.java
removed scroller
Java
apache-2.0
4eb61ccf0dd28bf1f0550a30d6b402d1457b7c9a
0
manstis/gwtbootstrap3-extras,bauna/gwtbootstrap3-extras,sjardine/gwtbootstrap3-extras,gwtbootstrap3/gwtbootstrap3-extras,gwtbootstrap3/gwtbootstrap3-extras,markonikolic/gwtbootstrap3-extras,crevete/gwtbootstrap3-extras,manstis/gwtbootstrap3-extras,BenDol/gwtbootstrap3-extras,bauna/gwtbootstrap3-extras,crevete/gwtbootstrap3-extras,bauna/gwtbootstrap3-extras,denis-vilyuzhanin/gwtbootstrap3-extras,markonikolic/gwtbootstrap3-extras,denis-vilyuzhanin/gwtbootstrap3-extras,denis-vilyuzhanin/gwtbootstrap3-extras,markonikolic/gwtbootstrap3-extras,BenDol/gwtbootstrap3-extras,sjardine/gwtbootstrap3-extras,BenDol/gwtbootstrap3-extras,crevete/gwtbootstrap3-extras,manstis/gwtbootstrap3-extras,sjardine/gwtbootstrap3-extras,gwtbootstrap3/gwtbootstrap3-extras
package org.gwtbootstrap3.extras.notify.client; /* * #%L * GwtBootstrap3 * %% * Copyright (C) 2013 - 2015 GwtBootstrap3 * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.ScriptInjector; public class NotifyEntryPoint implements EntryPoint { @Override public void onModuleLoad() { if (!isNotifyLoaded()) { ScriptInjector.fromString(NotifyClientBundle.INSTANCE.notifyJS().getText()).setWindow(ScriptInjector.TOP_WINDOW).inject(); } } /** * Check if notify is already loaded. * * @return <code>true</code> if notify is loaded, <code>false</code> otherwise */ private native boolean isNotifyLoaded() /*-{ if ($wnd.jQuery && $wnd.jQuery.notify) { return true; } else { return false; } }-*/; }
src/main/java/org/gwtbootstrap3/extras/notify/client/NotifyEntryPoint.java
package org.gwtbootstrap3.extras.notify.client; /* * #%L * GwtBootstrap3 * %% * Copyright (C) 2013 - 2015 GwtBootstrap3 * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.ScriptInjector; public class NotifyEntryPoint implements EntryPoint { @Override public void onModuleLoad() { if (!isNotifyLoaded()) { ScriptInjector.fromString(NotifyClientBundle.INSTANCE.notifyJS().getText()).setWindow(ScriptInjector.TOP_WINDOW).inject(); } } /** * Check if notify is already loaded. * * @return <code>true</code> if notify is loaded, <code>false</code> otherwise */ private native boolean isNotifyLoaded() /*-{ return ($wnd.jQuery && $wnd.jQuery.notify); }-*/; }
Fixed exception when in DevMode (issue #176)
src/main/java/org/gwtbootstrap3/extras/notify/client/NotifyEntryPoint.java
Fixed exception when in DevMode (issue #176)
Java
apache-2.0
b198753f48b5a4ee95fe41f3f02e3870b30a207d
0
konradxyz/cloudify-manager,konradxyz/dev_fileserver,geokala/cloudify-manager,isaac-s/cloudify-manager,codilime/cloudify-manager,codilime/cloudify-manager,konradxyz/dev_fileserver,codilime/cloudify-manager,isaac-s/cloudify-manager,geokala/cloudify-manager,cloudify-cosmo/cloudify-manager,cloudify-cosmo/cloudify-manager,isaac-s/cloudify-manager,konradxyz/cloudify-manager,cloudify-cosmo/cloudify-manager
package org.openspaces.servicegrid; import java.net.URI; import java.net.URISyntaxException; import java.text.DecimalFormat; import java.util.Comparator; import java.util.Set; import java.util.logging.Logger; import org.codehaus.jackson.map.ObjectMapper; import org.openspaces.servicegrid.agent.state.AgentState; import org.openspaces.servicegrid.client.ServiceClient; import org.openspaces.servicegrid.mock.MockEmbeddedAgentLifecycleTaskExecutor; import org.openspaces.servicegrid.mock.MockImmediateMachineSpawnerTaskExecutor; import org.openspaces.servicegrid.mock.MockStreams; import org.openspaces.servicegrid.mock.MockTaskContainer; import org.openspaces.servicegrid.mock.TaskExecutorWrapper; import org.openspaces.servicegrid.service.OrchestrateTask; import org.openspaces.servicegrid.service.ServiceGridOrchestrator; import org.openspaces.servicegrid.service.ServiceGridOrchestratorParameter; import org.openspaces.servicegrid.service.ServiceGridPlanner; import org.openspaces.servicegrid.service.ServiceGridPlannerParameter; import org.openspaces.servicegrid.service.ServiceUtils; import org.openspaces.servicegrid.service.state.ServiceConfig; import org.openspaces.servicegrid.service.state.ServiceGridOrchestratorState; import org.openspaces.servicegrid.service.state.ServiceInstanceState; import org.openspaces.servicegrid.service.state.ServiceState; import org.openspaces.servicegrid.service.tasks.InstallServiceTask; import org.openspaces.servicegrid.service.tasks.ScaleOutServiceTask; import org.openspaces.servicegrid.streams.StreamConsumer; import org.openspaces.servicegrid.streams.StreamProducer; import org.openspaces.servicegrid.time.MockCurrentTimeProvider; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.log.TextFormatter; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; public class ServiceGridOrchestrationTest { private ServiceClient client; private Set<MockTaskContainer> containers; private URI orchestratorExecutorId; private URI plannerExecutorId; private MockTaskContainer orchestratorContainer; private MockStreams<TaskExecutorState> state; private StreamConsumer<Task> taskConsumer; private final Logger logger; private MockStreams<Task> taskBroker; private MockCurrentTimeProvider timeProvider; public ServiceGridOrchestrationTest() { logger = Logger.getLogger(this.getClass().getName()); Logger parentLogger = logger; while (parentLogger.getHandlers().length == 0) { parentLogger = logger.getParent(); } parentLogger.getHandlers()[0].setFormatter(new TextFormatter()); } @BeforeMethod public void before() { timeProvider = new MockCurrentTimeProvider(); final URI cloudExecutorId; final URI agentLifecycleExecutorId; try { orchestratorExecutorId = new URI("http://localhost/services/orchestrator/"); plannerExecutorId = new URI("http://localhost/services/planner/"); cloudExecutorId = new URI("http://localhost/services/cloud/"); agentLifecycleExecutorId = new URI("http://localhost/services/agentLifecycle/"); } catch (URISyntaxException e) { throw Throwables.propagate(e); } state = new MockStreams<TaskExecutorState>(); StreamProducer<TaskExecutorState> stateWriter = state; StreamConsumer<TaskExecutorState> stateReader = state; this.taskBroker = new MockStreams<Task>(); StreamProducer<Task> taskProducer = taskBroker; taskConsumer = taskBroker; stateWriter.addElement(orchestratorExecutorId, new ServiceGridOrchestratorState()); client = new ServiceClient(stateReader, taskConsumer, taskProducer); final ServiceGridOrchestratorParameter serviceOrchestratorParameter = new ServiceGridOrchestratorParameter(); serviceOrchestratorParameter.setOrchestratorExecutorId(orchestratorExecutorId); serviceOrchestratorParameter.setCloudExecutorId(cloudExecutorId); serviceOrchestratorParameter.setAgentLifecycleExecutorId(agentLifecycleExecutorId); serviceOrchestratorParameter.setPlannerExecutorId(plannerExecutorId); serviceOrchestratorParameter.setTaskConsumer(taskConsumer); serviceOrchestratorParameter.setTaskProducer(taskProducer); serviceOrchestratorParameter.setStateReader(stateReader); serviceOrchestratorParameter.setTimeProvider(timeProvider); orchestratorContainer = new MockTaskContainer( orchestratorExecutorId, stateReader, stateWriter, taskConsumer, new ServiceGridOrchestrator( serviceOrchestratorParameter), timeProvider); final ServiceGridPlannerParameter servicePlannerParameter = new ServiceGridPlannerParameter(); servicePlannerParameter.setPlannerExecutorId(plannerExecutorId); servicePlannerParameter.setTaskConsumer(taskConsumer); servicePlannerParameter.setTaskProducer(taskProducer); servicePlannerParameter.setStateReader(stateReader); servicePlannerParameter.setTimeProvider(timeProvider); containers = Sets.newCopyOnWriteArraySet(); addContainers( orchestratorContainer, new MockTaskContainer( plannerExecutorId, stateReader, stateWriter, taskConsumer, new ServiceGridPlanner(servicePlannerParameter), timeProvider), new MockTaskContainer( cloudExecutorId, stateReader, stateWriter, taskConsumer, new MockImmediateMachineSpawnerTaskExecutor(), timeProvider), new MockTaskContainer( agentLifecycleExecutorId, stateReader, stateWriter, taskConsumer, new MockEmbeddedAgentLifecycleTaskExecutor(new TaskExecutorWrapper() { @Override public void wrapTaskExecutor( final Object taskExecutor, final URI executorId) { MockTaskContainer container = new MockTaskContainer(executorId, state, state, taskConsumer, taskExecutor, timeProvider); addContainer(container); } @Override public void removeTaskExecutor(final URI executorId) { containers.remove( Iterables.find(containers, new Predicate<MockTaskContainer>() { @Override public boolean apply(MockTaskContainer executor) { return executorId.equals(executor.getExecutorId()); } }) ); } } ), timeProvider) ); } private void addContainers(MockTaskContainer ... newContainers) { for (MockTaskContainer container : newContainers) { addContainer(container); } } private void addContainer(MockTaskContainer container) { //logger.info("Adding container for " + container.getExecutorId()); Preconditions.checkState(!containers.contains(container), "Container " + container.getExecutorId() + " was already added"); containers.add(container); } @AfterMethod public void after() throws URISyntaxException { //Iterable<Task> tasks = filterOrchestratorTasks(getSortedTasks()); Iterable<Task> tasks = getSortedTasks(); for (final Task task : tasks) { DecimalFormat timestampFormatter = new DecimalFormat("###,###"); Long sourceTimestamp = task.getSourceTimestamp(); String timestamp = ""; if (sourceTimestamp != null) { timestamp = timestampFormatter.format(sourceTimestamp); } logger.info(String.format("%-8s%-30starget: %s",timestamp,task.getClass().getSimpleName(),task.getTarget())); } } Iterable<Task> filterOrchestratorTasks(Iterable<Task> unfiltered) { return Iterables.filter(unfiltered, new Predicate<Task>(){ @Override public boolean apply(Task task) { return orchestratorExecutorId.equals(task.getSource()); }}); } private Iterable<Task> getSortedTasks() throws URISyntaxException { final Iterable<URI> taskExecutorIds = taskBroker.getElementIdsStartingWith(new URI("http://localhost/")); Set<Task> sortedTasks = Sets.newTreeSet( new Comparator<Task>() { private final ObjectMapper mapper = new ObjectMapper(); @Override public int compare(Task o1, Task o2) { int c; if (o1.getSourceTimestamp() == null) c = 1; else if (o2.getSourceTimestamp() == null) c = -1; else { c = o1.getSourceTimestamp().compareTo(o2.getSourceTimestamp()); if (c == 0) { try { c = mapper.writeValueAsString(o1).compareTo(mapper.writeValueAsString(o2)); } catch (Throwable t) { throw Throwables.propagate(t); } } } return c; } }); for (final URI executorId : taskExecutorIds) { for (URI taskId = taskBroker.getFirstElementId(executorId); taskId != null ; taskId = taskBroker.getNextElementId(taskId)) { final Task task = taskBroker.getElement(taskId, Task.class); sortedTasks.add(task); } } return sortedTasks; } @Test public void installSingleInstanceServiceTest() throws URISyntaxException { logger.info("Starting installSingleInstanceServiceTest URIs: " + state.getElementIdsStartingWith(new URI("http://localhost/"))); installService("tomcat", 1); execute(); URI serviceId = getServiceId("tomcat"); final ServiceState serviceState = state.getElement(state.getLastElementId(serviceId), ServiceState.class); Assert.assertEquals(Iterables.size(serviceState.getInstanceIds()),1); logger.info("URIs: " + state.getElementIdsStartingWith(new URI("http://localhost/"))); URI instanceId = getOnlyServiceInstanceId(); URI agentId = getOnlyAgentId(); ServiceInstanceState instanceState = getServiceInstanceState(instanceId); Assert.assertEquals(instanceState.getServiceId(), serviceId); Assert.assertEquals(instanceState.getAgentId(), agentId); Assert.assertEquals(instanceState.getProgress(), ServiceInstanceState.Progress.INSTANCE_STARTED); AgentState agentState = getAgentState(agentId); Assert.assertEquals(Iterables.getOnlyElement(agentState.getServiceInstanceIds()),instanceId); Assert.assertEquals(agentState.getProgress(), AgentState.Progress.AGENT_STARTED); Assert.assertEquals(agentState.getNumberOfRestarts(), 0); } private URI getOnlyAgentId() throws URISyntaxException { return Iterables.getOnlyElement(getAgentIds()); } @Test public void installMultipleInstanceServiceTest() throws URISyntaxException { logger.info("Starting installMultipleInstanceServiceTest"); installService("tomcat", 2); execute(); assertTwoTomcatInstances(); } @Test public void agentFailoverTest() throws URISyntaxException { logger.info("Starting agentFailoverTest"); installService("tomcat", 1); execute(); killOnlyAgent(); execute(); URI instanceId = getOnlyServiceInstanceId(); ServiceInstanceState instanceState = getServiceInstanceState(instanceId); Assert.assertEquals(instanceState.getProgress(), ServiceInstanceState.Progress.INSTANCE_STARTED); AgentState agentState = getAgentState(getOnlyAgentId()); Assert.assertEquals(Iterables.getOnlyElement(agentState.getServiceInstanceIds()),instanceId); Assert.assertEquals(agentState.getProgress(),AgentState.Progress.AGENT_STARTED); Assert.assertEquals(agentState.getNumberOfRestarts(),1); } @Test public void scaleOutServiceTest() throws URISyntaxException { logger.info("Starting installSingleInstanceServiceTest URIs: " + state.getElementIdsStartingWith(new URI("http://localhost/"))); installService("tomcat", 1); execute(); scaleOutService("tomcat",2); execute(); assertTwoTomcatInstances(); } private void assertTwoTomcatInstances() throws URISyntaxException { final URI serviceId = getServiceId("tomcat"); final ServiceState serviceState = state.getElement(state.getLastElementId(serviceId), ServiceState.class); Assert.assertEquals(Iterables.size(serviceState.getInstanceIds()),2); logger.info("URIs: " + state.getElementIdsStartingWith(new URI("http://localhost/"))); Iterable<URI> instanceIds = state.getElementIdsStartingWith(new URI("http://localhost/services/tomcat/instances/")); Assert.assertEquals(Iterables.size(instanceIds),2); Iterable<URI> agentIds = getAgentIds(); int numberOfAgents = Iterables.size(agentIds); Assert.assertEquals(numberOfAgents, 2); for (int i = 0 ; i < numberOfAgents; i++) { URI agentId = Iterables.get(agentIds, i); AgentState agentState = getAgentState(agentId); Assert.assertEquals(agentState.getProgress(), AgentState.Progress.AGENT_STARTED); Assert.assertEquals(agentState.getNumberOfRestarts(), 0); URI instanceId = Iterables.getOnlyElement(agentState.getServiceInstanceIds()); Assert.assertTrue(Iterables.contains(instanceIds, instanceId)); ServiceInstanceState instanceState = state.getElement(state.getLastElementId(instanceId), ServiceInstanceState.class); Assert.assertEquals(instanceState.getServiceId(), serviceId); Assert.assertEquals(instanceState.getAgentId(), agentId); Assert.assertEquals(instanceState.getProgress(), ServiceInstanceState.Progress.INSTANCE_STARTED); } } /*public void installTwoSingleInstanceServicesTest(){ installService("tomcat", 1); installService("cassandra", 1); execute(); }*/ // public void uninstallSingleInstanceServiceTest(){ // installService(1); // execute(); // // } private AgentState getAgentState(URI agentId) { return getLastState(agentId, AgentState.class); } private ServiceInstanceState getServiceInstanceState(URI instanceId) throws URISyntaxException { return getLastState(instanceId, ServiceInstanceState.class); } private <T extends TaskExecutorState> T getLastState(URI executorId, Class<T> stateClass) { T lastState = ServiceUtils.getLastState(state, executorId, stateClass); Assert.assertNotNull(lastState); return lastState; } private void installService(String name, int numberOfInstances) throws URISyntaxException { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setDisplayName(name); serviceConfig.setPlannedNumberOfInstances(numberOfInstances); serviceConfig.setServiceId(getServiceId(name)); final InstallServiceTask installServiceTask = new InstallServiceTask(); installServiceTask.setServiceConfig(serviceConfig); client.addServiceTask(orchestratorExecutorId, installServiceTask); } private void scaleOutService(String serviceName, int plannedNumberOfInstances) throws URISyntaxException { final ScaleOutServiceTask scaleOutServiceTask = new ScaleOutServiceTask(); URI serviceId = getServiceId(serviceName); scaleOutServiceTask.setServiceId(serviceId); scaleOutServiceTask.setPlannedNumberOfInstances(plannedNumberOfInstances); client.addServiceTask(orchestratorExecutorId, scaleOutServiceTask); } private URI getServiceId(String name) throws URISyntaxException { return new URI("http://localhost/services/" + name + "/"); } private void execute() throws URISyntaxException { int consecutiveEmptyCycles = 0; for (; timeProvider.currentTimeMillis() < 300000; timeProvider.increaseBy(1000)) { boolean emptyCycle = true; OrchestrateTask orchestrateTask = new OrchestrateTask(); orchestrateTask.setMaxNumberOfOrchestrationSteps(100); client.addServiceTask(orchestratorExecutorId, orchestrateTask); for (MockTaskContainer container : containers) { Assert.assertEquals(container.getExecutorId().getHost(),"localhost"); while (container.stepTaskExecutor()) { if (!container.getExecutorId().equals(orchestratorExecutorId)) { emptyCycle = false; } } } if (emptyCycle) { consecutiveEmptyCycles++; } if (consecutiveEmptyCycles > 60) { return; } } StringBuilder sb = new StringBuilder(); Iterable<URI> servicesIds = state.getElementIdsStartingWith(new URI("http://services/")); for (URI URI : servicesIds) { ServiceState serviceState = state.getElement(state.getLastElementId(URI), ServiceState.class); sb.append("service: " + serviceState.getServiceConfig().getDisplayName()); sb.append(" - "); for (URI instanceURI : serviceState.getInstanceIds()) { ServiceInstanceState instanceState = state.getElement(state.getLastElementId(instanceURI), ServiceInstanceState.class); sb.append(instanceURI).append("[").append(instanceState.getProgress()).append("] "); } } Assert.fail("Executing too many cycles progress=" + sb); } private URI getOnlyServiceInstanceId() throws URISyntaxException { final Iterable<URI> instanceIds = state.getElementIdsStartingWith(new URI("http://localhost/services/tomcat/instances/")); Assert.assertEquals(Iterables.size(instanceIds),1); final URI serviceInstanceId = Iterables.getOnlyElement(instanceIds); return serviceInstanceId; } private Iterable<URI> getAgentIds() throws URISyntaxException { return state.getElementIdsStartingWith(new URI("http://localhost/agent/")); } private void killOnlyAgent() throws URISyntaxException { killAgent(getOnlyAgentId()); } private void killAgent(URI agentId) { for (MockTaskContainer container : containers) { if (container.getExecutorId().equals(agentId)) { logger.info("Killed agent " + agentId); container.kill(); return; } } Assert.fail("Failed to kill agent " + agentId); } }
src/test/java/org/openspaces/servicegrid/ServiceGridOrchestrationTest.java
package org.openspaces.servicegrid; import java.net.URI; import java.net.URISyntaxException; import java.text.DecimalFormat; import java.util.Comparator; import java.util.Set; import java.util.logging.Logger; import org.codehaus.jackson.map.ObjectMapper; import org.openspaces.servicegrid.agent.state.AgentState; import org.openspaces.servicegrid.client.ServiceClient; import org.openspaces.servicegrid.mock.MockEmbeddedAgentLifecycleTaskExecutor; import org.openspaces.servicegrid.mock.MockImmediateMachineSpawnerTaskExecutor; import org.openspaces.servicegrid.mock.MockStreams; import org.openspaces.servicegrid.mock.MockTaskContainer; import org.openspaces.servicegrid.mock.TaskExecutorWrapper; import org.openspaces.servicegrid.service.OrchestrateTask; import org.openspaces.servicegrid.service.ServiceGridOrchestrator; import org.openspaces.servicegrid.service.ServiceGridOrchestratorParameter; import org.openspaces.servicegrid.service.ServiceGridPlanner; import org.openspaces.servicegrid.service.ServiceGridPlannerParameter; import org.openspaces.servicegrid.service.ServiceUtils; import org.openspaces.servicegrid.service.state.ServiceConfig; import org.openspaces.servicegrid.service.state.ServiceGridOrchestratorState; import org.openspaces.servicegrid.service.state.ServiceInstanceState; import org.openspaces.servicegrid.service.state.ServiceState; import org.openspaces.servicegrid.service.tasks.InstallServiceTask; import org.openspaces.servicegrid.service.tasks.ScaleOutServiceTask; import org.openspaces.servicegrid.streams.StreamConsumer; import org.openspaces.servicegrid.streams.StreamProducer; import org.openspaces.servicegrid.time.MockCurrentTimeProvider; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.log.TextFormatter; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; public class ServiceGridOrchestrationTest { private ServiceClient client; private Set<MockTaskContainer> containers; private URI orchestratorExecutorId; private URI plannerExecutorId; private MockTaskContainer orchestratorContainer; private MockStreams<TaskExecutorState> state; private StreamConsumer<Task> taskConsumer; private final Logger logger; private MockStreams<Task> taskBroker; private final MockCurrentTimeProvider timeProvider = new MockCurrentTimeProvider(); public ServiceGridOrchestrationTest() { logger = Logger.getLogger(this.getClass().getName()); Logger parentLogger = logger; while (parentLogger.getHandlers().length == 0) { parentLogger = logger.getParent(); } parentLogger.getHandlers()[0].setFormatter(new TextFormatter()); } @BeforeMethod public void before() { final URI cloudExecutorId; final URI agentLifecycleExecutorId; try { orchestratorExecutorId = new URI("http://localhost/services/orchestrator/"); plannerExecutorId = new URI("http://localhost/services/planner/"); cloudExecutorId = new URI("http://localhost/services/cloud/"); agentLifecycleExecutorId = new URI("http://localhost/services/agentLifecycle/"); } catch (URISyntaxException e) { throw Throwables.propagate(e); } state = new MockStreams<TaskExecutorState>(); StreamProducer<TaskExecutorState> stateWriter = state; StreamConsumer<TaskExecutorState> stateReader = state; this.taskBroker = new MockStreams<Task>(); StreamProducer<Task> taskProducer = taskBroker; taskConsumer = taskBroker; stateWriter.addElement(orchestratorExecutorId, new ServiceGridOrchestratorState()); client = new ServiceClient(stateReader, taskConsumer, taskProducer); final ServiceGridOrchestratorParameter serviceOrchestratorParameter = new ServiceGridOrchestratorParameter(); serviceOrchestratorParameter.setOrchestratorExecutorId(orchestratorExecutorId); serviceOrchestratorParameter.setCloudExecutorId(cloudExecutorId); serviceOrchestratorParameter.setAgentLifecycleExecutorId(agentLifecycleExecutorId); serviceOrchestratorParameter.setPlannerExecutorId(plannerExecutorId); serviceOrchestratorParameter.setTaskConsumer(taskConsumer); serviceOrchestratorParameter.setTaskProducer(taskProducer); serviceOrchestratorParameter.setStateReader(stateReader); serviceOrchestratorParameter.setTimeProvider(timeProvider); orchestratorContainer = new MockTaskContainer( orchestratorExecutorId, stateReader, stateWriter, taskConsumer, new ServiceGridOrchestrator( serviceOrchestratorParameter), timeProvider); final ServiceGridPlannerParameter servicePlannerParameter = new ServiceGridPlannerParameter(); servicePlannerParameter.setPlannerExecutorId(plannerExecutorId); servicePlannerParameter.setTaskConsumer(taskConsumer); servicePlannerParameter.setTaskProducer(taskProducer); servicePlannerParameter.setStateReader(stateReader); servicePlannerParameter.setTimeProvider(timeProvider); containers = Sets.newCopyOnWriteArraySet(); addContainers( orchestratorContainer, new MockTaskContainer( plannerExecutorId, stateReader, stateWriter, taskConsumer, new ServiceGridPlanner(servicePlannerParameter), timeProvider), new MockTaskContainer( cloudExecutorId, stateReader, stateWriter, taskConsumer, new MockImmediateMachineSpawnerTaskExecutor(), timeProvider), new MockTaskContainer( agentLifecycleExecutorId, stateReader, stateWriter, taskConsumer, new MockEmbeddedAgentLifecycleTaskExecutor(new TaskExecutorWrapper() { @Override public void wrapTaskExecutor( final Object taskExecutor, final URI executorId) { MockTaskContainer container = new MockTaskContainer(executorId, state, state, taskConsumer, taskExecutor, timeProvider); addContainer(container); } @Override public void removeTaskExecutor(final URI executorId) { containers.remove( Iterables.find(containers, new Predicate<MockTaskContainer>() { @Override public boolean apply(MockTaskContainer executor) { return executorId.equals(executor.getExecutorId()); } }) ); } } ), timeProvider) ); } private void addContainers(MockTaskContainer ... newContainers) { for (MockTaskContainer container : newContainers) { addContainer(container); } } private void addContainer(MockTaskContainer container) { //logger.info("Adding container for " + container.getExecutorId()); Preconditions.checkState(!containers.contains(container), "Container " + container.getExecutorId() + " was already added"); containers.add(container); } @AfterMethod public void after() throws URISyntaxException { //Iterable<Task> tasks = filterOrchestratorTasks(getSortedTasks()); Iterable<Task> tasks = getSortedTasks(); for (final Task task : tasks) { DecimalFormat timestampFormatter = new DecimalFormat("###,###"); Long sourceTimestamp = task.getSourceTimestamp(); String timestamp = ""; if (sourceTimestamp != null) { timestamp = timestampFormatter.format(sourceTimestamp); } logger.info(String.format("%-8s%-30starget: %s",timestamp,task.getClass().getSimpleName(),task.getTarget())); } } Iterable<Task> filterOrchestratorTasks(Iterable<Task> unfiltered) { return Iterables.filter(unfiltered, new Predicate<Task>(){ @Override public boolean apply(Task task) { return orchestratorExecutorId.equals(task.getSource()); }}); } private Iterable<Task> getSortedTasks() throws URISyntaxException { final Iterable<URI> taskExecutorIds = taskBroker.getElementIdsStartingWith(new URI("http://localhost/")); Set<Task> sortedTasks = Sets.newTreeSet( new Comparator<Task>() { private final ObjectMapper mapper = new ObjectMapper(); @Override public int compare(Task o1, Task o2) { int c; if (o1.getSourceTimestamp() == null) c = 1; else if (o2.getSourceTimestamp() == null) c = -1; else { c = o1.getSourceTimestamp().compareTo(o2.getSourceTimestamp()); if (c == 0) { try { c = mapper.writeValueAsString(o1).compareTo(mapper.writeValueAsString(o2)); } catch (Throwable t) { throw Throwables.propagate(t); } } } return c; } }); for (final URI executorId : taskExecutorIds) { for (URI taskId = taskBroker.getFirstElementId(executorId); taskId != null ; taskId = taskBroker.getNextElementId(taskId)) { final Task task = taskBroker.getElement(taskId, Task.class); sortedTasks.add(task); } } return sortedTasks; } @Test public void installSingleInstanceServiceTest() throws URISyntaxException { logger.info("Starting installSingleInstanceServiceTest URIs: " + state.getElementIdsStartingWith(new URI("http://localhost/"))); installService("tomcat", 1); execute(); URI serviceId = getServiceId("tomcat"); final ServiceState serviceState = state.getElement(state.getLastElementId(serviceId), ServiceState.class); Assert.assertEquals(Iterables.size(serviceState.getInstanceIds()),1); logger.info("URIs: " + state.getElementIdsStartingWith(new URI("http://localhost/"))); URI instanceId = getOnlyServiceInstanceId(); URI agentId = getOnlyAgentId(); ServiceInstanceState instanceState = getServiceInstanceState(instanceId); Assert.assertEquals(instanceState.getServiceId(), serviceId); Assert.assertEquals(instanceState.getAgentId(), agentId); Assert.assertEquals(instanceState.getProgress(), ServiceInstanceState.Progress.INSTANCE_STARTED); AgentState agentState = getAgentState(agentId); Assert.assertEquals(Iterables.getOnlyElement(agentState.getServiceInstanceIds()),instanceId); Assert.assertEquals(agentState.getProgress(), AgentState.Progress.AGENT_STARTED); Assert.assertEquals(agentState.getNumberOfRestarts(), 0); } private URI getOnlyAgentId() throws URISyntaxException { return Iterables.getOnlyElement(getAgentIds()); } @Test public void installMultipleInstanceServiceTest() throws URISyntaxException { logger.info("Starting installMultipleInstanceServiceTest"); installService("tomcat", 2); execute(); assertTwoTomcatInstances(); } @Test public void agentFailoverTest() throws URISyntaxException { logger.info("Starting agentFailoverTest"); installService("tomcat", 1); execute(); killOnlyAgent(); execute(); URI instanceId = getOnlyServiceInstanceId(); ServiceInstanceState instanceState = getServiceInstanceState(instanceId); Assert.assertEquals(instanceState.getProgress(), ServiceInstanceState.Progress.INSTANCE_STARTED); AgentState agentState = getAgentState(getOnlyAgentId()); Assert.assertEquals(Iterables.getOnlyElement(agentState.getServiceInstanceIds()),instanceId); Assert.assertEquals(agentState.getProgress(),AgentState.Progress.AGENT_STARTED); Assert.assertEquals(agentState.getNumberOfRestarts(),1); } @Test public void scaleOutServiceTest() throws URISyntaxException { logger.info("Starting installSingleInstanceServiceTest URIs: " + state.getElementIdsStartingWith(new URI("http://localhost/"))); installService("tomcat", 1); execute(); scaleOutService("tomcat",2); execute(); assertTwoTomcatInstances(); } private void assertTwoTomcatInstances() throws URISyntaxException { final URI serviceId = getServiceId("tomcat"); final ServiceState serviceState = state.getElement(state.getLastElementId(serviceId), ServiceState.class); Assert.assertEquals(Iterables.size(serviceState.getInstanceIds()),2); logger.info("URIs: " + state.getElementIdsStartingWith(new URI("http://localhost/"))); Iterable<URI> instanceIds = state.getElementIdsStartingWith(new URI("http://localhost/services/tomcat/instances/")); Assert.assertEquals(Iterables.size(instanceIds),2); Iterable<URI> agentIds = getAgentIds(); int numberOfAgents = Iterables.size(agentIds); Assert.assertEquals(numberOfAgents, 2); for (int i = 0 ; i < numberOfAgents; i++) { URI agentId = Iterables.get(agentIds, i); AgentState agentState = getAgentState(agentId); Assert.assertEquals(agentState.getProgress(), AgentState.Progress.AGENT_STARTED); Assert.assertEquals(agentState.getNumberOfRestarts(), 0); URI instanceId = Iterables.getOnlyElement(agentState.getServiceInstanceIds()); Assert.assertTrue(Iterables.contains(instanceIds, instanceId)); ServiceInstanceState instanceState = state.getElement(state.getLastElementId(instanceId), ServiceInstanceState.class); Assert.assertEquals(instanceState.getServiceId(), serviceId); Assert.assertEquals(instanceState.getAgentId(), agentId); Assert.assertEquals(instanceState.getProgress(), ServiceInstanceState.Progress.INSTANCE_STARTED); } } /*public void installTwoSingleInstanceServicesTest(){ installService("tomcat", 1); installService("cassandra", 1); execute(); }*/ // public void uninstallSingleInstanceServiceTest(){ // installService(1); // execute(); // // } private AgentState getAgentState(URI agentId) { return getLastState(agentId, AgentState.class); } private ServiceInstanceState getServiceInstanceState(URI instanceId) throws URISyntaxException { return getLastState(instanceId, ServiceInstanceState.class); } private <T extends TaskExecutorState> T getLastState(URI executorId, Class<T> stateClass) { T lastState = ServiceUtils.getLastState(state, executorId, stateClass); Assert.assertNotNull(lastState); return lastState; } private void installService(String name, int numberOfInstances) throws URISyntaxException { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setDisplayName(name); serviceConfig.setPlannedNumberOfInstances(numberOfInstances); serviceConfig.setServiceId(getServiceId(name)); final InstallServiceTask installServiceTask = new InstallServiceTask(); installServiceTask.setServiceConfig(serviceConfig); client.addServiceTask(orchestratorExecutorId, installServiceTask); } private void scaleOutService(String serviceName, int plannedNumberOfInstances) throws URISyntaxException { final ScaleOutServiceTask scaleOutServiceTask = new ScaleOutServiceTask(); URI serviceId = getServiceId(serviceName); scaleOutServiceTask.setServiceId(serviceId); scaleOutServiceTask.setPlannedNumberOfInstances(plannedNumberOfInstances); client.addServiceTask(orchestratorExecutorId, scaleOutServiceTask); } private URI getServiceId(String name) throws URISyntaxException { return new URI("http://localhost/services/" + name + "/"); } private void execute() throws URISyntaxException { int consecutiveEmptyCycles = 0; for (; timeProvider.currentTimeMillis() < 300000; timeProvider.increaseBy(1000)) { boolean emptyCycle = true; OrchestrateTask orchestrateTask = new OrchestrateTask(); orchestrateTask.setMaxNumberOfOrchestrationSteps(100); client.addServiceTask(orchestratorExecutorId, orchestrateTask); for (MockTaskContainer container : containers) { Assert.assertEquals(container.getExecutorId().getHost(),"localhost"); while (container.stepTaskExecutor()) { if (!container.getExecutorId().equals(orchestratorExecutorId)) { emptyCycle = false; } } } if (emptyCycle) { consecutiveEmptyCycles++; } if (consecutiveEmptyCycles > 60) { return; } } StringBuilder sb = new StringBuilder(); Iterable<URI> servicesIds = state.getElementIdsStartingWith(new URI("http://services/")); for (URI URI : servicesIds) { ServiceState serviceState = state.getElement(state.getLastElementId(URI), ServiceState.class); sb.append("service: " + serviceState.getServiceConfig().getDisplayName()); sb.append(" - "); for (URI instanceURI : serviceState.getInstanceIds()) { ServiceInstanceState instanceState = state.getElement(state.getLastElementId(instanceURI), ServiceInstanceState.class); sb.append(instanceURI).append("[").append(instanceState.getProgress()).append("] "); } } Assert.fail("Executing too many cycles progress=" + sb); } private URI getOnlyServiceInstanceId() throws URISyntaxException { final Iterable<URI> instanceIds = state.getElementIdsStartingWith(new URI("http://localhost/services/tomcat/instances/")); Assert.assertEquals(Iterables.size(instanceIds),1); final URI serviceInstanceId = Iterables.getOnlyElement(instanceIds); return serviceInstanceId; } private Iterable<URI> getAgentIds() throws URISyntaxException { return state.getElementIdsStartingWith(new URI("http://localhost/agent/")); } private void killOnlyAgent() throws URISyntaxException { killAgent(getOnlyAgentId()); } private void killAgent(URI agentId) { for (MockTaskContainer container : containers) { if (container.getExecutorId().equals(agentId)) { logger.info("Killed agent " + agentId); container.kill(); return; } } Assert.fail("Failed to kill agent " + agentId); } }
Fixed test bug
src/test/java/org/openspaces/servicegrid/ServiceGridOrchestrationTest.java
Fixed test bug
Java
apache-2.0
2fb0c77a0b0f77086911d49c088df190b01d0e03
0
rest-assured/rest-assured,jayway/rest-assured,rest-assured/rest-assured,rest-assured/rest-assured,jayway/rest-assured
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.restassured.builder; import io.restassured.RestAssured; import io.restassured.authentication.AuthenticationScheme; import io.restassured.config.LogConfig; import io.restassured.config.RestAssuredConfig; import io.restassured.config.SessionConfig; import io.restassured.filter.Filter; import io.restassured.filter.log.LogBlacklists; import io.restassured.filter.log.LogDetail; import io.restassured.filter.log.RequestLoggingFilter; import io.restassured.http.ContentType; import io.restassured.http.Cookie; import io.restassured.http.Cookies; import io.restassured.internal.RequestSpecificationImpl; import io.restassured.internal.SpecificationMerger; import io.restassured.internal.log.LogRepository; import io.restassured.mapper.ObjectMapper; import io.restassured.mapper.ObjectMapperType; import io.restassured.specification.MultiPartSpecification; import io.restassured.specification.ProxySpecification; import io.restassured.specification.RequestSpecification; import java.io.File; import java.io.InputStream; import java.io.PrintStream; import java.net.URI; import java.security.KeyStore; import java.util.Collection; import java.util.List; import java.util.Map; import static io.restassured.RestAssured.*; import static io.restassured.internal.common.assertion.AssertParameter.notNull; /** * You can use the builder to construct a request specification. The specification can be used as e.g. * <pre> * ResponseSpecification responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); * RequestSpecification requestSpec = new RequestSpecBuilder().addParam("parameter1", "value1").build(); * * given(responseSpec, requestSpec).post("/something"); * </pre> * <p/> * or * <pre> * RequestSpecification requestSpec = new RequestSpecBuilder().addParameter("parameter1", "value1").build(); * * given(). * spec(requestSpec). * expect(). * body("x.y.z", equalTo("something")). * when(). * get("/something"); * </pre> */ public class RequestSpecBuilder { private static final String SSL = "SSL"; private RequestSpecificationImpl spec; public RequestSpecBuilder() { this.spec = (RequestSpecificationImpl) new RequestSpecificationImpl(baseURI, port, basePath, authentication, filters(), requestSpecification, urlEncodingEnabled, config, new LogRepository(), proxy).config(RestAssured.config()); } /** * Specify a String request body (such as e.g. JSON or XML) to be sent with the request. This works for the * POST, PUT and PATCH methods only. Trying to do this for the other http methods will cause an exception to be thrown. * <p/> * * @param body The body to send. * @return The request specification builder */ public RequestSpecBuilder setBody(String body) { spec.body(body); return this; } /** * Specify a byte array request body to be sent with the request. This only works for the * POST http method. Trying to do this for the other http methods will cause an exception to be thrown. * * @param body The body to send. * @return The request specification builder */ public RequestSpecBuilder setBody(byte[] body) { spec.body(body); return this; } /** * Specify an Object request content that will automatically be serialized to JSON or XML and sent with the request. * If the object is a primitive or <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Number.html">Number</a> the object will * be converted to a String and put in the request body. This works for the POST, PUT and PATCH methods only. * Trying to do this for the other http methods will cause an exception to be thrown. * <p/> * * @param object The object to serialize and send with the request * @return The request specification */ public RequestSpecBuilder setBody(Object object) { spec.body(object); return this; } /** * Specify an Object request content that will automatically be serialized to JSON or XML and sent with the request using a specific object mapper. * This works for the POST, PATCH and PUT methods only. Trying to do this for the other http methods will cause an exception to be thrown. * * @param object The object to serialize and send with the request * @param mapper The object mapper * @return The request specification */ public RequestSpecBuilder setBody(Object object, ObjectMapper mapper) { spec.body(object, mapper); return this; } /** * Specify an Object request content that will automatically be serialized to JSON or XML and sent with the request using a specific object mapper type. * This works for the POST, PATCH and PUT methods only. Trying to do this for the other http methods will cause an exception to be thrown. * <p> * Example of use: * <pre> * Message message = new Message(); * message.setMessage("My beautiful message"); * * given(). * body(message, ObjectMapper.GSON). * expect(). * content(equalTo("Response to a beautiful message")). * when(). * post("/beautiful-message"); * </pre> * </p> * * @param object The object to serialize and send with the request * @param mapperType The object mapper type to be used * @return The request specification */ public RequestSpecBuilder setBody(Object object, ObjectMapperType mapperType) { spec.body(object, mapperType); return this; } /** * Add cookies to be sent with the request as Map e.g: * * @param cookies The Map containing the cookie names and their values to set in the request. * @return The request specification builder */ public RequestSpecBuilder addCookies(Map<String, ?> cookies) { spec.cookies(cookies); return this; } /** * Add a detailed cookie * * @param cookie The cookie to add. * @return The request specification builder */ public RequestSpecBuilder addCookie(Cookie cookie) { spec.cookie(cookie); return this; } /** * Add a cookie to be sent with the request. * * @param key The cookie key * @param value The cookie value * @param cookieNameValuePairs Additional cookies values. This will actually create two cookies with the same name but with different values. * @return The request specification builder */ public RequestSpecBuilder addCookie(String key, Object value, Object... cookieNameValuePairs) { spec.cookie(key, value, cookieNameValuePairs); return this; } /** * Add a cookie without value to be sent with the request. * * @param name The cookie name * @return The request specification builder */ public RequestSpecBuilder addCookie(String name) { spec.cookie(name); return this; } /** * Specify multiple detailed cookies that'll be sent with the request. * * @param cookies The cookies to set in the request. * @return The request specification builder * @see RequestSpecification#cookies(Cookies) */ public RequestSpecBuilder addCookies(Cookies cookies) { spec.cookies(cookies); return this; } /** * Add a filter that will be used in the request. * * @param filter The filter to add * @return RequestSpecBuilder builder */ public RequestSpecBuilder addFilter(Filter filter) { spec.filter(filter); return this; } /** * Add filters that will be used in the request. * * @param filters The filters to add * @return RequestSpecBuilder builder */ public RequestSpecBuilder addFilters(List<Filter> filters) { spec.filters(filters); return this; } /** * Add parameters to be sent with the request as Map. * * @param parametersMap The Map containing the parameter names and their values to send with the request. * @return The request specification builder */ public RequestSpecBuilder addParams(Map<String, ?> parametersMap) { spec.params(parametersMap); return this; } /** * Add a parameter to be sent with the request. * * @param parameterName The parameter name * @param parameterValues Zero to many parameter values for this parameter name. * @return The request specification builder */ public RequestSpecBuilder addParam(String parameterName, Object... parameterValues) { spec.param(parameterName, parameterValues); return this; } /** * Add a multi-value parameter to be sent with the request. * * @param parameterName The parameter key * @param parameterValues The parameter values * @return The request specification builder */ public RequestSpecBuilder addParam(String parameterName, Collection<?> parameterValues) { spec.param(parameterName, parameterValues); return this; } /** * Method to remove parameter added with {@link #addParam(String, Object...)} from map. * Removes all values of this parameter * * @param parameterName The parameter key * @return The request specification builder */ public RequestSpecBuilder removeParam(String parameterName) { spec.removeParam(parameterName); return this; } /** * Add a query parameter to be sent with the request. This method is the same as {@link #addParam(String, java.util.Collection)} * for all HTTP methods except POST where this method can be used to differentiate between form and query params. * * @param parameterName The parameter key * @param parameterValues The parameter values * @return The request specification builder * @see #addQueryParam(String, Object...) */ public RequestSpecBuilder addQueryParam(String parameterName, Collection<?> parameterValues) { spec.queryParam(parameterName, parameterValues); return this; } /** * Add query parameters to be sent with the request as a Map. This method is the same as {@link #addParams(java.util.Map)} * for all HTTP methods except POST where this method can be used to differentiate between form and query params. * * @param parametersMap The Map containing the parameter names and their values to send with the request. * @return The request specification builder */ public RequestSpecBuilder addQueryParams(Map<String, ?> parametersMap) { spec.queryParams(parametersMap); return this; } /** * Add a query parameter to be sent with the request. This method is the same as {@link #addParam(String, Object...)} )} * for all HTTP methods except POST where this method can be used to differentiate between form and query params. * * @param parameterName The parameter key * @param parameterValues Zero to many parameter values for this parameter name. * @return The request specification builder */ public RequestSpecBuilder addQueryParam(String parameterName, Object... parameterValues) { spec.queryParam(parameterName, parameterValues); return this; } /** * Method to remove parameter added with from map. * Removes all values of this parameter * * @param parameterName The parameter key * @return The request specification builder */ public RequestSpecBuilder removeQueryParam(String parameterName) { spec.removeQueryParam(parameterName); return this; } /** * Add a form parameter to be sent with the request. This method is the same as {@link #addParam(String, java.util.Collection)} * for all HTTP methods except PUT where this method can be used to differentiate between form and query params. * * @param parameterName The parameter key * @param parameterValues The parameter values * @return The request specification builder * @see #addFormParam(String, Object...) */ public RequestSpecBuilder addFormParam(String parameterName, Collection<?> parameterValues) { spec.formParam(parameterName, parameterValues); return this; } /** * Add query parameters to be sent with the request as a Map. This method is the same as {@link #addParams(java.util.Map)} * for all HTTP methods except POST where this method can be used to differentiate between form and query params. * * @param parametersMap The Map containing the parameter names and their values to send with the request. * @return The request specification builder */ public RequestSpecBuilder addFormParams(Map<String, ?> parametersMap) { spec.formParams(parametersMap); return this; } /** * Add a form parameter to be sent with the request. This method is the same as {@link #addParam(String, Object...)} )} * for all HTTP methods except PUT where this method can be used to differentiate between form and query params. * * @param parameterName The parameter key * @param parameterValues Zero to many parameter values for this parameter name. * @return The request specification builder * @see #addFormParam(String, Object...) */ public RequestSpecBuilder addFormParam(String parameterName, Object... parameterValues) { spec.formParam(parameterName, parameterValues); return this; } /** * Method to remove parameter added with {@link #addFormParam(String, Object...)} from map. * Removes all values of this parameter * * @param parameterName The parameter key * @return The request specification builder */ public RequestSpecBuilder removeFormParam(String parameterName) { spec.removeFormParam(parameterName); return this; } /** * Specify a path parameter. Path parameters are used to improve readability of the request path. E.g. instead * of writing: * <pre> * expect().statusCode(200).when().get("/item/"+myItem.getItemNumber()+"/buy/"+2); * </pre> * you can write: * <pre> * given(). * pathParam("itemNumber", myItem.getItemNumber()). * pathParam("amount", 2). * expect(). * statusCode(200). * when(). * get("/item/{itemNumber}/buy/{amount}"); * </pre> * <p/> * which improves readability and allows the path to be reusable in many tests. Another alternative is to use: * <pre> * expect().statusCode(200).when().get("/item/{itemNumber}/buy/{amount}", myItem.getItemNumber(), 2); * </pre> * * @param parameterName The parameter key * @param parameterValue The parameter value * @return The request specification */ public RequestSpecBuilder addPathParam(String parameterName, Object parameterValue) { spec.pathParam(parameterName, parameterValue); return this; } /** * Specify multiple path parameter name-value pairs. Path parameters are used to improve readability of the request path. E.g. instead * of writing: * <pre> * expect().statusCode(200).when().get("/item/"+myItem.getItemNumber()+"/buy/"+2); * </pre> * you can write: * <pre> * given(). * pathParam("itemNumber", myItem.getItemNumber(), "amount", 2). * expect(). * statusCode(200). * when(). * get("/item/{itemNumber}/buy/{amount}"); * </pre> * <p/> * which improves readability and allows the path to be reusable in many tests. Another alternative is to use: * <pre> * expect().statusCode(200).when().get("/item/{itemNumber}/buy/{amount}", myItem.getItemNumber(), 2); * </pre> * * @param firstParameterName The name of the first parameter * @param firstParameterValue The value of the first parameter * @param parameterNameValuePairs Additional parameters in name-value pairs. * @return The request specification */ public RequestSpecBuilder addPathParams(String firstParameterName, Object firstParameterValue, Object... parameterNameValuePairs) { spec.pathParams(firstParameterName, firstParameterValue, parameterNameValuePairs); return this; } /** * Specify multiple path parameter name-value pairs. Path parameters are used to improve readability of the request path. E.g. instead * of writing: * <pre> * expect().statusCode(200).when().get("/item/"+myItem.getItemNumber()+"/buy/"+2); * </pre> * you can write: * <pre> * Map&lt;String,Object&gt; pathParams = new HashMap&lt;String,Object&gt;(); * pathParams.add("itemNumber",myItem.getItemNumber()); * pathParams.add("amount",2); * * given(). * pathParameters(pathParams). * expect(). * statusCode(200). * when(). * get("/item/{itemNumber}/buy/{amount}"); * </pre> * <p/> * which improves readability and allows the path to be reusable in many tests. Another alternative is to use: * <pre> * expect().statusCode(200).when().get("/item/{itemNumber}/buy/{amount}", myItem.getItemNumber(), 2); * </pre> * * @param parameterNameValuePairs A map containing the path parameters. * @return The request specification */ public RequestSpecBuilder addPathParams(Map<String, ?> parameterNameValuePairs) { spec.pathParams(parameterNameValuePairs); return this; } /** * Method to remove parameter added with {@link #addPathParam(String, Object)} from map. * Removes all values of this parameter. * * @param parameterName The parameter key * @return The request specification builder */ public RequestSpecBuilder removePathParam(String parameterName) { spec.removePathParam(parameterName); return this; } /** * Specify a keystore. * <pre> * RestAssured.keyStore("/truststore_javanet.jks", "test1234"); * </pre> * or * <pre> * given().keyStore("/truststore_javanet.jks", "test1234"). .. * </pre> * </p> * * @param pathToJks The path to the JKS * @param password The store pass */ public RequestSpecBuilder setKeyStore(String pathToJks, String password) { spec.keyStore(pathToJks, password); return this; } /** * The following documentation is taken from <a href="HTTP Builder">https://github.com/jgritman/httpbuilder/wiki/SSL</a>: * <p> * <h1>SSL Configuration</h1> * <p/> * SSL should, for the most part, "just work." There are a few situations where it is not completely intuitive. You can follow the example below, or see HttpClient's SSLSocketFactory documentation for more information. * <p/> * <h1>SSLPeerUnverifiedException</h1> * <p/> * If you can't connect to an SSL website, it is likely because the certificate chain is not trusted. This is an Apache HttpClient issue, but explained here for convenience. To correct the untrusted certificate, you need to import a certificate into an SSL truststore. * <p/> * First, export a certificate from the website using your browser. For example, if you go to https://dev.java.net in Firefox, you will probably get a warning in your browser. Choose "Add Exception," "Get Certificate," "View," "Details tab." Choose a certificate in the chain and export it as a PEM file. You can view the details of the exported certificate like so: * <pre> * $ keytool -printcert -file EquifaxSecureGlobaleBusinessCA-1.crt * Owner: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US * Issuer: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US * Serial number: 1 * Valid from: Mon Jun 21 00:00:00 EDT 1999 until: Sun Jun 21 00:00:00 EDT 2020 * Certificate fingerprints: * MD5: 8F:5D:77:06:27:C4:98:3C:5B:93:78:E7:D7:7D:9B:CC * SHA1: 7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45 * Signature algorithm name: MD5withRSA * Version: 3 * .... * </pre> * Now, import that into a Java keystore file: * <pre> * $ keytool -importcert -alias "equifax-ca" -file EquifaxSecureGlobaleBusinessCA-1.crt -keystore truststore_javanet.jks -storepass test1234 * Owner: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US * Issuer: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US * Serial number: 1 * Valid from: Mon Jun 21 00:00:00 EDT 1999 until: Sun Jun 21 00:00:00 EDT 2020 * Certificate fingerprints: * MD5: 8F:5D:77:06:27:C4:98:3C:5B:93:78:E7:D7:7D:9B:CC * SHA1: 7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45 * Signature algorithm name: MD5withRSA * Version: 3 * ... * Trust this certificate? [no]: yes * Certificate was added to keystore * </pre> * Now you want to use this truststore in your client: * <pre> * RestAssured.trustStore("/truststore_javanet.jks", "test1234"); * </pre> * or * <pre> * given().trustStore("/truststore_javanet.jks", "test1234"). .. * </pre> * </p> * * @param pathToJks The path to the JKS * @param password The store pass */ public RequestSpecBuilder setTrustStore(String pathToJks, String password) { spec.trustStore(pathToJks, password); return this; } /** * The following documentation is taken from <a href="HTTP Builder">https://github.com/jgritman/httpbuilder/wiki/SSL</a>: * <p> * <h1>SSL Configuration</h1> * <p/> * SSL should, for the most part, "just work." There are a few situations where it is not completely intuitive. You can follow the example below, or see HttpClient's SSLSocketFactory documentation for more information. * <p/> * <h1>SSLPeerUnverifiedException</h1> * <p/> * If you can't connect to an SSL website, it is likely because the certificate chain is not trusted. This is an Apache HttpClient issue, but explained here for convenience. To correct the untrusted certificate, you need to import a certificate into an SSL truststore. * <p/> * First, export a certificate from the website using your browser. For example, if you go to https://dev.java.net in Firefox, you will probably get a warning in your browser. Choose "Add Exception," "Get Certificate," "View," "Details tab." Choose a certificate in the chain and export it as a PEM file. You can view the details of the exported certificate like so: * <pre> * $ keytool -printcert -file EquifaxSecureGlobaleBusinessCA-1.crt * Owner: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US * Issuer: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US * Serial number: 1 * Valid from: Mon Jun 21 00:00:00 EDT 1999 until: Sun Jun 21 00:00:00 EDT 2020 * Certificate fingerprints: * MD5: 8F:5D:77:06:27:C4:98:3C:5B:93:78:E7:D7:7D:9B:CC * SHA1: 7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45 * Signature algorithm name: MD5withRSA * Version: 3 * .... * </pre> * Now, import that into a Java keystore file: * <pre> * $ keytool -importcert -alias "equifax-ca" -file EquifaxSecureGlobaleBusinessCA-1.crt -keystore truststore_javanet.jks -storepass test1234 * Owner: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US * Issuer: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US * Serial number: 1 * Valid from: Mon Jun 21 00:00:00 EDT 1999 until: Sun Jun 21 00:00:00 EDT 2020 * Certificate fingerprints: * MD5: 8F:5D:77:06:27:C4:98:3C:5B:93:78:E7:D7:7D:9B:CC * SHA1: 7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45 * Signature algorithm name: MD5withRSA * Version: 3 * ... * Trust this certificate? [no]: yes * Certificate was added to keystore * </pre> * Now you want to use this truststore in your client: * <pre> * RestAssured.trustStore("/truststore_javanet.jks", "test1234"); * </pre> * or * <pre> * given().trustStore("/truststore_javanet.jks", "test1234"). .. * </pre> * </p> * * @param pathToJks The path to the JKS * @param password The store pass */ public RequestSpecBuilder setTrustStore(File pathToJks, String password) { spec.trustStore(pathToJks, password); return this; } /** * Add headers to be sent with the request as Map. * * @param headers The Map containing the header names and their values to send with the request. * @return The request specification builder */ public RequestSpecBuilder addHeaders(Map<String, String> headers) { spec.headers(headers); return this; } /** * Add a header to be sent with the request e.g: * * @param headerName The header name * @param headerValue The header value * @return The request specification builder */ public RequestSpecBuilder addHeader(String headerName, String headerValue) { spec.header(headerName, headerValue); return this; } /** * Specify the content type of the request. * * @param contentType The content type of the request * @return The request specification builder * @see ContentType */ public RequestSpecBuilder setContentType(ContentType contentType) { spec.contentType(contentType); return this; } /** * Specify the content type of the request as string. * * @param contentType The content type of the request * @return The request specification builder */ public RequestSpecBuilder setContentType(String contentType) { spec.contentType(contentType); return this; } /** * Specify the accept header of the request. This just a shortcut for: * <pre> * addHeader("Accept", contentType); * </pre> * * @param contentType The content type whose accept header {@link ContentType#getAcceptHeader()} will be used as Accept header in the request. * @return The request specification * @see ContentType * @see #addHeader(String, String) */ public RequestSpecBuilder setAccept(ContentType contentType) { spec.accept(contentType); return this; } /** * Specify the accept header of the request. This just a shortcut for: * <pre> * header("Accept", contentType); * </pre> * * @param mediaTypes The media type(s) that will be used as Accept header in the request. * @return The request specification * @see ContentType * @see #addHeader(String, String) */ public RequestSpecBuilder setAccept(String mediaTypes) { spec.accept(mediaTypes); return this; } /** * Specify a multi-part specification. Use this method if you need to specify content-type etc. * * @param multiPartSpecification Multipart specification * @return The request specification */ public RequestSpecBuilder addMultiPart(MultiPartSpecification multiPartSpecification) { spec.multiPart(multiPartSpecification); return this; } /** * Specify a file to upload to the server using multi-part form data uploading. * It will assume that the control name is <tt>file</tt> and the content-type is <tt>application/octet-stream</tt>. * If this is not what you want please use an overloaded method. * * @param file The file to upload * @return The request specification */ public RequestSpecBuilder addMultiPart(File file) { spec.multiPart(file); return this; } /** * Specify a file to upload to the server using multi-part form data uploading with a specific * control name. It will use the content-type <tt>application/octet-stream</tt>. * If this is not what you want please use an overloaded method. * * @param file The file to upload * @param controlName Defines the control name of the body part. In HTML this is the attribute name of the input tag. * @return The request specification */ public RequestSpecBuilder addMultiPart(String controlName, File file) { spec.multiPart(controlName, file); return this; } /** * Specify a file to upload to the server using multi-part form data uploading with a specific * control name and content-type. * * @param file The file to upload * @param controlName Defines the control name of the body part. In HTML this is the attribute name of the input tag. * @param mimeType The content-type * @return The request specification */ public RequestSpecBuilder addMultiPart(String controlName, File file, String mimeType) { spec.multiPart(controlName, file, mimeType); return this; } /** * Specify a byte-array to upload to the server using multi-part form data. * It will use the content-type <tt>application/octet-stream</tt>. If this is not what you want please use an overloaded method. * * @param controlName Defines the control name of the body part. In HTML this is the attribute name of the input tag. * @param fileName The name of the content you're uploading * @param bytes The bytes you want to send * @return The request specification */ public RequestSpecBuilder addMultiPart(String controlName, String fileName, byte[] bytes) { spec.multiPart(controlName, fileName, bytes); return this; } /** * Specify a byte-array to upload to the server using multi-part form data. * * @param controlName Defines the control name of the body part. In HTML this is the attribute name of the input tag. * @param fileName The name of the content you're uploading * @param bytes The bytes you want to send * @param mimeType The content-type * @return The request specification */ public RequestSpecBuilder addMultiPart(String controlName, String fileName, byte[] bytes, String mimeType) { spec.multiPart(controlName, fileName, bytes, mimeType); return this; } /** * Specify an inputstream to upload to the server using multi-part form data. * It will use the content-type <tt>application/octet-stream</tt>. If this is not what you want please use an overloaded method. * * @param controlName Defines the control name of the body part. In HTML this is the attribute name of the input tag. * @param fileName The name of the content you're uploading * @param stream The stream you want to send * @return The request specification */ public RequestSpecBuilder addMultiPart(String controlName, String fileName, InputStream stream) { spec.multiPart(controlName, fileName, stream); return this; } /** * Specify an inputstream to upload to the server using multi-part form data. * * @param controlName Defines the control name of the body part. In HTML this is the attribute name of the input tag. * @param fileName The name of the content you're uploading * @param stream The stream you want to send * @param mimeType The content-type * @return The request specification */ public RequestSpecBuilder addMultiPart(String controlName, String fileName, InputStream stream, String mimeType) { spec.multiPart(controlName, fileName, stream, mimeType); return this; } /** * Specify a string to send to the server using multi-part form data. * It will use the content-type <tt>text/plain</tt>. If this is not what you want please use an overloaded method. * * @param controlName Defines the control name of the body part. In HTML this is the attribute name of the input tag. * @param contentBody The string to send * @return The request specification */ public RequestSpecBuilder addMultiPart(String controlName, String contentBody) { spec.multiPart(controlName, contentBody); return this; } /** * Specify a string to send to the server using multi-part form data with a specific mime-type. * * @param controlName Defines the control name of the body part. In HTML this is the attribute name of the input tag. * @param contentBody The string to send * @param mimeType The mime-type * @return The request specification */ public RequestSpecBuilder addMultiPart(String controlName, String contentBody, String mimeType) { spec.multiPart(controlName, contentBody, mimeType); return this; } /** * If you need to specify some credentials when performing a request. * * @return The request specification builder */ public RequestSpecBuilder setAuth(AuthenticationScheme auth) { spec.setAuthenticationScheme(auth); return this; } /** * Specify the port. * * @param port The port of URI * @return The request specification builder */ public RequestSpecBuilder setPort(int port) { spec.port(port); return this; } /** * Specifies if Rest Assured should url encode the URL automatically. Usually this is a recommended but in some cases * e.g. the query parameters are already be encoded before you provide them to Rest Assured then it's useful to disable * URL encoding. * * @param isEnabled Specify whether or not URL encoding should be enabled or disabled. * @return The request specification builder */ public RequestSpecBuilder setUrlEncodingEnabled(boolean isEnabled) { spec.urlEncodingEnabled(isEnabled); return this; } /** * Set the session id for this request. It will use the configured session id name from the configuration (by default this is {@value SessionConfig#DEFAULT_SESSION_ID_NAME}). * You can configure the session id name by using: * <pre> * RestAssured.config = newConfig().sessionConfig(new SessionConfig().sessionIdName(&lt;sessionIdName&gt;)); * </pre> * or you can use the {@link #setSessionId(String, String)} method to set it for this request only. * * @param sessionIdValue The session id value. * @return The request specification */ public RequestSpecBuilder setSessionId(String sessionIdValue) { spec.sessionId(sessionIdValue); return this; } /** * Set the session id name and value for this request. It'll override the default session id name from the configuration (by default this is {@value SessionConfig#DEFAULT_SESSION_ID_NAME}). * You can configure the default session id name by using: * <pre> * RestAssured.config = newConfig().sessionConfig(new SessionConfig().sessionIdName(&lt;sessionIdName&gt;)); * </pre> * and then you can use the {@link RequestSpecBuilder#setSessionId(String)} method to set the session id value without specifying the name for each request. * * @param sessionIdName The session id name * @param sessionIdValue The session id value. * @return The request specification */ public RequestSpecBuilder setSessionId(String sessionIdName, String sessionIdValue) { spec.sessionId(sessionIdName, sessionIdValue); return this; } /** * Merge this builder with settings from another specification. Note that the supplied specification * can overwrite data in the current specification. The following settings are overwritten: * <ul> * <li>Port</li> * <li>Authentication scheme</ * <li>Content type</li> * <li>Request body</li> * </ul> * The following settings are merged: * <ul> * <li>Parameters</li> * <li>Cookies</li> * <li>Headers</li> * <li>Filters</li> * </ul> * * @param specification The specification to add * @return The request specification builder */ public RequestSpecBuilder addRequestSpecification(RequestSpecification specification) { if (!(specification instanceof RequestSpecificationImpl)) { throw new IllegalArgumentException("Specification must be of type " + RequestSpecificationImpl.class.getClass() + "."); } RequestSpecificationImpl rs = (RequestSpecificationImpl) specification; SpecificationMerger.merge((RequestSpecificationImpl) spec, rs); return this; } /** * Define a configuration for redirection settings and http client parameters. * * @param config The configuration to use for this request. If <code>null</code> no config will be used. * @return The request specification builder */ public RequestSpecBuilder setConfig(RestAssuredConfig config) { spec.config(config); return this; } /** * Build RequestSpecBuilder. * * @return The assembled request specification */ public RequestSpecification build() { return spec; } /** * Add the baseUri property from the RequestSpecBuilder instead of using static field RestAssured.baseURI. * <p/> * <pre> * RequestSpecBuilder builder = new RequestSpecBuilder(); * builder.setBaseUri("http://example.com"); * RequestSpecification specs = builder.build(); * given().specification(specs) * </pre> * * @param uri The URI * @return RequestSpecBuilder */ public RequestSpecBuilder setBaseUri(String uri) { spec.baseUri(uri); return this; } /** * Add the baseUri property from the RequestSpecBuilder instead of using static field RestAssured.baseURI. * <p/> * <pre> * RequestSpecification specs = new RequestSpecBuilder() * .setBaseUri(URI.create("http://example.com")) * .build(); * given().specification(specs) * </pre> * uses {@link #setBaseUri(String)} * * @param uri The URI * @return RequestSpecBuilder */ public RequestSpecBuilder setBaseUri(URI uri) { return setBaseUri(notNull(uri, "Base URI").toString()); } /** * Set the base path that's prepended to each path by REST assured when making requests. E.g. let's say that * the base uri is <code>http://localhost</code> and <code>basePath</code> is <code>/resource</code> * then * <p/> * <pre> * ..when().get("/something"); * </pre> * <p/> * will make a request to <code>http://localhost/resource</code>. * * @param path The base path to set. * @return RequestSpecBuilder */ public RequestSpecBuilder setBasePath(String path) { spec.basePath(path); return this; } /** * Enabled logging with the specified log detail. Set a {@link LogConfig} to configure the print stream and pretty printing options. * * @param logDetail The log detail. * @return RequestSpecBuilder */ public RequestSpecBuilder log(LogDetail logDetail) { notNull(logDetail, LogDetail.class); RestAssuredConfig restAssuredConfig = spec.getConfig(); LogConfig logConfig; if (restAssuredConfig == null) { logConfig = new RestAssuredConfig().getLogConfig(); } else { logConfig = restAssuredConfig.getLogConfig(); } PrintStream printStream = logConfig.defaultStream(); boolean prettyPrintingEnabled = logConfig.isPrettyPrintingEnabled(); boolean shouldUrlEncodeRequestUri = logConfig.shouldUrlEncodeRequestUri(); spec.filter(new RequestLoggingFilter(logDetail, prettyPrintingEnabled, printStream, shouldUrlEncodeRequestUri)); return this; } /** * Blacklists certain components of an HTTP request. * * @param logBlacklists The blacklists to be used during logging. * @return RequestSpecBuilder */ public RequestSpecBuilder logBlacklists(final LogBlacklists logBlacklists) { for (Object filter : spec.getDefinedFilters()) { if (filter instanceof RequestLoggingFilter) { RequestLoggingFilter requestLoggingFilter = (RequestLoggingFilter) filter; requestLoggingFilter.setLogBlacklists(logBlacklists); } } return this; } /** * Use the supplied truststore for HTTPS requests. Shortcut for: * <p> * <pre> * given().config(RestAssured.config().sslConfig(sslConfig().trustStore(truststore)); * </pre> * </p> * <p/> * * @param trustStore The truststore. * @return RequestSpecBuilder * @see #setKeyStore(String, String) */ public RequestSpecBuilder setTrustStore(KeyStore trustStore) { spec.trustStore(trustStore); return this; } /** * Use the supplied keystore for HTTPS requests. Shortcut for: * <p> * <pre> * given().config(RestAssured.config().sslConfig(sslConfig().keyStore(keystore)); * </pre> * </p> * <p/> * * @param keyStore The truststore. * @return RequestSpecBuilder * @see #setKeyStore(String, String) */ public RequestSpecBuilder setKeyStore(KeyStore keyStore) { spec.keyStore(keyStore); return this; } /** * Use relaxed HTTP validation with SSLContext protocol {@value #SSL}. This means that you'll trust all hosts regardless if the SSL certificate is invalid. By using this * method you don't need to specify a keystore (see {@link #setKeyStore(String, String)} or trust store (see {@link #setTrustStore(java.security.KeyStore)}. * <p> * This is just a shortcut for: * </p> * <pre> * given().config(RestAssured.config().sslConfig(sslConfig().relaxedHTTPSValidation())). ..; * </pre> * * @return RequestSpecBuilder */ public RequestSpecBuilder setRelaxedHTTPSValidation() { return setRelaxedHTTPSValidation(SSL); } /** * Use relaxed HTTP validation with a given SSLContext protocol. This means that you'll trust all hosts regardless if the SSL certificate is invalid. By using this * method you don't need to specify a keystore (see {@link #setKeyStore(String, String)} or trust store (see {@link #setTrustStore(java.security.KeyStore)}. * <p> * This is just a shortcut for: * </p> * <pre> * given().config(RestAssured.config().sslConfig(sslConfig().relaxedHTTPSValidation())). ..; * </pre> * * @param protocol The standard name of the requested protocol. See the SSLContext section in the <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#SSLContext">Java Cryptography Architecture Standard Algorithm Name Documentation</a> for information about standard protocol names. * @return RequestSpecBuilder */ public RequestSpecBuilder setRelaxedHTTPSValidation(String protocol) { spec.relaxedHTTPSValidation(protocol); return this; } /** * Instruct REST Assured to connect to a proxy on the specified host and port. * * @param host The hostname of the proxy to connect to (for example <code>127.0.0.1</code>) * @param port The port of the proxy to connect to (for example <code>8888</code>) * @return RequestSpecBuilder */ public RequestSpecBuilder setProxy(String host, int port) { spec.proxy(host, port); return this; } /** * Instruct REST Assured to connect to a proxy on the specified host on port <code>8888</code>. * * @param host The hostname of the proxy to connect to (for example <code>127.0.0.1</code>). Can also be a URI represented as a String. * @return RequestSpecBuilder * @see #setProxy(String) */ public RequestSpecBuilder setProxy(String host) { spec.proxy(host); return this; } /** * Instruct REST Assured to connect to a proxy on the specified port on localhost. * * @param port The port of the proxy to connect to (for example <code>8888</code>) * @return RequestSpecBuilder * @see #setProxy(int) */ public RequestSpecBuilder setProxy(int port) { spec.proxy(port); return this; } /** * Instruct REST Assured to connect to a proxy on the specified port on localhost with a specific scheme. * * @param host The hostname of the proxy to connect to (for example <code>127.0.0.1</code>) * @param port The port of the proxy to connect to (for example <code>8888</code>) * @param scheme The http scheme (http or https) * @return RequestSpecBuilder */ public RequestSpecBuilder setProxy(String host, int port, String scheme) { spec.proxy(host, port, scheme); return this; } /** * Instruct REST Assured to connect to a proxy using a URI. * * @param uri The URI of the proxy * @return RequestSpecBuilder */ public RequestSpecBuilder setProxy(URI uri) { spec.proxy(uri); return this; } /** * Instruct REST Assured to connect to a proxy using a {@link ProxySpecification}. * * @param proxySpecification The proxy specification to use. * @return RequestSpecBuilder * @see RequestSpecification#proxy(ProxySpecification) */ public RequestSpecBuilder setProxy(ProxySpecification proxySpecification) { spec.proxy(proxySpecification); return this; } /** * Syntactic sugar. * * @return the same RequestSpecBuilder instance */ public RequestSpecBuilder and() { return this; } }
rest-assured/src/main/java/io/restassured/builder/RequestSpecBuilder.java
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.restassured.builder; import io.restassured.RestAssured; import io.restassured.authentication.AuthenticationScheme; import io.restassured.config.LogConfig; import io.restassured.config.RestAssuredConfig; import io.restassured.config.SessionConfig; import io.restassured.filter.Filter; import io.restassured.filter.log.LogBlacklists; import io.restassured.filter.log.LogDetail; import io.restassured.filter.log.RequestLoggingFilter; import io.restassured.http.ContentType; import io.restassured.http.Cookie; import io.restassured.http.Cookies; import io.restassured.internal.RequestSpecificationImpl; import io.restassured.internal.SpecificationMerger; import io.restassured.internal.log.LogRepository; import io.restassured.mapper.ObjectMapper; import io.restassured.mapper.ObjectMapperType; import io.restassured.specification.MultiPartSpecification; import io.restassured.specification.ProxySpecification; import io.restassured.specification.RequestSpecification; import java.io.File; import java.io.InputStream; import java.io.PrintStream; import java.net.URI; import java.security.KeyStore; import java.util.Collection; import java.util.List; import java.util.Map; import static io.restassured.RestAssured.*; import static io.restassured.internal.common.assertion.AssertParameter.notNull; /** * You can use the builder to construct a request specification. The specification can be used as e.g. * <pre> * ResponseSpecification responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); * RequestSpecification requestSpec = new RequestSpecBuilder().addParam("parameter1", "value1").build(); * * given(responseSpec, requestSpec).post("/something"); * </pre> * <p/> * or * <pre> * RequestSpecification requestSpec = new RequestSpecBuilder().addParameter("parameter1", "value1").build(); * * given(). * spec(requestSpec). * expect(). * body("x.y.z", equalTo("something")). * when(). * get("/something"); * </pre> */ public class RequestSpecBuilder { private static final String SSL = "SSL"; private RequestSpecificationImpl spec; public RequestSpecBuilder() { this.spec = (RequestSpecificationImpl) new RequestSpecificationImpl(baseURI, port, basePath, authentication, filters(), requestSpecification, urlEncodingEnabled, config, new LogRepository(), proxy).config(RestAssured.config()); } /** * Specify a String request body (such as e.g. JSON or XML) to be sent with the request. This works for the * POST, PUT and PATCH methods only. Trying to do this for the other http methods will cause an exception to be thrown. * <p/> * * @param body The body to send. * @return The request specification builder */ public RequestSpecBuilder setBody(String body) { spec.body(body); return this; } /** * Specify a byte array request body to be sent with the request. This only works for the * POST http method. Trying to do this for the other http methods will cause an exception to be thrown. * * @param body The body to send. * @return The request specification builder */ public RequestSpecBuilder setBody(byte[] body) { spec.body(body); return this; } /** * Specify an Object request content that will automatically be serialized to JSON or XML and sent with the request. * If the object is a primitive or <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Number.html">Number</a> the object will * be converted to a String and put in the request body. This works for the POST, PUT and PATCH methods only. * Trying to do this for the other http methods will cause an exception to be thrown. * <p/> * * @param object The object to serialize and send with the request * @return The request specification */ public RequestSpecBuilder setBody(Object object) { spec.body(object); return this; } /** * Specify an Object request content that will automatically be serialized to JSON or XML and sent with the request using a specific object mapper. * This works for the POST, PATCH and PUT methods only. Trying to do this for the other http methods will cause an exception to be thrown. * * @param object The object to serialize and send with the request * @param mapper The object mapper * @return The request specification */ public RequestSpecBuilder setBody(Object object, ObjectMapper mapper) { spec.body(object, mapper); return this; } /** * Specify an Object request content that will automatically be serialized to JSON or XML and sent with the request using a specific object mapper type. * This works for the POST, PATCH and PUT methods only. Trying to do this for the other http methods will cause an exception to be thrown. * <p> * Example of use: * <pre> * Message message = new Message(); * message.setMessage("My beautiful message"); * * given(). * body(message, ObjectMapper.GSON). * expect(). * content(equalTo("Response to a beautiful message")). * when(). * post("/beautiful-message"); * </pre> * </p> * * @param object The object to serialize and send with the request * @param mapperType The object mapper type to be used * @return The request specification */ public RequestSpecBuilder setBody(Object object, ObjectMapperType mapperType) { spec.body(object, mapperType); return this; } /** * Add cookies to be sent with the request as Map e.g: * * @param cookies The Map containing the cookie names and their values to set in the request. * @return The request specification builder */ public RequestSpecBuilder addCookies(Map<String, ?> cookies) { spec.cookies(cookies); return this; } /** * Add a detailed cookie * * @param cookie The cookie to add. * @return The request specification builder */ public RequestSpecBuilder addCookie(Cookie cookie) { spec.cookie(cookie); return this; } /** * Add a cookie to be sent with the request. * * @param key The cookie key * @param value The cookie value * @param cookieNameValuePairs Additional cookies values. This will actually create two cookies with the same name but with different values. * @return The request specification builder */ public RequestSpecBuilder addCookie(String key, Object value, Object... cookieNameValuePairs) { spec.cookie(key, value, cookieNameValuePairs); return this; } /** * Add a cookie without value to be sent with the request. * * @param name The cookie name * @return The request specification builder */ public RequestSpecBuilder addCookie(String name) { spec.cookie(name); return this; } /** * Specify multiple detailed cookies that'll be sent with the request. * * @param cookies The cookies to set in the request. * @return The request specification builder * @see RequestSpecification#cookies(Cookies) */ public RequestSpecBuilder addCookies(Cookies cookies) { spec.cookies(cookies); return this; } /** * Add a filter that will be used in the request. * * @param filter The filter to add * @return RequestSpecBuilder builder */ public RequestSpecBuilder addFilter(Filter filter) { spec.filter(filter); return this; } /** * Add filters that will be used in the request. * * @param filters The filters to add * @return RequestSpecBuilder builder */ public RequestSpecBuilder addFilters(List<Filter> filters) { spec.filters(filters); return this; } /** * Add parameters to be sent with the request as Map. * * @param parametersMap The Map containing the parameter names and their values to send with the request. * @return The request specification builder */ public RequestSpecBuilder addParams(Map<String, ?> parametersMap) { spec.params(parametersMap); return this; } /** * Add a parameter to be sent with the request. * * @param parameterName The parameter name * @param parameterValues Zero to many parameter values for this parameter name. * @return The request specification builder */ public RequestSpecBuilder addParam(String parameterName, Object... parameterValues) { spec.param(parameterName, parameterValues); return this; } /** * Add a multi-value parameter to be sent with the request. * * @param parameterName The parameter key * @param parameterValues The parameter values * @return The request specification builder */ public RequestSpecBuilder addParam(String parameterName, Collection<?> parameterValues) { spec.param(parameterName, parameterValues); return this; } /** * Method to remove parameter added with {@link #addParam(String, Object...)} from map. * Removes all values of this parameter * * @param parameterName The parameter key * @return The request specification builder */ public RequestSpecBuilder removeParam(String parameterName) { spec.removeParam(parameterName); return this; } /** * Add a query parameter to be sent with the request. This method is the same as {@link #addParam(String, java.util.Collection)} * for all HTTP methods except POST where this method can be used to differentiate between form and query params. * * @param parameterName The parameter key * @param parameterValues The parameter values * @return The request specification builder * @see #addQueryParam(String, Object...) */ public RequestSpecBuilder addQueryParam(String parameterName, Collection<?> parameterValues) { spec.queryParam(parameterName, parameterValues); return this; } /** * Add query parameters to be sent with the request as a Map. This method is the same as {@link #addParams(java.util.Map)} * for all HTTP methods except POST where this method can be used to differentiate between form and query params. * * @param parametersMap The Map containing the parameter names and their values to send with the request. * @return The request specification builder */ public RequestSpecBuilder addQueryParams(Map<String, ?> parametersMap) { spec.queryParams(parametersMap); return this; } /** * Add a query parameter to be sent with the request. This method is the same as {@link #addParam(String, Object...)} )} * for all HTTP methods except POST where this method can be used to differentiate between form and query params. * * @param parameterName The parameter key * @param parameterValues Zero to many parameter values for this parameter name. * @return The request specification builder */ public RequestSpecBuilder addQueryParam(String parameterName, Object... parameterValues) { spec.queryParam(parameterName, parameterValues); return this; } /** * Method to remove parameter added with from map. * Removes all values of this parameter * * @param parameterName The parameter key * @return The request specification builder */ public RequestSpecBuilder removeQueryParam(String parameterName) { spec.removeQueryParam(parameterName); return this; } /** * Add a form parameter to be sent with the request. This method is the same as {@link #addParam(String, java.util.Collection)} * for all HTTP methods except PUT where this method can be used to differentiate between form and query params. * * @param parameterName The parameter key * @param parameterValues The parameter values * @return The request specification builder * @see #addFormParam(String, Object...) */ public RequestSpecBuilder addFormParam(String parameterName, Collection<?> parameterValues) { spec.formParam(parameterName, parameterValues); return this; } /** * Add query parameters to be sent with the request as a Map. This method is the same as {@link #addParams(java.util.Map)} * for all HTTP methods except POST where this method can be used to differentiate between form and query params. * * @param parametersMap The Map containing the parameter names and their values to send with the request. * @return The request specification builder */ public RequestSpecBuilder addFormParams(Map<String, ?> parametersMap) { spec.formParams(parametersMap); return this; } /** * Add a form parameter to be sent with the request. This method is the same as {@link #addParam(String, Object...)} )} * for all HTTP methods except PUT where this method can be used to differentiate between form and query params. * * @param parameterName The parameter key * @param parameterValues Zero to many parameter values for this parameter name. * @return The request specification builder * @see #addFormParam(String, Object...) */ public RequestSpecBuilder addFormParam(String parameterName, Object... parameterValues) { spec.formParam(parameterName, parameterValues); return this; } /** * Method to remove parameter added with {@link #addFormParam(String, Object...)} from map. * Removes all values of this parameter * * @param parameterName The parameter key * @return The request specification builder */ public RequestSpecBuilder removeFormParam(String parameterName) { spec.removeFormParam(parameterName); return this; } /** * Specify a path parameter. Path parameters are used to improve readability of the request path. E.g. instead * of writing: * <pre> * expect().statusCode(200).when().get("/item/"+myItem.getItemNumber()+"/buy/"+2); * </pre> * you can write: * <pre> * given(). * pathParam("itemNumber", myItem.getItemNumber()). * pathParam("amount", 2). * expect(). * statusCode(200). * when(). * get("/item/{itemNumber}/buy/{amount}"); * </pre> * <p/> * which improves readability and allows the path to be reusable in many tests. Another alternative is to use: * <pre> * expect().statusCode(200).when().get("/item/{itemNumber}/buy/{amount}", myItem.getItemNumber(), 2); * </pre> * * @param parameterName The parameter key * @param parameterValue The parameter value * @return The request specification */ public RequestSpecBuilder addPathParam(String parameterName, Object parameterValue) { spec.pathParam(parameterName, parameterValue); return this; } /** * Specify multiple path parameter name-value pairs. Path parameters are used to improve readability of the request path. E.g. instead * of writing: * <pre> * expect().statusCode(200).when().get("/item/"+myItem.getItemNumber()+"/buy/"+2); * </pre> * you can write: * <pre> * given(). * pathParam("itemNumber", myItem.getItemNumber(), "amount", 2). * expect(). * statusCode(200). * when(). * get("/item/{itemNumber}/buy/{amount}"); * </pre> * <p/> * which improves readability and allows the path to be reusable in many tests. Another alternative is to use: * <pre> * expect().statusCode(200).when().get("/item/{itemNumber}/buy/{amount}", myItem.getItemNumber(), 2); * </pre> * * @param firstParameterName The name of the first parameter * @param firstParameterValue The value of the first parameter * @param parameterNameValuePairs Additional parameters in name-value pairs. * @return The request specification */ public RequestSpecBuilder addPathParams(String firstParameterName, Object firstParameterValue, Object... parameterNameValuePairs) { spec.pathParams(firstParameterName, firstParameterValue, parameterNameValuePairs); return this; } /** * Specify multiple path parameter name-value pairs. Path parameters are used to improve readability of the request path. E.g. instead * of writing: * <pre> * expect().statusCode(200).when().get("/item/"+myItem.getItemNumber()+"/buy/"+2); * </pre> * you can write: * <pre> * Map&lt;String,Object&gt; pathParams = new HashMap&lt;String,Object&gt;(); * pathParams.add("itemNumber",myItem.getItemNumber()); * pathParams.add("amount",2); * * given(). * pathParameters(pathParams). * expect(). * statusCode(200). * when(). * get("/item/{itemNumber}/buy/{amount}"); * </pre> * <p/> * which improves readability and allows the path to be reusable in many tests. Another alternative is to use: * <pre> * expect().statusCode(200).when().get("/item/{itemNumber}/buy/{amount}", myItem.getItemNumber(), 2); * </pre> * * @param parameterNameValuePairs A map containing the path parameters. * @return The request specification */ public RequestSpecBuilder addPathParams(Map<String, ?> parameterNameValuePairs) { spec.pathParams(parameterNameValuePairs); return this; } /** * Method to remove parameter added with {@link #addPathParam(String, Object)} from map. * Removes all values of this parameter. * * @param parameterName The parameter key * @return The request specification builder */ public RequestSpecBuilder removePathParam(String parameterName) { spec.removePathParam(parameterName); return this; } /** * Specify a keystore. * <pre> * RestAssured.keyStore("/truststore_javanet.jks", "test1234"); * </pre> * or * <pre> * given().keyStore("/truststore_javanet.jks", "test1234"). .. * </pre> * </p> * * @param pathToJks The path to the JKS * @param password The store pass */ public RequestSpecBuilder setKeyStore(String pathToJks, String password) { spec.keyStore(pathToJks, password); return this; } /** * The following documentation is taken from <a href="HTTP Builder">https://github.com/jgritman/httpbuilder/wiki/SSL</a>: * <p> * <h1>SSL Configuration</h1> * <p/> * SSL should, for the most part, "just work." There are a few situations where it is not completely intuitive. You can follow the example below, or see HttpClient's SSLSocketFactory documentation for more information. * <p/> * <h1>SSLPeerUnverifiedException</h1> * <p/> * If you can't connect to an SSL website, it is likely because the certificate chain is not trusted. This is an Apache HttpClient issue, but explained here for convenience. To correct the untrusted certificate, you need to import a certificate into an SSL truststore. * <p/> * First, export a certificate from the website using your browser. For example, if you go to https://dev.java.net in Firefox, you will probably get a warning in your browser. Choose "Add Exception," "Get Certificate," "View," "Details tab." Choose a certificate in the chain and export it as a PEM file. You can view the details of the exported certificate like so: * <pre> * $ keytool -printcert -file EquifaxSecureGlobaleBusinessCA-1.crt * Owner: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US * Issuer: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US * Serial number: 1 * Valid from: Mon Jun 21 00:00:00 EDT 1999 until: Sun Jun 21 00:00:00 EDT 2020 * Certificate fingerprints: * MD5: 8F:5D:77:06:27:C4:98:3C:5B:93:78:E7:D7:7D:9B:CC * SHA1: 7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45 * Signature algorithm name: MD5withRSA * Version: 3 * .... * </pre> * Now, import that into a Java keystore file: * <pre> * $ keytool -importcert -alias "equifax-ca" -file EquifaxSecureGlobaleBusinessCA-1.crt -keystore truststore_javanet.jks -storepass test1234 * Owner: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US * Issuer: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US * Serial number: 1 * Valid from: Mon Jun 21 00:00:00 EDT 1999 until: Sun Jun 21 00:00:00 EDT 2020 * Certificate fingerprints: * MD5: 8F:5D:77:06:27:C4:98:3C:5B:93:78:E7:D7:7D:9B:CC * SHA1: 7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45 * Signature algorithm name: MD5withRSA * Version: 3 * ... * Trust this certificate? [no]: yes * Certificate was added to keystore * </pre> * Now you want to use this truststore in your client: * <pre> * RestAssured.trustStore("/truststore_javanet.jks", "test1234"); * </pre> * or * <pre> * given().trustStore("/truststore_javanet.jks", "test1234"). .. * </pre> * </p> * * @param pathToJks The path to the JKS * @param password The store pass */ public RequestSpecBuilder setTrustStore(String pathToJks, String password) { spec.trustStore(pathToJks, password); return this; } /** * The following documentation is taken from <a href="HTTP Builder">https://github.com/jgritman/httpbuilder/wiki/SSL</a>: * <p> * <h1>SSL Configuration</h1> * <p/> * SSL should, for the most part, "just work." There are a few situations where it is not completely intuitive. You can follow the example below, or see HttpClient's SSLSocketFactory documentation for more information. * <p/> * <h1>SSLPeerUnverifiedException</h1> * <p/> * If you can't connect to an SSL website, it is likely because the certificate chain is not trusted. This is an Apache HttpClient issue, but explained here for convenience. To correct the untrusted certificate, you need to import a certificate into an SSL truststore. * <p/> * First, export a certificate from the website using your browser. For example, if you go to https://dev.java.net in Firefox, you will probably get a warning in your browser. Choose "Add Exception," "Get Certificate," "View," "Details tab." Choose a certificate in the chain and export it as a PEM file. You can view the details of the exported certificate like so: * <pre> * $ keytool -printcert -file EquifaxSecureGlobaleBusinessCA-1.crt * Owner: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US * Issuer: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US * Serial number: 1 * Valid from: Mon Jun 21 00:00:00 EDT 1999 until: Sun Jun 21 00:00:00 EDT 2020 * Certificate fingerprints: * MD5: 8F:5D:77:06:27:C4:98:3C:5B:93:78:E7:D7:7D:9B:CC * SHA1: 7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45 * Signature algorithm name: MD5withRSA * Version: 3 * .... * </pre> * Now, import that into a Java keystore file: * <pre> * $ keytool -importcert -alias "equifax-ca" -file EquifaxSecureGlobaleBusinessCA-1.crt -keystore truststore_javanet.jks -storepass test1234 * Owner: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US * Issuer: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US * Serial number: 1 * Valid from: Mon Jun 21 00:00:00 EDT 1999 until: Sun Jun 21 00:00:00 EDT 2020 * Certificate fingerprints: * MD5: 8F:5D:77:06:27:C4:98:3C:5B:93:78:E7:D7:7D:9B:CC * SHA1: 7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45 * Signature algorithm name: MD5withRSA * Version: 3 * ... * Trust this certificate? [no]: yes * Certificate was added to keystore * </pre> * Now you want to use this truststore in your client: * <pre> * RestAssured.trustStore("/truststore_javanet.jks", "test1234"); * </pre> * or * <pre> * given().trustStore("/truststore_javanet.jks", "test1234"). .. * </pre> * </p> * * @param pathToJks The path to the JKS * @param password The store pass */ public RequestSpecBuilder setTrustStore(File pathToJks, String password) { spec.trustStore(pathToJks, password); return this; } /** * Add headers to be sent with the request as Map. * * @param headers The Map containing the header names and their values to send with the request. * @return The request specification builder */ public RequestSpecBuilder addHeaders(Map<String, String> headers) { spec.headers(headers); return this; } /** * Add a header to be sent with the request e.g: * * @param headerName The header name * @param headerValue The header value * @return The request specification builder */ public RequestSpecBuilder addHeader(String headerName, String headerValue) { spec.header(headerName, headerValue); return this; } /** * Specify the content type of the request. * * @param contentType The content type of the request * @return The request specification builder * @see ContentType */ public RequestSpecBuilder setContentType(ContentType contentType) { spec.contentType(contentType); return this; } /** * Specify the content type of the request as string. * * @param contentType The content type of the request * @return The request specification builder */ public RequestSpecBuilder setContentType(String contentType) { spec.contentType(contentType); return this; } /** * Specify the accept header of the request. This just a shortcut for: * <pre> * addHeader("Accept", contentType); * </pre> * * @param contentType The content type whose accept header {@link ContentType#getAcceptHeader()} will be used as Accept header in the request. * @return The request specification * @see ContentType * @see #addHeader(String, String) */ public RequestSpecBuilder setAccept(ContentType contentType) { spec.accept(contentType); return this; } /** * Specify the accept header of the request. This just a shortcut for: * <pre> * header("Accept", contentType); * </pre> * * @param mediaTypes The media type(s) that will be used as Accept header in the request. * @return The request specification * @see ContentType * @see #addHeader(String, String) */ public RequestSpecBuilder setAccept(String mediaTypes) { spec.accept(mediaTypes); return this; } /** * Specify a multi-part specification. Use this method if you need to specify content-type etc. * * @param multiPartSpecification Multipart specification * @return The request specification */ public RequestSpecBuilder addMultiPart(MultiPartSpecification multiPartSpecification) { spec.multiPart(multiPartSpecification); return this; } /** * Specify a file to upload to the server using multi-part form data uploading. * It will assume that the control name is <tt>file</tt> and the content-type is <tt>application/octet-stream</tt>. * If this is not what you want please use an overloaded method. * * @param file The file to upload * @return The request specification */ public RequestSpecBuilder addMultiPart(File file) { spec.multiPart(file); return this; } /** * Specify a file to upload to the server using multi-part form data uploading with a specific * control name. It will use the content-type <tt>application/octet-stream</tt>. * If this is not what you want please use an overloaded method. * * @param file The file to upload * @param controlName Defines the control name of the body part. In HTML this is the attribute name of the input tag. * @return The request specification */ public RequestSpecBuilder addMultiPart(String controlName, File file) { spec.multiPart(controlName, file); return this; } /** * Specify a file to upload to the server using multi-part form data uploading with a specific * control name and content-type. * * @param file The file to upload * @param controlName Defines the control name of the body part. In HTML this is the attribute name of the input tag. * @param mimeType The content-type * @return The request specification */ public RequestSpecBuilder addMultiPart(String controlName, File file, String mimeType) { spec.multiPart(controlName, file, mimeType); return this; } /** * Specify a byte-array to upload to the server using multi-part form data. * It will use the content-type <tt>application/octet-stream</tt>. If this is not what you want please use an overloaded method. * * @param controlName Defines the control name of the body part. In HTML this is the attribute name of the input tag. * @param fileName The name of the content you're uploading * @param bytes The bytes you want to send * @return The request specification */ public RequestSpecBuilder addMultiPart(String controlName, String fileName, byte[] bytes) { spec.multiPart(controlName, fileName, bytes); return this; } /** * Specify a byte-array to upload to the server using multi-part form data. * * @param controlName Defines the control name of the body part. In HTML this is the attribute name of the input tag. * @param fileName The name of the content you're uploading * @param bytes The bytes you want to send * @param mimeType The content-type * @return The request specification */ public RequestSpecBuilder addMultiPart(String controlName, String fileName, byte[] bytes, String mimeType) { spec.multiPart(controlName, fileName, bytes, mimeType); return this; } /** * Specify an inputstream to upload to the server using multi-part form data. * It will use the content-type <tt>application/octet-stream</tt>. If this is not what you want please use an overloaded method. * * @param controlName Defines the control name of the body part. In HTML this is the attribute name of the input tag. * @param fileName The name of the content you're uploading * @param stream The stream you want to send * @return The request specification */ public RequestSpecBuilder addMultiPart(String controlName, String fileName, InputStream stream) { spec.multiPart(controlName, fileName, stream); return this; } /** * Specify an inputstream to upload to the server using multi-part form data. * * @param controlName Defines the control name of the body part. In HTML this is the attribute name of the input tag. * @param fileName The name of the content you're uploading * @param stream The stream you want to send * @param mimeType The content-type * @return The request specification */ public RequestSpecBuilder addMultiPart(String controlName, String fileName, InputStream stream, String mimeType) { spec.multiPart(controlName, fileName, stream, mimeType); return this; } /** * Specify a string to send to the server using multi-part form data. * It will use the content-type <tt>text/plain</tt>. If this is not what you want please use an overloaded method. * * @param controlName Defines the control name of the body part. In HTML this is the attribute name of the input tag. * @param contentBody The string to send * @return The request specification */ public RequestSpecBuilder addMultiPart(String controlName, String contentBody) { spec.multiPart(controlName, contentBody); return this; } /** * Specify a string to send to the server using multi-part form data with a specific mime-type. * * @param controlName Defines the control name of the body part. In HTML this is the attribute name of the input tag. * @param contentBody The string to send * @param mimeType The mime-type * @return The request specification */ public RequestSpecBuilder addMultiPart(String controlName, String contentBody, String mimeType) { spec.multiPart(controlName, contentBody, mimeType); return this; } /** * If you need to specify some credentials when performing a request. * * @return The request specification builder */ public RequestSpecBuilder setAuth(AuthenticationScheme auth) { spec.setAuthenticationScheme(auth); return this; } /** * Specify the port. * * @param port The port of URI * @return The request specification builder */ public RequestSpecBuilder setPort(int port) { spec.port(port); return this; } /** * Specifies if Rest Assured should url encode the URL automatically. Usually this is a recommended but in some cases * e.g. the query parameters are already be encoded before you provide them to Rest Assured then it's useful to disable * URL encoding. * * @param isEnabled Specify whether or not URL encoding should be enabled or disabled. * @return The request specification builder */ public RequestSpecBuilder setUrlEncodingEnabled(boolean isEnabled) { spec.urlEncodingEnabled(isEnabled); return this; } /** * Set the session id for this request. It will use the configured session id name from the configuration (by default this is {@value SessionConfig#DEFAULT_SESSION_ID_NAME}). * You can configure the session id name by using: * <pre> * RestAssured.config = newConfig().sessionConfig(new SessionConfig().sessionIdName(&lt;sessionIdName&gt;)); * </pre> * or you can use the {@link #setSessionId(String, String)} method to set it for this request only. * * @param sessionIdValue The session id value. * @return The request specification */ public RequestSpecBuilder setSessionId(String sessionIdValue) { spec.sessionId(sessionIdValue); return this; } /** * Set the session id name and value for this request. It'll override the default session id name from the configuration (by default this is {@value SessionConfig#DEFAULT_SESSION_ID_NAME}). * You can configure the default session id name by using: * <pre> * RestAssured.config = newConfig().sessionConfig(new SessionConfig().sessionIdName(&lt;sessionIdName&gt;)); * </pre> * and then you can use the {@link RequestSpecBuilder#setSessionId(String)} method to set the session id value without specifying the name for each request. * * @param sessionIdName The session id name * @param sessionIdValue The session id value. * @return The request specification */ public RequestSpecBuilder setSessionId(String sessionIdName, String sessionIdValue) { spec.sessionId(sessionIdName, sessionIdValue); return this; } /** * Merge this builder with settings from another specification. Note that the supplied specification * can overwrite data in the current specification. The following settings are overwritten: * <ul> * <li>Port</li> * <li>Authentication scheme</ * <li>Content type</li> * <li>Request body</li> * </ul> * The following settings are merged: * <ul> * <li>Parameters</li> * <li>Cookies</li> * <li>Headers</li> * <li>Filters</li> * </ul> * * @param specification The specification to add * @return The request specification builder */ public RequestSpecBuilder addRequestSpecification(RequestSpecification specification) { if (!(specification instanceof RequestSpecificationImpl)) { throw new IllegalArgumentException("Specification must be of type " + RequestSpecificationImpl.class.getClass() + "."); } RequestSpecificationImpl rs = (RequestSpecificationImpl) specification; SpecificationMerger.merge((RequestSpecificationImpl) spec, rs); return this; } /** * Define a configuration for redirection settings and http client parameters. * * @param config The configuration to use for this request. If <code>null</code> no config will be used. * @return The request specification builder */ public RequestSpecBuilder setConfig(RestAssuredConfig config) { spec.config(config); return this; } /** * Build RequestSpecBuilder. * * @return The assembled request specification */ public RequestSpecification build() { return spec; } /** * Add the baseUri property from the RequestSpecBuilder instead of using static field RestAssured.baseURI. * <p/> * <pre> * RequestSpecBuilder builder = new RequestSpecBuilder(); * builder.setBaseUri("http://example.com"); * RequestSpecification specs = builder.build(); * given().specification(specs) * </pre> * * @param uri The URI * @return RequestSpecBuilder */ public RequestSpecBuilder setBaseUri(String uri) { spec.baseUri(uri); return this; } /** * Add the baseUri property from the RequestSpecBuilder instead of using static field RestAssured.baseURI. * <p/> * <pre> * RequestSpecification specs = new RequestSpecBuilder() * .setBaseUri(URI.create("http://example.com")) * .build(); * given().specification(specs) * </pre> * uses {@link #setBaseUri(String)} * * @param uri The URI * @return RequestSpecBuilder */ public RequestSpecBuilder setBaseUri(URI uri) { return setBaseUri(notNull(uri, "Base URI").toString()); } /** * Set the base path that's prepended to each path by REST assured when making requests. E.g. let's say that * the base uri is <code>http://localhost</code> and <code>basePath</code> is <code>/resource</code> * then * <p/> * <pre> * ..when().get("/something"); * </pre> * <p/> * will make a request to <code>http://localhost/resource</code>. * * @param path The base path to set. * @return RequestSpecBuilder */ public RequestSpecBuilder setBasePath(String path) { spec.basePath(path); return this; } /** * Enabled logging with the specified log detail. Set a {@link LogConfig} to configure the print stream and pretty printing options. * * @param logDetail The log detail. * @return RequestSpecBuilder */ public RequestSpecBuilder log(LogDetail logDetail) { notNull(logDetail, LogDetail.class); RestAssuredConfig restAssuredConfig = spec.getConfig(); LogConfig logConfig; if (restAssuredConfig == null) { logConfig = new RestAssuredConfig().getLogConfig(); } else { logConfig = restAssuredConfig.getLogConfig(); } PrintStream printStream = logConfig.defaultStream(); boolean prettyPrintingEnabled = logConfig.isPrettyPrintingEnabled(); boolean shouldUrlEncodeRequestUri = logConfig.shouldUrlEncodeRequestUri(); spec.filter(new RequestLoggingFilter(logDetail, prettyPrintingEnabled, printStream, shouldUrlEncodeRequestUri)); return this; } /** * Blacklists certain components of an HTTP request. * * @param logBlacklists The blacklists to be used during logging. * @return RequestSpecBuilder */ public RequestSpecBuilder logBlacklists(final LogBlacklists logBlacklists) { for (Filter filter : spec.getDefinedFilters()) { if (filter instanceof RequestLoggingFilter) { RequestLoggingFilter requestLoggingFilter = (RequestLoggingFilter) filter; requestLoggingFilter.setLogBlacklists(logBlacklists); } } return this; } /** * Use the supplied truststore for HTTPS requests. Shortcut for: * <p> * <pre> * given().config(RestAssured.config().sslConfig(sslConfig().trustStore(truststore)); * </pre> * </p> * <p/> * * @param trustStore The truststore. * @return RequestSpecBuilder * @see #setKeyStore(String, String) */ public RequestSpecBuilder setTrustStore(KeyStore trustStore) { spec.trustStore(trustStore); return this; } /** * Use the supplied keystore for HTTPS requests. Shortcut for: * <p> * <pre> * given().config(RestAssured.config().sslConfig(sslConfig().keyStore(keystore)); * </pre> * </p> * <p/> * * @param keyStore The truststore. * @return RequestSpecBuilder * @see #setKeyStore(String, String) */ public RequestSpecBuilder setKeyStore(KeyStore keyStore) { spec.keyStore(keyStore); return this; } /** * Use relaxed HTTP validation with SSLContext protocol {@value #SSL}. This means that you'll trust all hosts regardless if the SSL certificate is invalid. By using this * method you don't need to specify a keystore (see {@link #setKeyStore(String, String)} or trust store (see {@link #setTrustStore(java.security.KeyStore)}. * <p> * This is just a shortcut for: * </p> * <pre> * given().config(RestAssured.config().sslConfig(sslConfig().relaxedHTTPSValidation())). ..; * </pre> * * @return RequestSpecBuilder */ public RequestSpecBuilder setRelaxedHTTPSValidation() { return setRelaxedHTTPSValidation(SSL); } /** * Use relaxed HTTP validation with a given SSLContext protocol. This means that you'll trust all hosts regardless if the SSL certificate is invalid. By using this * method you don't need to specify a keystore (see {@link #setKeyStore(String, String)} or trust store (see {@link #setTrustStore(java.security.KeyStore)}. * <p> * This is just a shortcut for: * </p> * <pre> * given().config(RestAssured.config().sslConfig(sslConfig().relaxedHTTPSValidation())). ..; * </pre> * * @param protocol The standard name of the requested protocol. See the SSLContext section in the <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#SSLContext">Java Cryptography Architecture Standard Algorithm Name Documentation</a> for information about standard protocol names. * @return RequestSpecBuilder */ public RequestSpecBuilder setRelaxedHTTPSValidation(String protocol) { spec.relaxedHTTPSValidation(protocol); return this; } /** * Instruct REST Assured to connect to a proxy on the specified host and port. * * @param host The hostname of the proxy to connect to (for example <code>127.0.0.1</code>) * @param port The port of the proxy to connect to (for example <code>8888</code>) * @return RequestSpecBuilder */ public RequestSpecBuilder setProxy(String host, int port) { spec.proxy(host, port); return this; } /** * Instruct REST Assured to connect to a proxy on the specified host on port <code>8888</code>. * * @param host The hostname of the proxy to connect to (for example <code>127.0.0.1</code>). Can also be a URI represented as a String. * @return RequestSpecBuilder * @see #setProxy(String) */ public RequestSpecBuilder setProxy(String host) { spec.proxy(host); return this; } /** * Instruct REST Assured to connect to a proxy on the specified port on localhost. * * @param port The port of the proxy to connect to (for example <code>8888</code>) * @return RequestSpecBuilder * @see #setProxy(int) */ public RequestSpecBuilder setProxy(int port) { spec.proxy(port); return this; } /** * Instruct REST Assured to connect to a proxy on the specified port on localhost with a specific scheme. * * @param host The hostname of the proxy to connect to (for example <code>127.0.0.1</code>) * @param port The port of the proxy to connect to (for example <code>8888</code>) * @param scheme The http scheme (http or https) * @return RequestSpecBuilder */ public RequestSpecBuilder setProxy(String host, int port, String scheme) { spec.proxy(host, port, scheme); return this; } /** * Instruct REST Assured to connect to a proxy using a URI. * * @param uri The URI of the proxy * @return RequestSpecBuilder */ public RequestSpecBuilder setProxy(URI uri) { spec.proxy(uri); return this; } /** * Instruct REST Assured to connect to a proxy using a {@link ProxySpecification}. * * @param proxySpecification The proxy specification to use. * @return RequestSpecBuilder * @see RequestSpecification#proxy(ProxySpecification) */ public RequestSpecBuilder setProxy(ProxySpecification proxySpecification) { spec.proxy(proxySpecification); return this; } /** * Syntactic sugar. * * @return the same RequestSpecBuilder instance */ public RequestSpecBuilder and() { return this; } }
Fixed wrongly typed cast from groovy into java
rest-assured/src/main/java/io/restassured/builder/RequestSpecBuilder.java
Fixed wrongly typed cast from groovy into java
Java
apache-2.0
c995b15d4772d53db9826973cb300ec388feb37c
0
walletma/ansj_seg,shibing624/ansj_seg,walletma/ansj_seg,hitscs/ansj_seg,waiteryee1/ansj_seg,NLPchina/ansj_seg,hitscs/ansj_seg,chaoliu1024/ansj_seg,waiteryee1/ansj_seg,chaoliu1024/ansj_seg,shibing624/ansj_seg,XYUU/ansj_seg,avastms/ansj_seg,avastms/ansj_seg
package org.ansj.util; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import org.ansj.domain.Nature; import org.ansj.domain.Term; import org.ansj.library.UserDefineLibrary; import org.nlpcn.commons.lang.tire.domain.Forest; /* * 停用词过滤,修正词性到用户词性. */ public class FilterModifWord { private static Set<String> FILTER = new HashSet<String>(); private static String TAG = "#"; private static boolean isTag = false; // 停用词正则表达式 private static Pattern stopwordPattern; public static void insertStopWords(List<String> filterWords) { FILTER.addAll(filterWords); } public static void insertStopWord(String... filterWord) { for (String word : filterWord) { FILTER.add(word); } } public static void insertStopNatures(String... filterNatures) { isTag = true; for (String natureStr : filterNatures) { FILTER.add(TAG + natureStr); } } public static void insertStopRegex(String regex) { stopwordPattern = Pattern.compile(regex); } public static void removeStopRegex() { stopwordPattern = null; } /* * 停用词过滤并且修正词性 */ public static List<Term> modifResult(List<Term> all) { List<Term> result = new ArrayList<Term>(); try { for (Term term : all) { if (FILTER.size() > 0 && (FILTER.contains(term.getName()) || (isTag && FILTER .contains(TAG + term.natrue().natureStr)))) { continue; } // 添加对正则停用词的支持 if ((stopwordPattern != null) && stopwordPattern.matcher(term.getName()).matches()) { continue; } String[] params = UserDefineLibrary.getParams(term.getName()); if (params != null) { term.setNature(new Nature(params[0])); } result.add(term); } } catch (Exception e) { System.err .println("FilterStopWord.updateDic can not be null , " + "you must use set FilterStopWord.setUpdateDic(map) or use method set map"); } return result; } /* * 停用词过滤并且修正词性 */ public static List<Term> modifResult(List<Term> all, Forest... forests) { List<Term> result = new ArrayList<Term>(); try { for (Term term : all) { if (FILTER.size() > 0 && (FILTER.contains(term.getName()) || FILTER.contains(TAG + term.natrue().natureStr))) { continue; } // 添加对正则停用词的支持 if ((stopwordPattern != null) && stopwordPattern.matcher(term.getName()).matches()) { continue; } for (Forest forest : forests) { String[] params = UserDefineLibrary.getParams(forest, term.getName()); if (params != null) { term.setNature(new Nature(params[0])); } } result.add(term); } } catch (Exception e) { System.err .println("FilterStopWord.updateDic can not be null , " + "you must use set FilterStopWord.setUpdateDic(map) or use method set map"); } return result; } }
src/main/java/org/ansj/util/FilterModifWord.java
package org.ansj.util; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import org.ansj.domain.Nature; import org.ansj.domain.Term; import org.ansj.library.UserDefineLibrary; import org.nlpcn.commons.lang.tire.domain.Forest; /* * 停用词过滤,修正词性到用户词性. */ public class FilterModifWord { private static Set<String> FILTER = new HashSet<String>(); private static String TAG = "#"; private static boolean isTag = false; // 停用词正则表达式 private static Pattern stopwordPattern; public static void insertStopWords(List<String> filterWords) { FILTER.addAll(filterWords); } public static void insertStopWord(String... filterWord) { for (String word : filterWord) { FILTER.add(word); } } public static void insertStopNatures(String... filterNatures) { isTag = true; for (String natureStr : filterNatures) { FILTER.add(TAG + natureStr); } } public static void insertStopRegex(String regex) { stopwordPattern = Pattern.compile(regex); } public static void removeStopRegex(String regex) { stopwordPattern = null; } /* * 停用词过滤并且修正词性 */ public static List<Term> modifResult(List<Term> all) { List<Term> result = new ArrayList<Term>(); try { for (Term term : all) { if (FILTER.size() > 0 && (FILTER.contains(term.getName()) || (isTag && FILTER .contains(TAG + term.natrue().natureStr)))) { continue; } // 添加对正则停用词的支持 if ((stopwordPattern != null) && stopwordPattern.matcher(term.getName()).matches()) { continue; } String[] params = UserDefineLibrary.getParams(term.getName()); if (params != null) { term.setNature(new Nature(params[0])); } result.add(term); } } catch (Exception e) { System.err .println("FilterStopWord.updateDic can not be null , " + "you must use set FilterStopWord.setUpdateDic(map) or use method set map"); } return result; } /* * 停用词过滤并且修正词性 */ public static List<Term> modifResult(List<Term> all, Forest... forests) { List<Term> result = new ArrayList<Term>(); try { for (Term term : all) { if (FILTER.size() > 0 && (FILTER.contains(term.getName()) || FILTER.contains(TAG + term.natrue().natureStr))) { continue; } // 添加对正则停用词的支持 if ((stopwordPattern != null) && stopwordPattern.matcher(term.getName()).matches()) { continue; } for (Forest forest : forests) { String[] params = UserDefineLibrary.getParams(forest, term.getName()); if (params != null) { term.setNature(new Nature(params[0])); } } result.add(term); } } catch (Exception e) { System.err .println("FilterStopWord.updateDic can not be null , " + "you must use set FilterStopWord.setUpdateDic(map) or use method set map"); } return result; } }
增加对停用词正则表达式的支持 增加对停用词正则表达式的支持
src/main/java/org/ansj/util/FilterModifWord.java
增加对停用词正则表达式的支持
Java
apache-2.0
c2ca9cb67199ffbc5b5be33b22cbceca73436980
0
Reissner/maven-latex-plugin,Reissner/maven-latex-plugin,Reissner/maven-latex-plugin,Reissner/maven-latex-plugin,Reissner/maven-latex-plugin
/* * The akquinet maven-latex-plugin project * * Copyright (c) 2011 by akquinet tech@spree GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.m2latex.core; import org.m2latex.mojo.MavenLogWrapper; import org.m2latex.mojo.PdfMojo; import java.io.File; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugin.logging.SystemStreamLog; import org.easymock.MockControl; import org.junit.Test; import org.junit.Ignore; public class LatexProcessorTest { private MockControl executorCtrl = MockControl .createStrictControl(CommandExecutor.class); private CommandExecutor executor = (CommandExecutor) executorCtrl.getMock(); private MockControl fileUtilsCtrl = MockControl .createStrictControl(TexFileUtils.class); private TexFileUtils fileUtils = (TexFileUtils) fileUtilsCtrl.getMock(); private Settings settings = new Settings(); private LogWrapper log = new MavenLogWrapper(new SystemStreamLog()); private LatexProcessor processor = new LatexProcessor (settings, executor, log, fileUtils, new PdfMojo()); private File texFile = new File(System.getProperty("tmp.dir"), "test.tex"); private File auxFile = new File(System.getProperty("tmp.dir"), "test.aux"); private File logFile = new File(System.getProperty("tmp.dir"), "test.log"); private File blgFile = new File(System.getProperty("tmp.dir"), "test.blg"); private File idxFile = new File(System.getProperty("tmp.dir"), "test.idx"); private File ilgFile = new File(System.getProperty("tmp.dir"), "test.ilg"); private File gloFile = new File(System.getProperty("tmp.dir"), "test.glo"); private File istFile = new File(System.getProperty("tmp.dir"), "test.ist"); private File xdyFile = new File(System.getProperty("tmp.dir"), "test.xdy"); private File glsFile = new File(System.getProperty("tmp.dir"), "test.gls"); private File glgFile = new File(System.getProperty("tmp.dir"), "test.glg"); // this one does never exist. private File xxxFile = new File(System.getProperty("tmp.dir"), "test"); private File tocFile = new File(System.getProperty("tmp.dir"), "test.toc"); private File lofFile = new File(System.getProperty("tmp.dir"), "test.lof"); private File lotFile = new File(System.getProperty("tmp.dir"), "test.lot"); private String[] tex2htmlArgsExpected = new String[] { this.texFile.getName(), "html,2", "", "", settings.getLatex2pdfOptions() }; //@Ignore @Test public void testProcessLatexSimple() throws BuildFailureException { mockConstrLatexMainDesc(); // run latex mockRunLatex(); // run bibtex by need: no mockRunBibtexByNeed(false); // run makeIndex by need: no mockRunMakeIndexByNeed(false); // run makeGlossary by need: no mockRunMakeGlossaryByNeed(false); // determine from presence of toc, lof, lot (and idx and other criteria) // whether to rerun latex: no fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_TOC); fileUtilsCtrl.setReturnValue(tocFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_LOF); fileUtilsCtrl.setReturnValue(lofFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_LOT); fileUtilsCtrl.setReturnValue(lotFile); // determine whether to rerun latex or makeindex: no mockNeedAnotherLatexRun(false); mockNeedAnotherMakeIndexRun(false); // // detect bad boxes and warnings: none // fileUtils.matchInFile(logFile, LatexProcessor.PATTERN_OUFULL_HVBOX); // fileUtilsCtrl.setReturnValue( false ); // fileUtils.matchInFile(logFile, // this.settings.getPatternWarnLatex()); // fileUtilsCtrl.setReturnValue( false ); replay(); processor.processLatex2pdf(this.texFile); verify(); } //@Ignore @Test public void testProcessLatexWithBibtex() throws BuildFailureException { mockConstrLatexMainDesc(); // run latex mockRunLatex(); // run bibtex by need: yes mockRunBibtexByNeed(true); // run makeIndex by need: no mockRunMakeIndexByNeed(false); // run makeGlossary by need: no mockRunMakeGlossaryByNeed(false); // run latex twice because bibtex had been run mockRunLatex(); //mockRunLatex(); // determine whether to rerun latex and run until no //mockNeedAnotherLatexRun(true); // no, because bibtex triggers two latex runs mockNeedAnotherMakeIndexRun(false); mockRunLatex(); mockNeedAnotherLatexRun(false); mockNeedAnotherMakeIndexRun(false); // // detect bad boxes and warnings: none // fileUtils.matchInFile(logFile, LatexProcessor.PATTERN_OUFULL_HVBOX); // fileUtilsCtrl.setReturnValue( false ); // fileUtils.matchInFile(logFile, // this.settings.getPatternWarnLatex()); // fileUtilsCtrl.setReturnValue( false ); replay(); processor.processLatex2pdf(this.texFile); verify(); } //@Ignore @Test public void testProcessLatex2html() throws BuildFailureException { mockConstrLatexMainDesc(); // run latex mockRunLatex(); // run bibtex by need: no mockRunBibtexByNeed(false); // run makeIndex by need: no mockRunMakeIndexByNeed(false); // run makeGlossary by need: no mockRunMakeGlossaryByNeed(false); // determine from presence of toc, lof, lot (and idx and other criteria) // whether to rerun latex: no fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_TOC); fileUtilsCtrl.setReturnValue(tocFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_LOF); fileUtilsCtrl.setReturnValue(lofFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_LOT); fileUtilsCtrl.setReturnValue(lotFile); // // determine whether to rerun latex: no // mockNeedAnotherLatexRun( false ); // // detect bad boxes and warnings: none // fileUtils.matchInFile(logFile, LatexProcessor.PATTERN_OUFULL_HVBOX); // fileUtilsCtrl.setReturnValue( false ); // fileUtils.matchInFile(logFile, // this.settings.getPatternWarnLatex()); // fileUtilsCtrl.setReturnValue( false ); mockRunLatex2html(); replay(); processor.processLatex2html(this. texFile); verify(); } private void mockConstrLatexMainDesc() { fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_VOID); fileUtilsCtrl.setReturnValue(xxxFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_LOG); fileUtilsCtrl.setReturnValue(logFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_IDX); fileUtilsCtrl.setReturnValue(idxFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_ILG); fileUtilsCtrl.setReturnValue(ilgFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_GLO); fileUtilsCtrl.setReturnValue(gloFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_GLG); fileUtilsCtrl.setReturnValue(glgFile); } private void mockNeedAnotherLatexRun(Boolean retVal) throws BuildFailureException { fileUtils.matchInFile(logFile, this.settings.getPatternReRunLatex()); fileUtilsCtrl.setReturnValue(retVal); } private void mockNeedAnotherMakeIndexRun(Boolean retVal) throws BuildFailureException { fileUtils.matchInFile(logFile, this.settings.getPatternReRunMakeIndex()); fileUtilsCtrl.setReturnValue(retVal); } // private void mockNeedBibtexRun(boolean retVal) // throws BuildFailureException // { // fileUtils.matchInFile(auxFile, LatexProcessor.PATTERN_NEED_BIBTEX_RUN); // fileUtilsCtrl.setReturnValue( retVal ); // } private void mockRunBibtexByNeed(Boolean runBibtex) throws BuildFailureException { fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_AUX); fileUtilsCtrl.setReturnValue(auxFile); fileUtils.matchInFile(auxFile, LatexProcessor.PATTERN_NEED_BIBTEX_RUN); fileUtilsCtrl.setReturnValue(runBibtex); if (!runBibtex) { return; } executor.execute(texFile.getParentFile(), settings.getTexPath(), settings.getBibtexCommand(), new String[] {auxFile.getPath()}); executorCtrl.setMatcher(MockControl.ARRAY_MATCHER); executorCtrl.setReturnValue(null); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_BLG); fileUtilsCtrl.setReturnValue(blgFile); // fileUtils.matchInFile(blgFile, "Error"); // fileUtilsCtrl.setReturnValue( false ); // fileUtils.matchInFile(blgFile, // this.settings.getPatternReRunLatex()); // fileUtilsCtrl.setReturnValue( false ); } private void mockRunMakeIndexByNeed(boolean runMakeIndex) throws BuildFailureException { if (!runMakeIndex) { return; } executor.execute(texFile.getParentFile(), settings.getTexPath(), settings.getMakeIndexCommand(), new String[] {idxFile.getPath()}); executorCtrl.setMatcher(MockControl.ARRAY_MATCHER); executorCtrl.setReturnValue(null); } private void mockRunMakeGlossaryByNeed(boolean runMakeGlossary) throws BuildFailureException { if (!runMakeGlossary) { return; } executor.execute(texFile.getParentFile(), settings.getTexPath(), settings.getMakeGlossariesCommand(), new String[] {xxxFile.getName()} ); executorCtrl.setMatcher(MockControl.ARRAY_MATCHER); executorCtrl.setReturnValue(null); } private void mockRunLatex() throws BuildFailureException { executor.execute(texFile.getParentFile(), settings.getTexPath(), settings.getLatex2pdfCommand(), LatexProcessor .buildArguments(settings.getLatex2pdfOptions(), texFile)); executorCtrl.setMatcher(MockControl.ARRAY_MATCHER); executorCtrl.setReturnValue(null); } private void mockRunLatex2html() throws BuildFailureException { executor.execute(texFile.getParentFile(), settings.getTexPath(), settings.getTex4htCommand(), tex2htmlArgsExpected); executorCtrl.setMatcher(MockControl.ARRAY_MATCHER); executorCtrl.setReturnValue(null); // logErrs // fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_LOG); // fileUtilsCtrl.setReturnValue(logFile); // since log file does not exist // fileUtils.matchInFile(logFile, this.settings.getPatternErrLatex()); // fileUtilsCtrl.setReturnValue( false ); } private void replay() { executorCtrl.replay(); fileUtilsCtrl.replay(); } private void verify() { executorCtrl.verify(); fileUtilsCtrl.verify(); } }
maven-latex-plugin/src/test/java/org/m2latex/core/LatexProcessorTest.java
/* * The akquinet maven-latex-plugin project * * Copyright (c) 2011 by akquinet tech@spree GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.m2latex.core; import org.m2latex.mojo.MavenLogWrapper; import org.m2latex.mojo.PdfMojo; import java.io.File; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugin.logging.SystemStreamLog; import org.easymock.MockControl; import org.junit.Test; import org.junit.Ignore; public class LatexProcessorTest { private MockControl executorCtrl = MockControl .createStrictControl(CommandExecutor.class); private CommandExecutor executor = (CommandExecutor) executorCtrl.getMock(); private MockControl fileUtilsCtrl = MockControl .createStrictControl(TexFileUtils.class); private TexFileUtils fileUtils = (TexFileUtils) fileUtilsCtrl.getMock(); private Settings settings = new Settings(); private LogWrapper log = new MavenLogWrapper(new SystemStreamLog()); private LatexProcessor processor = new LatexProcessor (settings, executor, log, fileUtils, new PdfMojo()); private File texFile = new File(System.getProperty("tmp.dir"), "test.tex"); private File auxFile = new File(System.getProperty("tmp.dir"), "test.aux"); private File logFile = new File(System.getProperty("tmp.dir"), "test.log"); private File blgFile = new File(System.getProperty("tmp.dir"), "test.blg"); private File idxFile = new File(System.getProperty("tmp.dir"), "test.idx"); private File ilgFile = new File(System.getProperty("tmp.dir"), "test.ilg"); private File gloFile = new File(System.getProperty("tmp.dir"), "test.glo"); private File istFile = new File(System.getProperty("tmp.dir"), "test.ist"); private File xdyFile = new File(System.getProperty("tmp.dir"), "test.xdy"); private File glsFile = new File(System.getProperty("tmp.dir"), "test.gls"); private File glgFile = new File(System.getProperty("tmp.dir"), "test.glg"); // this one does never exist. private File xxxFile = new File(System.getProperty("tmp.dir"), "test"); private File tocFile = new File(System.getProperty("tmp.dir"), "test.toc"); private File lofFile = new File(System.getProperty("tmp.dir"), "test.lof"); private File lotFile = new File(System.getProperty("tmp.dir"), "test.lot"); private String[] tex2htmlArgsExpected = new String[] { this.texFile.getName(), "html,2", "", "", settings.getLatex2pdfOptions() }; //@Ignore @Test public void testProcessLatexSimple() throws BuildFailureException { mockConstrLatexMainDesc(); // run latex mockRunLatex(); // run bibtex by need: no mockRunBibtexByNeed(false); // run makeIndex by need: no mockRunMakeIndexByNeed(false); // run makeGlossary by need: no mockRunMakeGlossaryByNeed(false); // determine from presence of toc, lof, lot (and idx and other criteria) // whether to rerun latex: no fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_TOC); fileUtilsCtrl.setReturnValue(tocFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_LOF); fileUtilsCtrl.setReturnValue(lofFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_LOT); fileUtilsCtrl.setReturnValue(lotFile); // determine whether to rerun latex or makeindex: no mockNeedAnotherLatexRun(false); mockNeedAnotherMakeIndexRun(false); // // detect bad boxes and warnings: none // fileUtils.matchInFile(logFile, LatexProcessor.PATTERN_OUFULL_HVBOX); // fileUtilsCtrl.setReturnValue( false ); // fileUtils.matchInFile(logFile, // this.settings.getPatternWarnLatex()); // fileUtilsCtrl.setReturnValue( false ); replay(); processor.processLatex2pdf(this.texFile); verify(); } //@Ignore @Test public void testProcessLatexWithBibtex() throws BuildFailureException { mockConstrLatexMainDesc(); // run latex mockRunLatex(); // run bibtex by need: yes mockRunBibtexByNeed(true); // run makeIndex by need: no mockRunMakeIndexByNeed(false); // run makeGlossary by need: no mockRunMakeGlossaryByNeed(false); // run latex twice because bibtex had been run mockRunLatex(); //mockRunLatex(); // determine whether to rerun latex and run until no //mockNeedAnotherLatexRun(true); // no, because bibtex triggers two latex runs mockNeedAnotherMakeIndexRun(false); mockRunLatex(); mockNeedAnotherLatexRun(false); mockNeedAnotherMakeIndexRun(false); // // detect bad boxes and warnings: none // fileUtils.matchInFile(logFile, LatexProcessor.PATTERN_OUFULL_HVBOX); // fileUtilsCtrl.setReturnValue( false ); // fileUtils.matchInFile(logFile, // this.settings.getPatternWarnLatex()); // fileUtilsCtrl.setReturnValue( false ); replay(); processor.processLatex2pdf(this.texFile); verify(); } //@Ignore @Test public void testProcessLatex2html() throws BuildFailureException { mockConstrLatexMainDesc(); // run latex mockRunLatex(); // run bibtex by need: no mockRunBibtexByNeed(false); // run makeIndex by need: no mockRunMakeIndexByNeed(false); // run makeGlossary by need: no mockRunMakeGlossaryByNeed(false); // determine from presence of toc, lof, lot (and idx and other criteria) // whether to rerun latex: no fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_TOC); fileUtilsCtrl.setReturnValue(tocFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_LOF); fileUtilsCtrl.setReturnValue(lofFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_LOT); fileUtilsCtrl.setReturnValue(lotFile); // // determine whether to rerun latex: no // mockNeedAnotherLatexRun( false ); // // detect bad boxes and warnings: none // fileUtils.matchInFile(logFile, LatexProcessor.PATTERN_OUFULL_HVBOX); // fileUtilsCtrl.setReturnValue( false ); // fileUtils.matchInFile(logFile, // this.settings.getPatternWarnLatex()); // fileUtilsCtrl.setReturnValue( false ); mockRunLatex2html(); replay(); processor.processLatex2html(this. texFile); verify(); } private void mockConstrLatexMainDesc() { fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_VOID); fileUtilsCtrl.setReturnValue(xxxFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_LOG); fileUtilsCtrl.setReturnValue(logFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_IDX); fileUtilsCtrl.setReturnValue(idxFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_ILG); fileUtilsCtrl.setReturnValue(ilgFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_GLO); fileUtilsCtrl.setReturnValue(gloFile); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_GLG); fileUtilsCtrl.setReturnValue(glgFile); } private void mockNeedAnotherLatexRun(boolean retVal) throws BuildFailureException { fileUtils.matchInFile(logFile, this.settings.getPatternReRunLatex()); fileUtilsCtrl.setReturnValue(retVal); } private void mockNeedAnotherMakeIndexRun(boolean retVal) throws BuildFailureException { fileUtils.matchInFile(logFile, this.settings.getPatternReRunMakeIndex()); fileUtilsCtrl.setReturnValue(retVal); } // private void mockNeedBibtexRun(boolean retVal) // throws BuildFailureException // { // fileUtils.matchInFile(auxFile, LatexProcessor.PATTERN_NEED_BIBTEX_RUN); // fileUtilsCtrl.setReturnValue( retVal ); // } private void mockRunBibtexByNeed(boolean runBibtex) throws BuildFailureException { fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_AUX); fileUtilsCtrl.setReturnValue(auxFile); fileUtils.matchInFile(auxFile, LatexProcessor.PATTERN_NEED_BIBTEX_RUN); fileUtilsCtrl.setReturnValue(runBibtex); if (!runBibtex) { return; } executor.execute(texFile.getParentFile(), settings.getTexPath(), settings.getBibtexCommand(), new String[] {auxFile.getPath()}); executorCtrl.setMatcher(MockControl.ARRAY_MATCHER); executorCtrl.setReturnValue(null); fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_BLG); fileUtilsCtrl.setReturnValue(blgFile); // fileUtils.matchInFile(blgFile, "Error"); // fileUtilsCtrl.setReturnValue( false ); // fileUtils.matchInFile(blgFile, // this.settings.getPatternReRunLatex()); // fileUtilsCtrl.setReturnValue( false ); } private void mockRunMakeIndexByNeed(boolean runMakeIndex) throws BuildFailureException { if (!runMakeIndex) { return; } executor.execute(texFile.getParentFile(), settings.getTexPath(), settings.getMakeIndexCommand(), new String[] {idxFile.getPath()}); executorCtrl.setMatcher(MockControl.ARRAY_MATCHER); executorCtrl.setReturnValue(null); } private void mockRunMakeGlossaryByNeed(boolean runMakeGlossary) throws BuildFailureException { if (!runMakeGlossary) { return; } executor.execute(texFile.getParentFile(), settings.getTexPath(), settings.getMakeGlossariesCommand(), new String[] {xxxFile.getName()} ); executorCtrl.setMatcher(MockControl.ARRAY_MATCHER); executorCtrl.setReturnValue(null); } private void mockRunLatex() throws BuildFailureException { executor.execute(texFile.getParentFile(), settings.getTexPath(), settings.getLatex2pdfCommand(), LatexProcessor .buildArguments(settings.getLatex2pdfOptions(), texFile)); executorCtrl.setMatcher(MockControl.ARRAY_MATCHER); executorCtrl.setReturnValue(null); } private void mockRunLatex2html() throws BuildFailureException { executor.execute(texFile.getParentFile(), settings.getTexPath(), settings.getTex4htCommand(), tex2htmlArgsExpected); executorCtrl.setMatcher(MockControl.ARRAY_MATCHER); executorCtrl.setReturnValue(null); // logErrs // fileUtils.replaceSuffix(texFile, LatexProcessor.SUFFIX_LOG); // fileUtilsCtrl.setReturnValue(logFile); // since log file does not exist // fileUtils.matchInFile(logFile, this.settings.getPatternErrLatex()); // fileUtilsCtrl.setReturnValue( false ); } private void replay() { executorCtrl.replay(); fileUtilsCtrl.replay(); } private void verify() { executorCtrl.verify(); fileUtilsCtrl.verify(); } }
@chg reworked exception and warning messages. Above all reimplemented method matchInFile without exceptions and with return type boolean-->Boolean indicating IOException if null. - adapted testcases.
maven-latex-plugin/src/test/java/org/m2latex/core/LatexProcessorTest.java
@chg reworked exception and warning messages. Above all reimplemented method matchInFile without exceptions and with return type boolean-->Boolean indicating IOException if null. - adapted testcases.
Java
apache-2.0
be1d164a22fae9d921fbc7980cabb58c243caab4
0
steinarb/ukelonn,steinarb/ukelonn,steinarb/ukelonn
package no.priv.bang.ukelonn.impl; import static no.priv.bang.ukelonn.testutils.TestUtils.releaseFakeOsgiServices; import static no.priv.bang.ukelonn.testutils.TestUtils.setupFakeOsgiServices; import static org.junit.Assert.*; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import java.util.Collections; import java.util.Properties; import java.util.concurrent.locks.ReentrantLock; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import org.apache.shiro.SecurityUtils; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.subject.Subject; import org.apache.shiro.subject.SubjectContext; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.vaadin.server.DefaultDeploymentConfiguration; import com.vaadin.server.ServiceException; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinResponse; import com.vaadin.server.VaadinServlet; import com.vaadin.server.VaadinServletService; import com.vaadin.server.VaadinSession; import com.vaadin.server.WrappedSession; import com.vaadin.util.CurrentInstance; public class UkelonnUITest { private static VaadinSession session; private static Subject user; @BeforeClass public static void setupClass() throws ServiceException, ServletException { setupFakeOsgiServices(); VaadinServlet servlet = new VaadinServlet(); ServletConfig config = mock(ServletConfig.class); ServletContext context = mock(ServletContext.class); when(context.getInitParameterNames()).thenReturn(Collections.emptyEnumeration()); when(config.getServletContext()).thenReturn(context); when(config.getInitParameterNames()).thenReturn(Collections.emptyEnumeration()); servlet.init(config); VaadinServletService service = new VaadinServletService(servlet, new DefaultDeploymentConfiguration(UkelonnUI.class, new Properties())); session = new VaadinSession(service); WrappedSession wrappedsession = mock(WrappedSession.class); ReentrantLock lock = new ReentrantLock(); lock.lock(); when(wrappedsession.getAttribute(anyString())).thenReturn(lock); session.refreshTransients(wrappedsession, service); SecurityManager securitymanager = mock(SecurityManager.class); user = mock(Subject.class); when(securitymanager.createSubject(any(SubjectContext.class))).thenReturn(user); SecurityUtils.setSecurityManager(securitymanager); } @AfterClass public static void teardownForAllTests() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { releaseFakeOsgiServices(); } @Test public void testInitWhenNotLoggedIn() { VaadinSession.setCurrent(session); when(user.isRemembered()).thenReturn(false); when(user.isAuthenticated()).thenReturn(false); when(user.hasRole(eq("administrator"))).thenReturn(false); UkelonnUI ui = new UkelonnUI(); String location = "http://localhost:8181/ukelonn/"; VaadinRequest request = createMockVaadinRequest(location); ui.doInit(request, -1, location); assertEquals(LoginView.class, ui.getNavigator().getCurrentView().getClass()); } @Test public void testInitWhenRegularUser() { VaadinSession.setCurrent(session); when(user.isRemembered()).thenReturn(false); when(user.isAuthenticated()).thenReturn(true); when(user.hasRole(eq("administrator"))).thenReturn(false); UkelonnUI ui = new UkelonnUI(); String location = "http://localhost:8181/ukelonn/"; VaadinRequest request = createMockVaadinRequest(location); ui.doInit(request, -1, location); assertEquals(UserView.class, ui.getNavigator().getCurrentView().getClass()); } @Test public void testFallbackUserViewInitWhenRegularUser() { VaadinSession.setCurrent(session); when(user.isRemembered()).thenReturn(false); when(user.isAuthenticated()).thenReturn(true); when(user.hasRole(eq("administrator"))).thenReturn(false); UkelonnUI ui = new UkelonnUI(); String location = "http://localhost:8181/ukelonn/"; VaadinRequest request = createMockVaadinRequest(location); Cookie[] cookies = { new Cookie("cookie", "crumb"), new Cookie("ui-style", "browser")}; when(request.getCookies()).thenReturn(cookies); ui.doInit(request, -1, location); assertEquals(UserFallbackView.class, ui.getNavigator().getCurrentView().getClass()); } @Test public void testSwitchToBrowserFriendlyView() { VaadinSession.setCurrent(session); when(user.isRemembered()).thenReturn(false); when(user.isAuthenticated()).thenReturn(true); when(user.hasRole(eq("administrator"))).thenReturn(false); UkelonnUI ui = new UkelonnUI(); String location = "http://localhost:8181/ukelonn/"; VaadinRequest request = createMockVaadinRequest(location); when(request.getParameter(eq("ui-style"))).thenReturn("browser"); CurrentInstance.set(VaadinResponse.class, mock(VaadinResponse.class)); ui.doInit(request, -1, location); assertEquals(UserFallbackView.class, ui.getNavigator().getCurrentView().getClass()); } @Test public void testSwitchToMobileFriendlyView() { VaadinSession.setCurrent(session); when(user.isRemembered()).thenReturn(false); when(user.isAuthenticated()).thenReturn(true); when(user.hasRole(eq("administrator"))).thenReturn(false); UkelonnUI ui = new UkelonnUI(); String location = "http://localhost:8181/ukelonn/"; VaadinRequest request = createMockVaadinRequest(location); when(request.getParameter(eq("ui-style"))).thenReturn("mobile"); CurrentInstance.set(VaadinResponse.class, mock(VaadinResponse.class)); ui.doInit(request, -1, location); assertEquals(UserView.class, ui.getNavigator().getCurrentView().getClass()); } @Test public void testInitWhenRememberedUser() { VaadinSession.setCurrent(session); when(user.isRemembered()).thenReturn(true); when(user.isAuthenticated()).thenReturn(false); when(user.hasRole(eq("administrator"))).thenReturn(false); UkelonnUI ui = new UkelonnUI(); String location = "http://localhost:8181/ukelonn/"; VaadinRequest request = createMockVaadinRequest(location); ui.doInit(request, -1, location); assertEquals(UserView.class, ui.getNavigator().getCurrentView().getClass()); } @Test public void testInitWhenLoggedInAsAdministrator() { VaadinSession.setCurrent(session); when(user.isRemembered()).thenReturn(true); when(user.isAuthenticated()).thenReturn(false); when(user.hasRole(eq("administrator"))).thenReturn(true); UkelonnUI ui = new UkelonnUI(); String location = "http://localhost:8181/ukelonn/"; VaadinRequest request = createMockVaadinRequest(location); ui.doInit(request, -1, location); assertEquals(AdminView.class, ui.getNavigator().getCurrentView().getClass()); } @Test public void testAdminFallbackViewInitWhenLoggedInAsAdministrator() { VaadinSession.setCurrent(session); when(user.isRemembered()).thenReturn(true); when(user.isAuthenticated()).thenReturn(false); when(user.hasRole(eq("administrator"))).thenReturn(true); UkelonnUI ui = new UkelonnUI(); String location = "http://localhost:8181/ukelonn/"; VaadinRequest request = createMockVaadinRequest(location); Cookie[] cookies = { new Cookie("ui-style", "browser")}; when(request.getCookies()).thenReturn(cookies); ui.doInit(request, -1, location); assertEquals(AdminFallbackView.class, ui.getNavigator().getCurrentView().getClass()); } private VaadinRequest createMockVaadinRequest(String location) { VaadinRequest request = mock(VaadinRequest.class); when(request.getCookies()).thenReturn(new Cookie[0]); when(request.getParameter(eq("v-loc"))).thenReturn(location); return request; } }
ukelonn.bundle/src/test/java/no/priv/bang/ukelonn/impl/UkelonnUITest.java
package no.priv.bang.ukelonn.impl; import static org.junit.Assert.*; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import java.util.Collections; import java.util.Properties; import java.util.concurrent.locks.ReentrantLock; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import org.apache.shiro.SecurityUtils; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.subject.Subject; import org.apache.shiro.subject.SubjectContext; import org.junit.BeforeClass; import org.junit.Test; import com.vaadin.server.DefaultDeploymentConfiguration; import com.vaadin.server.ServiceException; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinResponse; import com.vaadin.server.VaadinServlet; import com.vaadin.server.VaadinServletService; import com.vaadin.server.VaadinSession; import com.vaadin.server.WrappedSession; import com.vaadin.util.CurrentInstance; public class UkelonnUITest { private static VaadinSession session; private static Subject user; @BeforeClass public static void setupClass() throws ServiceException, ServletException { VaadinServlet servlet = new VaadinServlet(); ServletConfig config = mock(ServletConfig.class); ServletContext context = mock(ServletContext.class); when(context.getInitParameterNames()).thenReturn(Collections.emptyEnumeration()); when(config.getServletContext()).thenReturn(context); when(config.getInitParameterNames()).thenReturn(Collections.emptyEnumeration()); servlet.init(config); VaadinServletService service = new VaadinServletService(servlet, new DefaultDeploymentConfiguration(UkelonnUI.class, new Properties())); session = new VaadinSession(service); WrappedSession wrappedsession = mock(WrappedSession.class); ReentrantLock lock = new ReentrantLock(); lock.lock(); when(wrappedsession.getAttribute(anyString())).thenReturn(lock); session.refreshTransients(wrappedsession, service); SecurityManager securitymanager = mock(SecurityManager.class); user = mock(Subject.class); when(securitymanager.createSubject(any(SubjectContext.class))).thenReturn(user); SecurityUtils.setSecurityManager(securitymanager); } @Test public void testInitWhenNotLoggedIn() { VaadinSession.setCurrent(session); when(user.isRemembered()).thenReturn(false); when(user.isAuthenticated()).thenReturn(false); when(user.hasRole(eq("administrator"))).thenReturn(false); UkelonnUI ui = new UkelonnUI(); String location = "http://localhost:8181/ukelonn/"; VaadinRequest request = createMockVaadinRequest(location); ui.doInit(request, -1, location); assertEquals(LoginView.class, ui.getNavigator().getCurrentView().getClass()); } @Test public void testInitWhenRegularUser() { VaadinSession.setCurrent(session); when(user.isRemembered()).thenReturn(false); when(user.isAuthenticated()).thenReturn(true); when(user.hasRole(eq("administrator"))).thenReturn(false); UkelonnUI ui = new UkelonnUI(); String location = "http://localhost:8181/ukelonn/"; VaadinRequest request = createMockVaadinRequest(location); ui.doInit(request, -1, location); assertEquals(UserView.class, ui.getNavigator().getCurrentView().getClass()); } @Test public void testFallbackUserViewInitWhenRegularUser() { VaadinSession.setCurrent(session); when(user.isRemembered()).thenReturn(false); when(user.isAuthenticated()).thenReturn(true); when(user.hasRole(eq("administrator"))).thenReturn(false); UkelonnUI ui = new UkelonnUI(); String location = "http://localhost:8181/ukelonn/"; VaadinRequest request = createMockVaadinRequest(location); Cookie[] cookies = { new Cookie("cookie", "crumb"), new Cookie("ui-style", "browser")}; when(request.getCookies()).thenReturn(cookies); ui.doInit(request, -1, location); assertEquals(UserFallbackView.class, ui.getNavigator().getCurrentView().getClass()); } @Test public void testSwitchToBrowserFriendlyView() { VaadinSession.setCurrent(session); when(user.isRemembered()).thenReturn(false); when(user.isAuthenticated()).thenReturn(true); when(user.hasRole(eq("administrator"))).thenReturn(false); UkelonnUI ui = new UkelonnUI(); String location = "http://localhost:8181/ukelonn/"; VaadinRequest request = createMockVaadinRequest(location); when(request.getParameter(eq("ui-style"))).thenReturn("browser"); CurrentInstance.set(VaadinResponse.class, mock(VaadinResponse.class)); ui.doInit(request, -1, location); assertEquals(UserFallbackView.class, ui.getNavigator().getCurrentView().getClass()); } @Test public void testSwitchToMobileFriendlyView() { VaadinSession.setCurrent(session); when(user.isRemembered()).thenReturn(false); when(user.isAuthenticated()).thenReturn(true); when(user.hasRole(eq("administrator"))).thenReturn(false); UkelonnUI ui = new UkelonnUI(); String location = "http://localhost:8181/ukelonn/"; VaadinRequest request = createMockVaadinRequest(location); when(request.getParameter(eq("ui-style"))).thenReturn("mobile"); CurrentInstance.set(VaadinResponse.class, mock(VaadinResponse.class)); ui.doInit(request, -1, location); assertEquals(UserView.class, ui.getNavigator().getCurrentView().getClass()); } @Test public void testInitWhenRememberedUser() { VaadinSession.setCurrent(session); when(user.isRemembered()).thenReturn(true); when(user.isAuthenticated()).thenReturn(false); when(user.hasRole(eq("administrator"))).thenReturn(false); UkelonnUI ui = new UkelonnUI(); String location = "http://localhost:8181/ukelonn/"; VaadinRequest request = createMockVaadinRequest(location); ui.doInit(request, -1, location); assertEquals(UserView.class, ui.getNavigator().getCurrentView().getClass()); } @Test public void testInitWhenLoggedInAsAdministrator() { VaadinSession.setCurrent(session); when(user.isRemembered()).thenReturn(true); when(user.isAuthenticated()).thenReturn(false); when(user.hasRole(eq("administrator"))).thenReturn(true); UkelonnUI ui = new UkelonnUI(); String location = "http://localhost:8181/ukelonn/"; VaadinRequest request = createMockVaadinRequest(location); ui.doInit(request, -1, location); assertEquals(AdminView.class, ui.getNavigator().getCurrentView().getClass()); } @Test public void testAdminFallbackViewInitWhenLoggedInAsAdministrator() { VaadinSession.setCurrent(session); when(user.isRemembered()).thenReturn(true); when(user.isAuthenticated()).thenReturn(false); when(user.hasRole(eq("administrator"))).thenReturn(true); UkelonnUI ui = new UkelonnUI(); String location = "http://localhost:8181/ukelonn/"; VaadinRequest request = createMockVaadinRequest(location); Cookie[] cookies = { new Cookie("ui-style", "browser")}; when(request.getCookies()).thenReturn(cookies); ui.doInit(request, -1, location); assertEquals(AdminFallbackView.class, ui.getNavigator().getCurrentView().getClass()); } private VaadinRequest createMockVaadinRequest(String location) { VaadinRequest request = mock(VaadinRequest.class); when(request.getCookies()).thenReturn(new Cookie[0]); when(request.getParameter(eq("v-loc"))).thenReturn(location); return request; } }
Fix test UkelonnUI test only failing with maven on debian. The reason for the test failure was "test intereference", or lack of. With maven on windows and in eclipse on both windows and debian, the fake OSGi services were set up by a different test. The fix was to make sure they are set up for the UkelonnUI tests as well.
ukelonn.bundle/src/test/java/no/priv/bang/ukelonn/impl/UkelonnUITest.java
Fix test UkelonnUI test only failing with maven on debian.
Java
apache-2.0
54f3ef87abe12aaa4e91096fe8d6ada601673412
0
APriestman/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,esaunders/autopsy,rcordovano/autopsy,esaunders/autopsy,dgrove727/autopsy,rcordovano/autopsy,rcordovano/autopsy,narfindustries/autopsy,APriestman/autopsy,esaunders/autopsy,millmanorama/autopsy,dgrove727/autopsy,dgrove727/autopsy,millmanorama/autopsy,narfindustries/autopsy,esaunders/autopsy,wschaeferB/autopsy,rcordovano/autopsy,APriestman/autopsy,APriestman/autopsy,millmanorama/autopsy,wschaeferB/autopsy,rcordovano/autopsy,millmanorama/autopsy,APriestman/autopsy,esaunders/autopsy,wschaeferB/autopsy,narfindustries/autopsy,APriestman/autopsy,rcordovano/autopsy,APriestman/autopsy
/* * Autopsy Forensic Browser * * Copyright 2011-2017 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.framework; import java.awt.Dialog; import java.awt.Frame; import java.awt.event.ActionListener; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import javax.swing.JDialog; import javax.swing.SwingUtilities; import org.openide.DialogDescriptor; import org.openide.DialogDisplayer; import org.openide.util.HelpCtx; /** * A progress indicator that displays progress using a modal dialog with a * message label, a progress bar, and optionally, a configurable set of buttons * with a button listener. Setting a cancelling flag which locks in a cancelling * message and an indeterminate progress bar is supported. */ @ThreadSafe public final class ModalDialogProgressIndicator implements ProgressIndicator { private final Frame parent; private final String title; private final ProgressPanel progressPanel; private final Object[] buttonLabels; private final Object focusedButtonLabel; private final ActionListener buttonListener; private Dialog dialog; @GuardedBy("this") private boolean cancelling; /** * Creates a progress indicator that displays progress using a modal dialog * with a message label, a progress bar with a configurable set of buttons * with a button listener. * * @param parent The parent frame. * @param title The title for the dialog. * @param buttonLabels The labels for the desired buttons. * @param focusedButtonLabel The label of the button that should have * initial focus. * @param buttonListener An ActionListener for the buttons. */ public ModalDialogProgressIndicator(Frame parent, String title, Object[] buttonLabels, Object focusedButtonLabel, ActionListener buttonListener) { this.parent = parent; this.title = title; progressPanel = new ProgressPanel(); progressPanel.setIndeterminate(true); this.buttonLabels = buttonLabels; this.focusedButtonLabel = focusedButtonLabel; this.buttonListener = buttonListener; // DialogDescriptor dialogDescriptor = new DialogDescriptor( // progressPanel, // title, // true, // buttonLabels, // focusedButtonLabel, // DialogDescriptor.BOTTOM_ALIGN, // HelpCtx.DEFAULT_HELP, // buttonListener); // dialog = DialogDisplayer.getDefault().createDialog(dialogDescriptor); } /** * Creates a progress indicator that displays progress using a modal dialog * with a message label and a progress bar with no buttons. * * @param parent The parent frame. * @param title The title for the dialog. */ public ModalDialogProgressIndicator(Frame parent, String title) { this.parent = parent; this.title = title; progressPanel = new ProgressPanel(); progressPanel.setIndeterminate(true); this.buttonLabels = null; this.focusedButtonLabel = null; this.buttonListener = null; // dialog = new JDialog(parent, title, true); // dialog.add(progressPanel); // dialog.pack(); } /** * Starts the progress indicator in determinate mode (the total number of * work units to be completed is known). * * @param message The initial progress message. * @param totalWorkUnits The total number of work units. */ @Override public synchronized void start(String message, int totalWorkUnits) { cancelling = false; SwingUtilities.invokeLater(() -> { progressPanel.setIndeterminate(false); progressPanel.setMessage(message); progressPanel.setMaximum(totalWorkUnits); displayDialog(); // dialog.setLocationRelativeTo(parent); // this.dialog.setVisible(true); }); } /** * Starts the progress indicator in indeterminate mode (the total number of * work units to be completed is unknown). * * @param message The initial progress message. */ @Override public synchronized void start(String message) { cancelling = false; SwingUtilities.invokeLater(() -> { progressPanel.setIndeterminate(true); progressPanel.setMessage(message); displayDialog(); // dialog.setLocationRelativeTo(parent); // this.dialog.setVisible(true); }); } /** * Sets a cancelling message and makes the progress bar indeterminate. Once * cancel has been called, the progress indicator no longer accepts updates * unless start is called again. * * @param cancellingMessage */ public synchronized void setCancelling(String cancellingMessage) { cancelling = true; SwingUtilities.invokeLater(() -> { progressPanel.setIndeterminate(false); progressPanel.setMessage(cancellingMessage); }); } /** * Switches the progress indicator to indeterminate mode (the total number * of work units to be completed is unknown). * * @param message The initial progress message. */ @Override public synchronized void switchToIndeterminate(String message) { if (!cancelling) { SwingUtilities.invokeLater(() -> { progressPanel.setIndeterminate(true); progressPanel.setMessage(message); }); } } /** * Switches the progress indicator to determinate mode (the total number of * work units to be completed is known). * * @param message The initial progress message. * @param workUnitsCompleted The number of work units completed so far. * @param totalWorkUnits The total number of work units to be completed. */ @Override public synchronized void switchToDeterminate(String message, int workUnitsCompleted, int totalWorkUnits) { if (!cancelling) { SwingUtilities.invokeLater(() -> { progressPanel.setIndeterminate(false); progressPanel.setMessage(message); progressPanel.setMaximum(totalWorkUnits); progressPanel.setCurrent(workUnitsCompleted); }); } } /** * Updates the progress indicator with a progress message. * * @param message The progress message. */ @Override public synchronized void progress(String message) { if (!cancelling) { SwingUtilities.invokeLater(() -> { progressPanel.setMessage(message); }); } } /** * Updates the progress indicator with the number of work units completed so * far when in determinate mode (the total number of work units to be * completed is known). * * @param workUnitsCompleted Number of work units completed so far. */ @Override public synchronized void progress(int workUnitsCompleted) { if (!cancelling) { SwingUtilities.invokeLater(() -> { progressPanel.setCurrent(workUnitsCompleted); }); } } /** * Updates the progress indicator with a progress message and the number of * work units completed so far when in determinate mode (the total number of * work units to be completed is known). * * @param message The progress message. * @param workUnitsCompleted Number of work units completed so far. */ @Override public synchronized void progress(String message, int workUnitsCompleted) { if (!cancelling) { SwingUtilities.invokeLater(() -> { progressPanel.setMessage(message); progressPanel.setCurrent(workUnitsCompleted); }); } } /** * Finishes the progress indicator when the task is completed. */ @Override public synchronized void finish() { SwingUtilities.invokeLater(() -> { this.dialog.setVisible(false); }); } /** * Creates and dislpays the dialog for the progress indicator. */ private void displayDialog() { DialogDescriptor dialogDescriptor = new DialogDescriptor( progressPanel, title, true, buttonLabels, focusedButtonLabel, DialogDescriptor.BOTTOM_ALIGN, HelpCtx.DEFAULT_HELP, buttonListener); dialog = DialogDisplayer.getDefault().createDialog(dialogDescriptor); dialog.setLocationRelativeTo(parent); this.dialog.setVisible(true); } }
Core/src/org/sleuthkit/autopsy/framework/ModalDialogProgressIndicator.java
/* * Autopsy Forensic Browser * * Copyright 2011-2017 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.framework; import java.awt.Dialog; import java.awt.Frame; import java.awt.event.ActionListener; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import javax.swing.JDialog; import javax.swing.SwingUtilities; import org.openide.DialogDescriptor; import org.openide.DialogDisplayer; import org.openide.util.HelpCtx; /** * A progress indicator that displays progress using a modal dialog with a * message label, a progress bar, and optionally, a configurable set of buttons * with a button listener. Setting a cancelling flag which locks in a cancelling * message and an indeterminate progress bar is supported. */ @ThreadSafe public final class ModalDialogProgressIndicator implements ProgressIndicator { private final Frame parent; private final ProgressPanel progressPanel; private final Dialog dialog; @GuardedBy("this") private boolean cancelling; /** * Creates a progress indicator that displays progress using a modal dialog * with a message label, a progress bar with a configurable set of buttons * with a button listener. * * @param parent The parent frame. * @param title The title for the dialog. * @param buttonLabels The labels for the desired buttons. * @param focusedButtonLabel The label of the button that should have * initial focus. * @param buttonListener An ActionListener for the buttons. */ public ModalDialogProgressIndicator(Frame parent, String title, Object[] buttonLabels, Object focusedButtonLabel, ActionListener buttonListener) { this.parent = parent; progressPanel = new ProgressPanel(); progressPanel.setIndeterminate(true); DialogDescriptor dialogDescriptor = new DialogDescriptor( progressPanel, title, true, buttonLabels, focusedButtonLabel, DialogDescriptor.BOTTOM_ALIGN, HelpCtx.DEFAULT_HELP, buttonListener); dialog = DialogDisplayer.getDefault().createDialog(dialogDescriptor); } /** * Creates a progress indicator that displays progress using a modal dialog * with a message label and a progress bar with no buttons. * * @param parent The parent frame. * @param title The title for the dialog. */ public ModalDialogProgressIndicator(Frame parent, String title) { this.parent = parent; progressPanel = new ProgressPanel(); progressPanel.setIndeterminate(true); dialog = new JDialog(parent, title, true); dialog.add(progressPanel); dialog.pack(); } /** * Starts the progress indicator in determinate mode (the total number of * work units to be completed is known). * * @param message The initial progress message. * @param totalWorkUnits The total number of work units. */ @Override public synchronized void start(String message, int totalWorkUnits) { cancelling = false; SwingUtilities.invokeLater(() -> { progressPanel.setIndeterminate(false); progressPanel.setMessage(message); progressPanel.setMaximum(totalWorkUnits); dialog.setLocationRelativeTo(parent); this.dialog.setVisible(true); }); } /** * Starts the progress indicator in indeterminate mode (the total number of * work units to be completed is unknown). * * @param message The initial progress message. */ @Override public synchronized void start(String message) { cancelling = false; SwingUtilities.invokeLater(() -> { progressPanel.setIndeterminate(true); progressPanel.setMessage(message); dialog.setLocationRelativeTo(parent); this.dialog.setVisible(true); }); } /** * Sets a cancelling message and makes the progress bar indeterminate. Once * cancel has been called, the progress indicator no longer accepts updates * unless start is called again. * * @param cancellingMessage */ public synchronized void setCancelling(String cancellingMessage) { cancelling = true; SwingUtilities.invokeLater(() -> { progressPanel.setIndeterminate(false); progressPanel.setMessage(cancellingMessage); }); } /** * Switches the progress indicator to indeterminate mode (the total number * of work units to be completed is unknown). * * @param message The initial progress message. */ @Override public synchronized void switchToIndeterminate(String message) { if (!cancelling) { SwingUtilities.invokeLater(() -> { progressPanel.setIndeterminate(true); progressPanel.setMessage(message); }); } } /** * Switches the progress indicator to determinate mode (the total number of * work units to be completed is known). * * @param message The initial progress message. * @param workUnitsCompleted The number of work units completed so far. * @param totalWorkUnits The total number of work units to be completed. */ @Override public synchronized void switchToDeterminate(String message, int workUnitsCompleted, int totalWorkUnits) { if (!cancelling) { SwingUtilities.invokeLater(() -> { progressPanel.setIndeterminate(false); progressPanel.setMessage(message); progressPanel.setMaximum(totalWorkUnits); progressPanel.setCurrent(workUnitsCompleted); }); } } /** * Updates the progress indicator with a progress message. * * @param message The progress message. */ @Override public synchronized void progress(String message) { if (!cancelling) { SwingUtilities.invokeLater(() -> { progressPanel.setMessage(message); }); } } /** * Updates the progress indicator with the number of work units completed so * far when in determinate mode (the total number of work units to be * completed is known). * * @param workUnitsCompleted Number of work units completed so far. */ @Override public synchronized void progress(int workUnitsCompleted) { if (!cancelling) { SwingUtilities.invokeLater(() -> { progressPanel.setCurrent(workUnitsCompleted); }); } } /** * Updates the progress indicator with a progress message and the number of * work units completed so far when in determinate mode (the total number of * work units to be completed is known). * * @param message The progress message. * @param workUnitsCompleted Number of work units completed so far. */ @Override public synchronized void progress(String message, int workUnitsCompleted) { if (!cancelling) { SwingUtilities.invokeLater(() -> { progressPanel.setMessage(message); progressPanel.setCurrent(workUnitsCompleted); }); } } /** * Finishes the progress indicator when the task is completed. */ @Override public synchronized void finish() { SwingUtilities.invokeLater(() -> { this.dialog.setVisible(false); }); } }
Improve ModalDialogProgressIndicator, both create and display on EDT
Core/src/org/sleuthkit/autopsy/framework/ModalDialogProgressIndicator.java
Improve ModalDialogProgressIndicator, both create and display on EDT
Java
apache-2.0
698a07d92b8f354b4ff4a6399808924a2d31d40b
0
adam-roughton/Concentus,adam-roughton/Concentus
package com.adamroughton.concentus.actioncollector; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import java.util.Iterator; import java.util.Objects; import uk.co.real_logic.intrinsics.ComponentFactory; import com.adamroughton.concentus.Constants; import com.adamroughton.concentus.InitialiseDelegate; import com.adamroughton.concentus.data.ArrayBackedResizingBuffer; import com.adamroughton.concentus.data.ChunkWriter; import com.adamroughton.concentus.data.DataType; import com.adamroughton.concentus.data.NullResizingBuffer; import com.adamroughton.concentus.data.ResizingBuffer; import com.adamroughton.concentus.data.events.bufferbacked.ActionEvent; import com.adamroughton.concentus.data.events.bufferbacked.ActionReceiptEvent; import com.adamroughton.concentus.data.events.bufferbacked.ActionReceiptMetaData; import com.adamroughton.concentus.data.events.bufferbacked.ClientHandlerInputEvent; import com.adamroughton.concentus.data.events.bufferbacked.ClientHandlerUpdateEvent; import com.adamroughton.concentus.data.events.bufferbacked.ReplayRequestEvent; import com.adamroughton.concentus.data.events.bufferbacked.TickEvent; import com.adamroughton.concentus.data.model.bufferbacked.BufferBackedEffect; import com.adamroughton.concentus.data.model.kryo.CandidateValue; import com.adamroughton.concentus.disruptor.DeadlineBasedEventHandler; import com.adamroughton.concentus.messaging.EventHeader; import com.adamroughton.concentus.messaging.IncomingEventHeader; import com.adamroughton.concentus.messaging.OutgoingEventHeader; import com.adamroughton.concentus.messaging.SocketIdentity; import com.adamroughton.concentus.messaging.patterns.EventPattern; import com.adamroughton.concentus.messaging.patterns.EventReader; import com.adamroughton.concentus.messaging.patterns.EventWriter; import com.adamroughton.concentus.messaging.patterns.RouterPattern; import com.adamroughton.concentus.messaging.patterns.SendQueue; import com.adamroughton.concentus.metric.CountMetric; import com.adamroughton.concentus.metric.MetricContext; import com.adamroughton.concentus.metric.MetricGroup; import com.adamroughton.concentus.metric.StatsMetric; import com.adamroughton.concentus.model.CollectiveApplication; import com.adamroughton.concentus.util.StructuredSlidingWindowMap; import com.esotericsoftware.minlog.Log; public final class ActionCollectorProcessor<TBuffer extends ResizingBuffer> implements DeadlineBasedEventHandler<TBuffer> { private final int _actionCollectorId; private final ActionProcessingLogic _actionProcessingLogic; private final TickDelegate _tickDelegate; private final SendQueue<OutgoingEventHeader, TBuffer> _sendQueue; private final IncomingEventHeader _recvHeader; private final TickEvent _tickEvent = new TickEvent(); private final ClientHandlerInputEvent _clientHandlerInputEvent = new ClientHandlerInputEvent(); private final Int2ObjectMap<StructuredSlidingWindowMap<ResizingBuffer>> _clientHandlerReliableEventStoreLookup = new Int2ObjectOpenHashMap<>(); private final MetricGroup _metrics; private final CountMetric _clientHandlerRecvThroughputMetric; private final CountMetric _replayRequestThroughputMetric; private final CountMetric _replayOutOfRangeThroughputMetric; private final StatsMetric _replayChunkCountStatsMetric; private long _nextDeadline = 0; public ActionCollectorProcessor( int actionCollectorId, IncomingEventHeader recvHeader, CollectiveApplication application, TickDelegate tickDelegate, SendQueue<OutgoingEventHeader, TBuffer> sendQueue, long startTime, long tickDuration, MetricContext metricContext) { _actionCollectorId = actionCollectorId; _recvHeader = Objects.requireNonNull(recvHeader); _actionProcessingLogic = new ActionProcessingLogic(application, tickDuration, startTime); _tickDelegate = Objects.requireNonNull(tickDelegate); _sendQueue = Objects.requireNonNull(sendQueue); _metrics = new MetricGroup(); String reference = "actionCollector"; _clientHandlerRecvThroughputMetric = _metrics.add(metricContext.newThroughputMetric(reference, "clientHandlerRecvThroughput", false)); _replayRequestThroughputMetric = _metrics.add(metricContext.newThroughputMetric(reference, "replayRequestThroughout", false)); _replayOutOfRangeThroughputMetric = _metrics.add(metricContext.newThroughputMetric(reference, "replayOutOfRangeThroughput", false)); _replayChunkCountStatsMetric = _metrics.add(metricContext.newStatsMetric(reference, "replayChunkCountStats", false)); } @Override public void onEvent(TBuffer event, long sequence, boolean endOfBatch) throws Exception { if (!EventHeader.isValid(event, 0)) { return; } if (_recvHeader.isMessagingEvent(event)) { _sendQueue.send(event, _recvHeader); return; } int eventTypeId = EventPattern.getEventType(event, _recvHeader); if (eventTypeId == DataType.CLIENT_HANDLER_INPUT_EVENT.getId()) { _clientHandlerRecvThroughputMetric.push(1); final SocketIdentity sender = RouterPattern.getSocketId(event, _recvHeader); EventPattern.readContent(event, _recvHeader, _clientHandlerInputEvent, new EventReader<IncomingEventHeader, ClientHandlerInputEvent>() { @Override public void read(IncomingEventHeader header, ClientHandlerInputEvent event) { processClientHandlerInputEvent(sender, event); } }); } else if (eventTypeId == DataType.TICK_EVENT.getId()) { EventPattern.readContent(event, _recvHeader, _tickEvent, new EventReader<IncomingEventHeader, TickEvent>() { @Override public void read(IncomingEventHeader header, TickEvent event) { onTick(event); } }); } else { Log.warn(String.format("Unknown event type %d received. Contents = %s", eventTypeId, event.toString())); } } @Override public void onDeadline() { _metrics.publishPending(); } @Override public long moveToNextDeadline(long pendingEventCount) { _nextDeadline = _metrics.nextBucketReadyTime(); return _nextDeadline; } @Override public long getDeadline() { return _nextDeadline; } @Override public String name() { return "ActionCollectorProcessor"; } private void processClientHandlerInputEvent(SocketIdentity sender, final ClientHandlerInputEvent clientHandlerInputEvent) { final int clientHandlerId = clientHandlerInputEvent.getClientHandlerId(); final StructuredSlidingWindowMap<ResizingBuffer> reliableEventMap; if (_clientHandlerReliableEventStoreLookup.containsKey(clientHandlerId)) { reliableEventMap = _clientHandlerReliableEventStoreLookup.get(clientHandlerId); } else { reliableEventMap = newClientHandlerReliableEventMap(); _clientHandlerReliableEventStoreLookup.put(clientHandlerId, reliableEventMap); } final int handlerEventTypeId = clientHandlerInputEvent.getContentSlice().readInt(0); final long nextReliableSeq = reliableEventMap.advance(); _sendQueue.send(RouterPattern.asReliableTask(sender, new ClientHandlerUpdateEvent(), new EventWriter<OutgoingEventHeader, ClientHandlerUpdateEvent>() { @Override public void write(OutgoingEventHeader header, ClientHandlerUpdateEvent update) throws Exception { update.setClientHandlerId(clientHandlerId); update.setReliableSeq(nextReliableSeq); update.setActionCollectorId(_actionCollectorId); ChunkWriter updateChunkWriter = update.newChunkedContentWriter(); ResizingBuffer reliableDataBuffer = reliableEventMap.get(nextReliableSeq); if (handlerEventTypeId == DataType.ACTION_EVENT.getId()) { ActionEvent actionEvent = new ActionEvent(); actionEvent.attachToBuffer(clientHandlerInputEvent.getContentSlice()); ActionReceiptMetaData actionReceiptMetaData = new ActionReceiptMetaData(); actionReceiptMetaData.attachToBuffer(reliableDataBuffer); try { actionReceiptMetaData.writeTypeId(); processAction(actionEvent, actionReceiptMetaData, updateChunkWriter); } finally { actionEvent.releaseBuffer(); actionReceiptMetaData.releaseBuffer(); } } else if (handlerEventTypeId == DataType.REPLAY_REQUEST_EVENT.getId()) { _replayRequestThroughputMetric.push(1); ReplayRequestEvent replayRequestEvent = new ReplayRequestEvent(); replayRequestEvent.attachToBuffer(clientHandlerInputEvent.getContentSlice()); try { processReplayRequest(clientHandlerId, replayRequestEvent, reliableEventMap, reliableDataBuffer, updateChunkWriter); } finally { replayRequestEvent.releaseBuffer(); } } else { Log.warn("ActionCollectorProcessor.processClientHandlerInputEvent: Unknown event type ID " + handlerEventTypeId); } } })); } private void processAction(ActionEvent actionEvent, ActionReceiptMetaData receiptMetaData, ChunkWriter updateChunkWriter) { final long effectsStartTime = _actionProcessingLogic.nextTickTime(); final long clientId = actionEvent.getClientIdBits(); final long actionId = actionEvent.getActionId(); int actionTypeId = actionEvent.getActionTypeId(); ResizingBuffer actionData = actionEvent.getActionDataSlice(); final Iterator<ResizingBuffer> effectsIterator = _actionProcessingLogic.newAction(clientId, actionTypeId, actionData); ResizingBuffer chunkBuffer = updateChunkWriter.getChunkBuffer(); ActionReceiptEvent actionReceiptEvent = new ActionReceiptEvent(); actionReceiptEvent.attachToBuffer(chunkBuffer); try { // write the action receipt into the buffer actionReceiptEvent.writeTypeId(); actionReceiptEvent.setClientIdBits(clientId); actionReceiptEvent.setActionId(actionId); actionReceiptEvent.setStartTime(effectsStartTime); receiptMetaData.setClientIdBits(clientId); int varIdCount = 0; ResizingBuffer varIdsBuffer = receiptMetaData.getVarIdsSlice(); int varIdsCursor = 0; ChunkWriter effectsWriter = actionReceiptEvent.getEffectsWriter(); while(effectsIterator.hasNext()) { ResizingBuffer nextEffectBuffer = effectsIterator.next(); nextEffectBuffer.copyTo(effectsWriter.getChunkBuffer()); effectsWriter.commitChunk(); BufferBackedEffect effect = new BufferBackedEffect(); effect.attachToBuffer(nextEffectBuffer); try { varIdsBuffer.writeInt(varIdsCursor, effect.getVariableId()); varIdsCursor += ResizingBuffer.INT_SIZE; varIdCount++; } finally { effect.releaseBuffer(); } } effectsWriter.finish(); receiptMetaData.setVarIdCount(varIdCount); } finally { actionReceiptEvent.releaseBuffer(); updateChunkWriter.commitChunk(); } } private void processReplayRequest( int clientHandlerId, ReplayRequestEvent replayRequest, StructuredSlidingWindowMap<ResizingBuffer> reliableEventWindow, ResizingBuffer thisRequestReliableBuffer, ChunkWriter updateChunkWriter) { // store a copy of the request into the reliable buffer replayRequest.getBuffer().copyTo(thisRequestReliableBuffer); long headSeq = reliableEventWindow.getHeadIndex(); long tailSeq = headSeq - reliableEventWindow.getLength() + 1; long requestedStartSeq = replayRequest.getStartSequence(); long requestedEndSeq = requestedStartSeq + replayRequest.getCount() - 1; // endSeq is inclusive long startSeq = Math.max(tailSeq, requestedStartSeq); // this can work out to be less than the startSeq if requestedEndSeq < tailSeq: this is safe, and // will result in the replay loop terminating immediately long endSeq = Math.min(headSeq, requestedEndSeq); if (startSeq > requestedStartSeq) { _replayOutOfRangeThroughputMetric.push(1); // Log.warn(String.format("Client Handler %d: requested %d, but %d " + // "was the lowest seq available", clientHandlerId, requestedStartSeq, startSeq)); } _replayChunkCountStatsMetric.push(endSeq - startSeq + 1); for (long seq = startSeq; seq <= endSeq; seq++) { ResizingBuffer receiptChunkBuffer = updateChunkWriter.getChunkBuffer(); final ResizingBuffer reliableEventBuffer = reliableEventWindow.get(seq); int storedEventTypeId = reliableEventBuffer.readInt(0); if (storedEventTypeId == DataType.ACTION_RECEIPT_META_DATA.getId()) { ActionReceiptEvent actionReceiptEvent = new ActionReceiptEvent(); actionReceiptEvent.attachToBuffer(receiptChunkBuffer); ActionReceiptMetaData actionReceiptMetaData = new ActionReceiptMetaData(); actionReceiptMetaData.attachToBuffer(reliableEventBuffer); try { long clientIdBits = actionReceiptMetaData.getClientIdBits(); actionReceiptEvent.writeTypeId(); actionReceiptEvent.setActionId(actionReceiptMetaData.getActionId()); actionReceiptEvent.setClientIdBits(clientIdBits); actionReceiptEvent.setStartTime(actionReceiptMetaData.getStartTime()); ResizingBuffer varIdsBuffer = actionReceiptMetaData.getVarIdsSlice(); int varsIdCount = actionReceiptMetaData.getVarIdCount(); ChunkWriter effectChunkWriter = actionReceiptEvent.getEffectsWriter(); for (int i = 0; i < varsIdCount; i++) { int varId = varIdsBuffer.readInt(i * ResizingBuffer.INT_SIZE); ResizingBuffer effectData = _actionProcessingLogic.getEffectData(clientIdBits, varId); if (effectData.getContentSize() > 0) { effectData.copyTo(effectChunkWriter.getChunkBuffer()); effectChunkWriter.commitChunk(); } } } finally { actionReceiptMetaData.releaseBuffer(); actionReceiptEvent.releaseBuffer(); } } else if (storedEventTypeId == DataType.REPLAY_REQUEST_EVENT.getId()) { ReplayRequestEvent lostReplayRequestEvent = new ReplayRequestEvent(); lostReplayRequestEvent.attachToBuffer(receiptChunkBuffer); try { processReplayRequest(clientHandlerId, lostReplayRequestEvent, reliableEventWindow, new NullResizingBuffer(), updateChunkWriter); } finally { lostReplayRequestEvent.releaseBuffer(); } } } } private void onTick(TickEvent tickEvent) { long time = tickEvent.getTime(); Iterator<CandidateValue> candidateValuesForTick = _actionProcessingLogic.tick(time); _tickDelegate.onTick(time, candidateValuesForTick); } private static StructuredSlidingWindowMap<ResizingBuffer> newClientHandlerReliableEventMap() { return new StructuredSlidingWindowMap<ResizingBuffer>( 4096, ResizingBuffer.class, new ComponentFactory<ResizingBuffer>() { @Override public ResizingBuffer newInstance(Object[] initArgs) { return new ArrayBackedResizingBuffer(Constants.MSG_BUFFER_ENTRY_LENGTH); } }, new InitialiseDelegate<ResizingBuffer>() { @Override public void initialise(ResizingBuffer content) { content.reset(); } }); } }
Service/src/main/java/com/adamroughton/concentus/actioncollector/ActionCollectorProcessor.java
package com.adamroughton.concentus.actioncollector; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import java.util.Iterator; import java.util.Objects; import uk.co.real_logic.intrinsics.ComponentFactory; import com.adamroughton.concentus.Constants; import com.adamroughton.concentus.InitialiseDelegate; import com.adamroughton.concentus.data.ArrayBackedResizingBuffer; import com.adamroughton.concentus.data.ChunkWriter; import com.adamroughton.concentus.data.DataType; import com.adamroughton.concentus.data.NullResizingBuffer; import com.adamroughton.concentus.data.ResizingBuffer; import com.adamroughton.concentus.data.events.bufferbacked.ActionEvent; import com.adamroughton.concentus.data.events.bufferbacked.ActionReceiptEvent; import com.adamroughton.concentus.data.events.bufferbacked.ActionReceiptMetaData; import com.adamroughton.concentus.data.events.bufferbacked.ClientHandlerInputEvent; import com.adamroughton.concentus.data.events.bufferbacked.ClientHandlerUpdateEvent; import com.adamroughton.concentus.data.events.bufferbacked.ReplayRequestEvent; import com.adamroughton.concentus.data.events.bufferbacked.TickEvent; import com.adamroughton.concentus.data.model.bufferbacked.BufferBackedEffect; import com.adamroughton.concentus.data.model.kryo.CandidateValue; import com.adamroughton.concentus.disruptor.DeadlineBasedEventHandler; import com.adamroughton.concentus.messaging.EventHeader; import com.adamroughton.concentus.messaging.IncomingEventHeader; import com.adamroughton.concentus.messaging.OutgoingEventHeader; import com.adamroughton.concentus.messaging.SocketIdentity; import com.adamroughton.concentus.messaging.patterns.EventPattern; import com.adamroughton.concentus.messaging.patterns.EventReader; import com.adamroughton.concentus.messaging.patterns.EventWriter; import com.adamroughton.concentus.messaging.patterns.RouterPattern; import com.adamroughton.concentus.messaging.patterns.SendQueue; import com.adamroughton.concentus.metric.CountMetric; import com.adamroughton.concentus.metric.MetricContext; import com.adamroughton.concentus.metric.MetricGroup; import com.adamroughton.concentus.model.CollectiveApplication; import com.adamroughton.concentus.util.StructuredSlidingWindowMap; import com.esotericsoftware.minlog.Log; public final class ActionCollectorProcessor<TBuffer extends ResizingBuffer> implements DeadlineBasedEventHandler<TBuffer> { private final int _actionCollectorId; private final ActionProcessingLogic _actionProcessingLogic; private final TickDelegate _tickDelegate; private final SendQueue<OutgoingEventHeader, TBuffer> _sendQueue; private final IncomingEventHeader _recvHeader; private final TickEvent _tickEvent = new TickEvent(); private final ClientHandlerInputEvent _clientHandlerInputEvent = new ClientHandlerInputEvent(); private final Int2ObjectMap<StructuredSlidingWindowMap<ResizingBuffer>> _clientHandlerReliableEventStoreLookup = new Int2ObjectOpenHashMap<>(); private final MetricGroup _metrics; private final CountMetric _clientHandlerRecvThroughputMetric; private final CountMetric _replayRequestThroughputMetric; private final CountMetric _replayOutOfRangeThroughputMetric; private long _nextDeadline = 0; public ActionCollectorProcessor( int actionCollectorId, IncomingEventHeader recvHeader, CollectiveApplication application, TickDelegate tickDelegate, SendQueue<OutgoingEventHeader, TBuffer> sendQueue, long startTime, long tickDuration, MetricContext metricContext) { _actionCollectorId = actionCollectorId; _recvHeader = Objects.requireNonNull(recvHeader); _actionProcessingLogic = new ActionProcessingLogic(application, tickDuration, startTime); _tickDelegate = Objects.requireNonNull(tickDelegate); _sendQueue = Objects.requireNonNull(sendQueue); _metrics = new MetricGroup(); String reference = "actionCollector"; _clientHandlerRecvThroughputMetric = _metrics.add(metricContext.newThroughputMetric(reference, "clientHandlerRecvThroughput", false)); _replayRequestThroughputMetric = _metrics.add(metricContext.newThroughputMetric(reference, "replayRequestThroughout", false)); _replayOutOfRangeThroughputMetric = _metrics.add(metricContext.newThroughputMetric(reference, "replayOutOfRangeThroughput", false)); } @Override public void onEvent(TBuffer event, long sequence, boolean endOfBatch) throws Exception { if (!EventHeader.isValid(event, 0)) { return; } if (_recvHeader.isMessagingEvent(event)) { _sendQueue.send(event, _recvHeader); return; } int eventTypeId = EventPattern.getEventType(event, _recvHeader); if (eventTypeId == DataType.CLIENT_HANDLER_INPUT_EVENT.getId()) { final SocketIdentity sender = RouterPattern.getSocketId(event, _recvHeader); EventPattern.readContent(event, _recvHeader, _clientHandlerInputEvent, new EventReader<IncomingEventHeader, ClientHandlerInputEvent>() { @Override public void read(IncomingEventHeader header, ClientHandlerInputEvent event) { processClientHandlerInputEvent(sender, event); } }); _clientHandlerRecvThroughputMetric.push(1); } else if (eventTypeId == DataType.TICK_EVENT.getId()) { EventPattern.readContent(event, _recvHeader, _tickEvent, new EventReader<IncomingEventHeader, TickEvent>() { @Override public void read(IncomingEventHeader header, TickEvent event) { onTick(event); } }); } else { Log.warn(String.format("Unknown event type %d received. Contents = %s", eventTypeId, event.toString())); } } @Override public void onDeadline() { _metrics.publishPending(); } @Override public long moveToNextDeadline(long pendingEventCount) { _nextDeadline = _metrics.nextBucketReadyTime(); return _nextDeadline; } @Override public long getDeadline() { return _nextDeadline; } @Override public String name() { return "ActionCollectorProcessor"; } private void processClientHandlerInputEvent(SocketIdentity sender, final ClientHandlerInputEvent clientHandlerInputEvent) { final int clientHandlerId = clientHandlerInputEvent.getClientHandlerId(); final StructuredSlidingWindowMap<ResizingBuffer> reliableEventMap; if (_clientHandlerReliableEventStoreLookup.containsKey(clientHandlerId)) { reliableEventMap = _clientHandlerReliableEventStoreLookup.get(clientHandlerId); } else { reliableEventMap = newClientHandlerReliableEventMap(); _clientHandlerReliableEventStoreLookup.put(clientHandlerId, reliableEventMap); } final int handlerEventTypeId = clientHandlerInputEvent.getContentSlice().readInt(0); final long nextReliableSeq = reliableEventMap.advance(); _sendQueue.send(RouterPattern.asReliableTask(sender, new ClientHandlerUpdateEvent(), new EventWriter<OutgoingEventHeader, ClientHandlerUpdateEvent>() { @Override public void write(OutgoingEventHeader header, ClientHandlerUpdateEvent update) throws Exception { update.setClientHandlerId(clientHandlerId); update.setReliableSeq(nextReliableSeq); update.setActionCollectorId(_actionCollectorId); ChunkWriter updateChunkWriter = update.newChunkedContentWriter(); ResizingBuffer reliableDataBuffer = reliableEventMap.get(nextReliableSeq); if (handlerEventTypeId == DataType.ACTION_EVENT.getId()) { ActionEvent actionEvent = new ActionEvent(); actionEvent.attachToBuffer(clientHandlerInputEvent.getContentSlice()); ActionReceiptMetaData actionReceiptMetaData = new ActionReceiptMetaData(); actionReceiptMetaData.attachToBuffer(reliableDataBuffer); try { actionReceiptMetaData.writeTypeId(); processAction(actionEvent, actionReceiptMetaData, updateChunkWriter); } finally { actionEvent.releaseBuffer(); actionReceiptMetaData.releaseBuffer(); } } else if (handlerEventTypeId == DataType.REPLAY_REQUEST_EVENT.getId()) { ReplayRequestEvent replayRequestEvent = new ReplayRequestEvent(); replayRequestEvent.attachToBuffer(clientHandlerInputEvent.getContentSlice()); try { processReplayRequest(clientHandlerId, replayRequestEvent, reliableEventMap, reliableDataBuffer, updateChunkWriter); } finally { replayRequestEvent.releaseBuffer(); } } else { Log.warn("ActionCollectorProcessor.processClientHandlerInputEvent: Unknown event type ID " + handlerEventTypeId); } } })); } private void processAction(ActionEvent actionEvent, ActionReceiptMetaData receiptMetaData, ChunkWriter updateChunkWriter) { _replayRequestThroughputMetric.push(1); final long effectsStartTime = _actionProcessingLogic.nextTickTime(); final long clientId = actionEvent.getClientIdBits(); final long actionId = actionEvent.getActionId(); int actionTypeId = actionEvent.getActionTypeId(); ResizingBuffer actionData = actionEvent.getActionDataSlice(); final Iterator<ResizingBuffer> effectsIterator = _actionProcessingLogic.newAction(clientId, actionTypeId, actionData); ResizingBuffer chunkBuffer = updateChunkWriter.getChunkBuffer(); ActionReceiptEvent actionReceiptEvent = new ActionReceiptEvent(); actionReceiptEvent.attachToBuffer(chunkBuffer); try { // write the action receipt into the buffer actionReceiptEvent.writeTypeId(); actionReceiptEvent.setClientIdBits(clientId); actionReceiptEvent.setActionId(actionId); actionReceiptEvent.setStartTime(effectsStartTime); receiptMetaData.setClientIdBits(clientId); int varIdCount = 0; ResizingBuffer varIdsBuffer = receiptMetaData.getVarIdsSlice(); int varIdsCursor = 0; ChunkWriter effectsWriter = actionReceiptEvent.getEffectsWriter(); while(effectsIterator.hasNext()) { ResizingBuffer nextEffectBuffer = effectsIterator.next(); nextEffectBuffer.copyTo(effectsWriter.getChunkBuffer()); effectsWriter.commitChunk(); BufferBackedEffect effect = new BufferBackedEffect(); effect.attachToBuffer(nextEffectBuffer); try { varIdsBuffer.writeInt(varIdsCursor, effect.getVariableId()); varIdsCursor += ResizingBuffer.INT_SIZE; varIdCount++; } finally { effect.releaseBuffer(); } } effectsWriter.finish(); receiptMetaData.setVarIdCount(varIdCount); } finally { actionReceiptEvent.releaseBuffer(); updateChunkWriter.commitChunk(); } } private void processReplayRequest( int clientHandlerId, ReplayRequestEvent replayRequest, StructuredSlidingWindowMap<ResizingBuffer> reliableEventWindow, ResizingBuffer thisRequestReliableBuffer, ChunkWriter updateChunkWriter) { // store a copy of the request into the reliable buffer replayRequest.getBuffer().copyTo(thisRequestReliableBuffer); long headSeq = reliableEventWindow.getHeadIndex(); long tailSeq = headSeq - reliableEventWindow.getLength() + 1; long requestedStartSeq = replayRequest.getStartSequence(); long requestedEndSeq = requestedStartSeq + replayRequest.getCount() - 1; // endSeq is inclusive long startSeq = Math.max(tailSeq, requestedStartSeq); // this can work out to be less than the startSeq if requestedEndSeq < tailSeq: this is safe, and // will result in the replay loop terminating immediately long endSeq = Math.min(headSeq, requestedEndSeq); if (startSeq > requestedStartSeq) { _replayOutOfRangeThroughputMetric.push(1); // Log.warn(String.format("Client Handler %d: requested %d, but %d " + // "was the lowest seq available", clientHandlerId, requestedStartSeq, startSeq)); } for (long seq = startSeq; seq <= endSeq; seq++) { ResizingBuffer receiptChunkBuffer = updateChunkWriter.getChunkBuffer(); final ResizingBuffer reliableEventBuffer = reliableEventWindow.get(seq); int storedEventTypeId = reliableEventBuffer.readInt(0); if (storedEventTypeId == DataType.ACTION_RECEIPT_META_DATA.getId()) { ActionReceiptEvent actionReceiptEvent = new ActionReceiptEvent(); actionReceiptEvent.attachToBuffer(receiptChunkBuffer); ActionReceiptMetaData actionReceiptMetaData = new ActionReceiptMetaData(); actionReceiptMetaData.attachToBuffer(reliableEventBuffer); try { long clientIdBits = actionReceiptMetaData.getClientIdBits(); actionReceiptEvent.writeTypeId(); actionReceiptEvent.setActionId(actionReceiptMetaData.getActionId()); actionReceiptEvent.setClientIdBits(clientIdBits); actionReceiptEvent.setStartTime(actionReceiptMetaData.getStartTime()); ResizingBuffer varIdsBuffer = actionReceiptMetaData.getVarIdsSlice(); int varsIdCount = actionReceiptMetaData.getVarIdCount(); ChunkWriter effectChunkWriter = actionReceiptEvent.getEffectsWriter(); for (int i = 0; i < varsIdCount; i++) { int varId = varIdsBuffer.readInt(i * ResizingBuffer.INT_SIZE); ResizingBuffer effectData = _actionProcessingLogic.getEffectData(clientIdBits, varId); if (effectData.getContentSize() > 0) { effectData.copyTo(effectChunkWriter.getChunkBuffer()); effectChunkWriter.commitChunk(); } } } finally { actionReceiptMetaData.releaseBuffer(); actionReceiptEvent.releaseBuffer(); } } else if (storedEventTypeId == DataType.REPLAY_REQUEST_EVENT.getId()) { ReplayRequestEvent lostReplayRequestEvent = new ReplayRequestEvent(); lostReplayRequestEvent.attachToBuffer(receiptChunkBuffer); try { processReplayRequest(clientHandlerId, lostReplayRequestEvent, reliableEventWindow, new NullResizingBuffer(), updateChunkWriter); } finally { lostReplayRequestEvent.releaseBuffer(); } } } } private void onTick(TickEvent tickEvent) { long time = tickEvent.getTime(); Iterator<CandidateValue> candidateValuesForTick = _actionProcessingLogic.tick(time); _tickDelegate.onTick(time, candidateValuesForTick); } private static StructuredSlidingWindowMap<ResizingBuffer> newClientHandlerReliableEventMap() { return new StructuredSlidingWindowMap<ResizingBuffer>( 4096, ResizingBuffer.class, new ComponentFactory<ResizingBuffer>() { @Override public ResizingBuffer newInstance(Object[] initArgs) { return new ArrayBackedResizingBuffer(Constants.MSG_BUFFER_ENTRY_LENGTH); } }, new InitialiseDelegate<ResizingBuffer>() { @Override public void initialise(ResizingBuffer content) { content.reset(); } }); } }
Updated ActionCollectorProcessor metrics
Service/src/main/java/com/adamroughton/concentus/actioncollector/ActionCollectorProcessor.java
Updated ActionCollectorProcessor metrics
Java
apache-2.0
46162739cd1c6a84be489c9d1853233b0781d980
0
helyho/Voovan,helyho/Voovan,helyho/Voovan
package org.voovan.network; import org.voovan.tools.buffer.ByteBufferChannel; import org.voovan.tools.buffer.TByteBuffer; import org.voovan.tools.exception.MemoryReleasedException; import org.voovan.tools.log.Logger; import javax.net.ssl.*; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.Status; import java.io.IOException; import java.nio.ByteBuffer; /** * SSL 解析器 * 1.握手信息 * 2.报文信息 * * @author helyho * <p> * Voovan Framework. * WebSite: https://github.com/helyho/Voovan * Licence: Apache v2 License */ public class SSLParser { private SSLEngine engine; private ByteBuffer appData; private ByteBuffer netData; private IoSession session; boolean handShakeDone = false; private ByteBufferChannel sslByteBufferChannel; /** * 构造函数 * * @param engine SSLEngine对象 * @param session session 对象 */ public SSLParser(SSLEngine engine, IoSession session) { this.engine = engine; this.session = session; this.appData = buildAppBuffer(); this.netData = buildNetBuffer(); sslByteBufferChannel = new ByteBufferChannel(session.socketContext().getReadBufferSize()); } public ByteBufferChannel getSSlByteBufferChannel() { return sslByteBufferChannel; } /** * 判断握手是否完成 * * @return 握手是否完成 */ public boolean isHandShakeDone() { return handShakeDone; } /** * 获取 SSLEngine * * @return SSLEngine 对象 */ public SSLEngine getSSLEngine() { return engine; } public ByteBuffer buildNetBuffer() { SSLSession sslSession = engine.getSession(); int newBufferMax = sslSession.getPacketBufferSize(); return TByteBuffer.allocateDirect(newBufferMax); } public ByteBuffer buildAppBuffer() { SSLSession sslSession = engine.getSession(); int newBufferMax = sslSession.getPacketBufferSize(); return TByteBuffer.allocateDirect(newBufferMax); } /** * 清理缓冲区 */ private void clearBuffer() { appData.clear(); netData.clear(); } /** * 打包并发送数据 * * @param buffer 需要的数据缓冲区 * @return 返回成功执行的最后一个或者失败的那个 SSLEnginResult * @throws IOException IO 异常 */ public synchronized SSLEngineResult warp(ByteBuffer buffer) throws SSLException { if (session.isConnected()) { SSLEngineResult engineResult = null; do { synchronized (netData) { if(!TByteBuffer.isReleased(netData)) { netData.clear(); engineResult = engine.wrap(buffer, netData); netData.flip(); if (session.isConnected() && engineResult.bytesProduced() > 0 && netData.limit() > 0) { session.sendToBuffer(netData); } netData.clear(); } else { return null; } } } while (engineResult.getStatus() == Status.OK && buffer.hasRemaining()); return engineResult; } else { return null; } } /** * 处理握手 Warp; * * @return * @throws IOException * @throws Exception */ private synchronized HandshakeStatus doHandShakeWarp() throws IOException { if(!session.isConnected()){ return null; } try { clearBuffer(); appData.flip(); if (warp(appData) == null) { return null; } //如果有 HandShake Task 则执行 HandshakeStatus handshakeStatus = runDelegatedTasks(); return handshakeStatus; } catch (SSLException e) { Logger.error("HandShakeWarp error:", e); return null; } } /** * 解包数据 * * @param netBuffer 接受解包数据的缓冲区 * @param appBuffer 接受解包后数据的缓冲区 * @throws SSLException SSL 异常 * @return SSLEngineResult 对象 */ public synchronized SSLEngineResult unwarp(ByteBuffer netBuffer, ByteBuffer appBuffer) throws SSLException { if (session.isConnected()) { SSLEngineResult engineResult = null; if(!TByteBuffer.isReleased(appBuffer)) { engineResult = engine.unwrap(netBuffer, appBuffer); } else { return null; } return engineResult; } else { return null; } } /** * 处理握手 Unwarp; * * @return * @throws IOException * @throws Exception */ private synchronized HandshakeStatus doHandShakeUnwarp() throws IOException { HandshakeStatus handshakeStatus = null; SSLEngineResult engineResult = null; clearBuffer(); if (sslByteBufferChannel.isReleased()) { throw new IOException("Socket is disconnect"); } if (sslByteBufferChannel.size() > 0) { ByteBuffer byteBuffer = sslByteBufferChannel.getByteBuffer(); try { engineResult = unwarp(byteBuffer, appData); if (engineResult == null) { return null; } switch (engineResult.getStatus()) { case OK: { return engine.getHandshakeStatus(); } default: { Logger.error(new SSLHandshakeException("Handshake failed: " + engineResult.getStatus())); session.close(); break; } } } finally { sslByteBufferChannel.compact(); } } return handshakeStatus == null ? engine.getHandshakeStatus() : handshakeStatus; } /** * 执行委派任务 * * @throws Exception */ private synchronized HandshakeStatus runDelegatedTasks() { if (handShakeDone == false) { if (engine.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { Runnable runnable; while ((runnable = engine.getDelegatedTask()) != null) { runnable.run(); } } return engine.getHandshakeStatus(); } return null; } /** * 进行 SSL 握手 * @return true: 握手完成, false: 握手未完成 */ public synchronized boolean doHandShake() { try { engine.beginHandshake(); int handShakeCount = 0; HandshakeStatus handshakeStatus = engine.getHandshakeStatus(); while (!handShakeDone && handShakeCount < 20) { handShakeCount++; if (handshakeStatus == null) { throw new SSLException("doHandShake: Socket is disconnect"); } switch (handshakeStatus) { case NEED_TASK: handshakeStatus = runDelegatedTasks(); break; case NEED_WRAP: handshakeStatus = doHandShakeWarp(); session.flush(); break; case NEED_UNWRAP: if(isEnoughToUnwarp()){ handshakeStatus = doHandShakeUnwarp(); } else { //如果不可解包, 则直接返回, 等待下一次数据接收 handShakeDone = false; } break; case FINISHED: handshakeStatus = engine.getHandshakeStatus(); handShakeDone = true; break; case NOT_HANDSHAKING: //对于粘包数据的处理 if(sslByteBufferChannel.size() > 0){ try { unwarpByteBufferChannel(); } finally { sslByteBufferChannel.compact(); } } handShakeDone = true; break; default: break; } } } catch (Exception e) { Logger.error("SSLParser.doHandShake error:", e); } return handShakeDone; } /** * 读取SSL消息到缓冲区 * * @return 接收数据大小 * @throws IOException IO异常 */ public synchronized int unwarpByteBufferChannel() throws IOException { ByteBufferChannel appByteBufferChannel = session.getReadByteBufferChannel(); if(!isEnoughToUnwarp()) { return 0; } int readSize = 0; if (session.isConnected() && sslByteBufferChannel.size() > 0) { SSLEngineResult engineResult = null; try { ByteBuffer appData = appByteBufferChannel.getByteBuffer(); try { appData.limit(appData.capacity()); while (true) { ByteBuffer sslByteBuffer = sslByteBufferChannel.getByteBuffer(); try { engineResult = unwarp(sslByteBuffer, appData); } finally { sslByteBufferChannel.compact(); } if (engineResult == null) { throw new SSLException("unWarpByteBufferChannel: Socket is disconnect"); } if (engineResult.getStatus() == Status.OK && sslByteBuffer.remaining() == 0) { break; } if (engineResult.getStatus() != Status.OK) { break; } } appData.flip(); } finally { appByteBufferChannel.compact(); } }catch (MemoryReleasedException e){ if(!session.isConnected()) { throw new SSLException("unWarpByteBufferChannel ", e); } } } return readSize; } /** * 释放方法 */ public void release() { TByteBuffer.release(netData); TByteBuffer.release(appData); sslByteBufferChannel.release(); } /** * 判断给定的会话握手是否完成 * @param session IoSession 对象 * @return true:握手完成或不需要握手, false:握手未完成 */ public static boolean isHandShakeDone(IoSession session){ if(session==null || !session.isSSLMode()){ return true; }else{ return session.getSSLParser().isHandShakeDone(); } } /** <pre> record type (1 byte) / / version (1 byte major, 1 byte minor) / / / / length (2 bytes) / / / +----+----+----+----+----+ | | | | | | | | | | | | TLS Record header +----+----+----+----+----+ Record Type Values dec hex ------------------------------------- CHANGE_CIPHER_SPEC 20 0x14 ALERT 21 0x15 HANDSHAKE 22 0x16 APPLICATION_DATA 23 0x17 Version Values dec hex ------------------------------------- SSL 3.0 3,0 0x0300 TLS 1.0 3,1 0x0301 TLS 1.1 3,2 0x0302 TLS 1.2 3,3 0x0303 ref:http://blog.fourthbit.com/2014/12/23/traffic-analysis-of-an-ssl-slash-tls-session/ </pre> */ private boolean isEnoughToUnwarp() throws SSLException { ByteBuffer src = sslByteBufferChannel.getByteBuffer(); try { if (src.remaining() < 5) { return false; } int pos = src.position(); // TLS - Check ContentType int type = src.get(pos) & 0xff; if (type < 20 || type > 23) { throw new SSLException("Not SSL package"); } // TLS - Check ProtocolVersion int majorVersion = src.get(pos + 1) & 0xff; int minorVersion = src.get(pos + 2) & 0xff; int packetLength = src.getShort(pos + 3) & 0xffff; if (majorVersion != 3 || minorVersion < 1) { // NOT TLS (i.e. SSLv2,3 or bad data) throw new SSLException("Not TLS protocol"); } int len = packetLength + 5; if (src.remaining() < len) { return false; } return true; } finally { sslByteBufferChannel.compact(); } } }
Network/src/main/java/org/voovan/network/SSLParser.java
package org.voovan.network; import org.voovan.tools.buffer.ByteBufferChannel; import org.voovan.tools.buffer.TByteBuffer; import org.voovan.tools.exception.MemoryReleasedException; import org.voovan.tools.log.Logger; import javax.net.ssl.*; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.Status; import java.io.IOException; import java.nio.ByteBuffer; /** * SSL 解析器 * 1.握手信息 * 2.报文信息 * * @author helyho * <p> * Voovan Framework. * WebSite: https://github.com/helyho/Voovan * Licence: Apache v2 License */ public class SSLParser { private SSLEngine engine; private ByteBuffer appData; private ByteBuffer netData; private IoSession session; boolean handShakeDone = false; private ByteBufferChannel sslByteBufferChannel; /** * 构造函数 * * @param engine SSLEngine对象 * @param session session 对象 */ public SSLParser(SSLEngine engine, IoSession session) { this.engine = engine; this.session = session; this.appData = buildAppBuffer(); this.netData = buildNetBuffer(); sslByteBufferChannel = new ByteBufferChannel(session.socketContext().getReadBufferSize()); } public ByteBufferChannel getSSlByteBufferChannel() { return sslByteBufferChannel; } /** * 判断握手是否完成 * * @return 握手是否完成 */ public boolean isHandShakeDone() { return handShakeDone; } /** * 获取 SSLEngine * * @return SSLEngine 对象 */ public SSLEngine getSSLEngine() { return engine; } public ByteBuffer buildNetBuffer() { SSLSession sslSession = engine.getSession(); int newBufferMax = sslSession.getPacketBufferSize(); return TByteBuffer.allocateDirect(newBufferMax); } public ByteBuffer buildAppBuffer() { SSLSession sslSession = engine.getSession(); int newBufferMax = sslSession.getPacketBufferSize(); return TByteBuffer.allocateDirect(newBufferMax); } /** * 清理缓冲区 */ private void clearBuffer() { appData.clear(); netData.clear(); } /** * 打包并发送数据 * * @param buffer 需要的数据缓冲区 * @return 返回成功执行的最后一个或者失败的那个 SSLEnginResult * @throws IOException IO 异常 */ public synchronized SSLEngineResult warp(ByteBuffer buffer) throws SSLException { if (session.isConnected()) { SSLEngineResult engineResult = null; do { synchronized (netData) { if(!TByteBuffer.isReleased(netData)) { netData.clear(); engineResult = engine.wrap(buffer, netData); netData.flip(); if (session.isConnected() && engineResult.bytesProduced() > 0 && netData.limit() > 0) { session.sendToBuffer(netData); } netData.clear(); } else { return null; } } } while (engineResult.getStatus() == Status.OK && buffer.hasRemaining()); return engineResult; } else { return null; } } /** * 处理握手 Warp; * * @return * @throws IOException * @throws Exception */ private synchronized HandshakeStatus doHandShakeWarp() throws IOException { if(!session.isConnected()){ return null; } try { clearBuffer(); appData.flip(); if (warp(appData) == null) { return null; } //如果有 HandShake Task 则执行 HandshakeStatus handshakeStatus = runDelegatedTasks(); return handshakeStatus; } catch (SSLException e) { Logger.error("HandShakeWarp error:", e); return null; } } /** * 解包数据 * * @param netBuffer 接受解包数据的缓冲区 * @param appBuffer 接受解包后数据的缓冲区 * @throws SSLException SSL 异常 * @return SSLEngineResult 对象 */ public synchronized SSLEngineResult unwarp(ByteBuffer netBuffer, ByteBuffer appBuffer) throws SSLException { if (session.isConnected()) { SSLEngineResult engineResult = null; if(!TByteBuffer.isReleased(appBuffer)) { engineResult = engine.unwrap(netBuffer, appBuffer); } else { return null; } return engineResult; } else { return null; } } /** * 处理握手 Unwarp; * * @return * @throws IOException * @throws Exception */ private synchronized HandshakeStatus doHandShakeUnwarp() throws IOException { HandshakeStatus handshakeStatus = null; SSLEngineResult engineResult = null; clearBuffer(); if (sslByteBufferChannel.isReleased()) { throw new IOException("Socket is disconnect"); } if (sslByteBufferChannel.size() > 0) { ByteBuffer byteBuffer = sslByteBufferChannel.getByteBuffer(); try { engineResult = unwarp(byteBuffer, appData); if (engineResult == null) { return null; } switch (engineResult.getStatus()) { case OK: { return engine.getHandshakeStatus(); } default: { Logger.error(new SSLHandshakeException("Handshake failed: " + engineResult.getStatus())); session.close(); break; } } } finally { sslByteBufferChannel.compact(); } } return handshakeStatus == null ? engine.getHandshakeStatus() : handshakeStatus; } /** * 执行委派任务 * * @throws Exception */ private synchronized HandshakeStatus runDelegatedTasks() { if (handShakeDone == false) { if (engine.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { Runnable runnable; while ((runnable = engine.getDelegatedTask()) != null) { runnable.run(); } } return engine.getHandshakeStatus(); } return null; } /** * 进行 SSL 握手 * @return true: 握手完成, false: 握手未完成 */ public synchronized boolean doHandShake() { try { engine.beginHandshake(); int handShakeCount = 0; HandshakeStatus handshakeStatus = engine.getHandshakeStatus(); while (!handShakeDone && handShakeCount < 20) { handShakeCount++; if (handshakeStatus == null) { throw new SSLException("doHandShake: Socket is disconnect"); } switch (handshakeStatus) { case NEED_TASK: handshakeStatus = runDelegatedTasks(); break; case NEED_WRAP: handshakeStatus = doHandShakeWarp(); session.flush(); break; case NEED_UNWRAP: if(isEnoughToUnwarp()){ handshakeStatus = doHandShakeUnwarp(); } else { //如果不可解包, 则直接返回, 等待下一次数据接收 handShakeDone = false; } break; case FINISHED: handshakeStatus = engine.getHandshakeStatus(); handShakeDone = true; break; case NOT_HANDSHAKING: //对于粘包数据的处理 if(sslByteBufferChannel.size() > 0){ try { unwarpByteBufferChannel(); } finally { sslByteBufferChannel.compact(); } } handShakeDone = true; break; default: break; } } } catch (Exception e) { Logger.error("SSLParser.doHandShake error:", e); } return handShakeDone; } /** * 读取SSL消息到缓冲区 * * @return 接收数据大小 * @throws IOException IO异常 */ public synchronized int unwarpByteBufferChannel() throws IOException { ByteBufferChannel appByteBufferChannel = session.getReadByteBufferChannel(); if(!isEnoughToUnwarp()) { return 0; } int readSize = 0; if (session.isConnected() && sslByteBufferChannel.size() > 0) { SSLEngineResult engineResult = null; try { ByteBuffer appData = appByteBufferChannel.getByteBuffer(); try { appData.limit(appData.capacity()); while (true) { ByteBuffer sslByteBuffer = sslByteBufferChannel.getByteBuffer(); ; try { engineResult = unwarp(sslByteBuffer, appData); } finally { sslByteBufferChannel.compact(); } if (engineResult == null) { throw new SSLException("unWarpByteBufferChannel: Socket is disconnect"); } if (engineResult.getStatus() == Status.OK && sslByteBuffer.remaining() == 0) { break; } if (engineResult.getStatus() != Status.OK) { break; } } appData.flip(); } finally { appByteBufferChannel.compact(); } }catch (MemoryReleasedException e){ if(!session.isConnected()) { throw new SSLException("unWarpByteBufferChannel ", e); } } } return readSize; } /** * 释放方法 */ public void release() { TByteBuffer.release(netData); TByteBuffer.release(appData); sslByteBufferChannel.release(); } /** * 判断给定的会话握手是否完成 * @param session IoSession 对象 * @return true:握手完成或不需要握手, false:握手未完成 */ public static boolean isHandShakeDone(IoSession session){ if(session==null || !session.isSSLMode()){ return true; }else{ return session.getSSLParser().isHandShakeDone(); } } /** <pre> record type (1 byte) / / version (1 byte major, 1 byte minor) / / / / length (2 bytes) / / / +----+----+----+----+----+ | | | | | | | | | | | | TLS Record header +----+----+----+----+----+ Record Type Values dec hex ------------------------------------- CHANGE_CIPHER_SPEC 20 0x14 ALERT 21 0x15 HANDSHAKE 22 0x16 APPLICATION_DATA 23 0x17 Version Values dec hex ------------------------------------- SSL 3.0 3,0 0x0300 TLS 1.0 3,1 0x0301 TLS 1.1 3,2 0x0302 TLS 1.2 3,3 0x0303 ref:http://blog.fourthbit.com/2014/12/23/traffic-analysis-of-an-ssl-slash-tls-session/ </pre> */ private boolean isEnoughToUnwarp() throws SSLException { ByteBuffer src = sslByteBufferChannel.getByteBuffer(); try { if (src.remaining() < 5) { return false; } int pos = src.position(); // TLS - Check ContentType int type = src.get(pos) & 0xff; if (type < 20 || type > 23) { throw new SSLException("Not SSL package"); } // TLS - Check ProtocolVersion int majorVersion = src.get(pos + 1) & 0xff; int minorVersion = src.get(pos + 2) & 0xff; int packetLength = src.getShort(pos + 3) & 0xffff; if (majorVersion != 3 || minorVersion < 1) { // NOT TLS (i.e. SSLv2,3 or bad data) throw new SSLException("Not TLS protocol"); } int len = packetLength + 5; if (src.remaining() < len) { return false; } return true; } finally { sslByteBufferChannel.compact(); } } }
imp: SSLParser 相关优化
Network/src/main/java/org/voovan/network/SSLParser.java
imp: SSLParser 相关优化
Java
apache-2.0
61b0b1ef977a46765694cd08006739778ebb5431
0
JNOSQL/diana-driver,JNOSQL/diana-driver
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jnosql.diana.riak.key; import com.basho.riak.client.core.RiakCluster; import com.basho.riak.client.core.RiakNode; import org.jnosql.diana.api.key.KeyValueConfiguration; import org.jnosql.diana.driver.ConfigurationReader; import org.jnosql.diana.driver.ConfigurationReaderException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.logging.Logger; /** * The riak implementation to {@link KeyValueConfiguration} that returns {@link RiakKeyValueEntityManagerFactory}. * It tries to read diana-riak.properties file. * <p>riak-server-host-: The prefix to host. eg: riak-server-host-1= host1</p> */ public class RiakConfiguration implements KeyValueConfiguration<RiakKeyValueEntityManagerFactory> { private static final String SERVER_PREFIX = "riak-server-host-"; private static Logger LOGGER = Logger.getLogger(RiakConfiguration.class.getName()); private static final String FILE_CONFIGURATION = "diana-riak.properties"; private static final RiakNode DEFAULT_NODE = new RiakNode.Builder() .withRemoteAddress("127.0.0.1").build(); private final List<RiakNode> nodes = new ArrayList<>(); private RiakCluster cluster; public RiakConfiguration() { try { Map<String, String> properties = ConfigurationReader.from(FILE_CONFIGURATION); properties.keySet().stream() .filter(k -> k.startsWith(SERVER_PREFIX)) .sorted().map(properties::get) .forEach(this::add); } catch (ConfigurationReaderException ex) { LOGGER.fine("Configuration file to arandodb does not found"); } } /** * Adds new Riak node * * @param node the node * @throws NullPointerException when node is null */ public void add(RiakNode node) throws NullPointerException { Objects.requireNonNull(node, "Node is required"); this.nodes.add(node); } /** * Adds a new address on riak * * @param address the address to be added * @throws NullPointerException when address is null */ public void add(String address) throws NullPointerException { Objects.requireNonNull(address, "Address is required"); this.nodes.add(new RiakNode.Builder().withRemoteAddress(address).build()); } @Override public RiakKeyValueEntityManagerFactory getManagerFactory() { if (nodes.isEmpty()) { nodes.add(DEFAULT_NODE); } cluster = new RiakCluster.Builder(nodes) .build(); return new RiakKeyValueEntityManagerFactory(cluster); } }
riak-driver/src/main/java/org/jnosql/diana/riak/key/RiakConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jnosql.diana.riak.key; import com.basho.riak.client.core.RiakCluster; import com.basho.riak.client.core.RiakNode; import org.jnosql.diana.api.key.KeyValueConfiguration; import org.jnosql.diana.driver.ConfigurationReader; import org.jnosql.diana.driver.ConfigurationReaderException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.logging.Logger; /** * The riak implementation to {@link KeyValueConfiguration} that returns {@link RiakKeyValueEntityManagerFactory}. * It tries to read diana-riak.properties file. * <p>riak-server-host-: The prefix to host. eg: riak-server-host-1= host1</p> */ public class RiakConfiguration implements KeyValueConfiguration<RiakKeyValueEntityManagerFactory> { private static Logger LOGGER = Logger.getLogger(RiakConfiguration.class.getName()); private static final String FILE_CONFIGURATION = "diana-riak.properties"; private static final RiakNode DEFAULT_NODE = new RiakNode.Builder() .withRemoteAddress("127.0.0.1").build(); private final List<RiakNode> nodes = new ArrayList<>(); private RiakCluster cluster; public RiakConfiguration() { try { Map<String, String> properties = ConfigurationReader.from(FILE_CONFIGURATION); } catch (ConfigurationReaderException ex) { LOGGER.fine("Configuration file to arandodb does not found"); } } /** * Adds new Riak node * * @param node the node * @throws NullPointerException when node is null */ public void add(RiakNode node) throws NullPointerException { Objects.requireNonNull(node, "Node is required"); this.nodes.add(node); } /** * Adds a new address on riak * * @param address the address to be added * @throws NullPointerException when address is null */ public void add(String address) throws NullPointerException { Objects.requireNonNull(address, "Address is required"); this.nodes.add(new RiakNode.Builder().withRemoteAddress(address).build()); } @Override public RiakKeyValueEntityManagerFactory getManagerFactory() { if (nodes.isEmpty()) { nodes.add(DEFAULT_NODE); } cluster = new RiakCluster.Builder(nodes) .build(); return new RiakKeyValueEntityManagerFactory(cluster); } }
Adds read riak configuration
riak-driver/src/main/java/org/jnosql/diana/riak/key/RiakConfiguration.java
Adds read riak configuration
Java
apache-2.0
9fefa8459f3a14147a8defa8e63d3408d2ba5043
0
jtheulier/bouquet-java-sdk,jtheulier/bouquet-java-sdk
/******************************************************************************* * Copyright 2017 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package io.bouquet.v4.client; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import io.bouquet.v4.ApiException; import io.bouquet.v4.api.ModelApi; import io.bouquet.v4.client.CacheConfiguration.ComparePeriod; import io.bouquet.v4.model.Bookmark; import io.bouquet.v4.model.ChosenMetric; import io.bouquet.v4.model.Dimension; import io.bouquet.v4.model.Dimension.TypeEnum; import io.bouquet.v4.model.Domain; import io.bouquet.v4.model.DomainPK; import io.bouquet.v4.model.Expression; import io.bouquet.v4.model.Facet; import io.bouquet.v4.model.FacetMember; import io.bouquet.v4.model.FacetMemberInterval; import io.bouquet.v4.model.FacetSelection; import io.bouquet.v4.model.Metric; import io.bouquet.v4.model.OrderBy; import io.bouquet.v4.model.OrderBy.DirectionEnum; import io.bouquet.v4.model.ProjectAnalysisJob; import io.bouquet.v4.model.ProjectAnalysisJobPK; import io.bouquet.v4.model.ProjectFacetJob; import io.bouquet.v4.model.ProjectFacetJobPK; import io.bouquet.v4.model.RollUp; public class ClientEngine { Logger logger = Logger.getLogger(ClientEngine.class); public ClientEngine() { super(); } public void writeAnalysisResult(InputStream in, OutputStream out) throws ApiException, IOException, FileNotFoundException { if (in != null && out != null) { try { IOUtils.copy(in, out); } finally { try { in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } } public Object getAnalysisJobResults(ModelApi api, ProjectAnalysisJob analysis, Integer timeout, Integer maxResults, Integer startIndex, Boolean lazy, String format, String compression, int maxLoops) throws ApiException { boolean done = false; int loops = 0; String projectId = null; String jobId = null; Object result = null; if (analysis != null) { projectId = analysis.getId().getProjectId(); jobId = analysis.getId().getAnalysisJobId(); while (!done) { // Launch the execution result = api.getAnalysisJobResults(projectId, jobId, timeout, maxResults, startIndex, lazy, format, compression); ProjectAnalysisJob analysisJob = api.getAnalysisJob(projectId, jobId, null, 10000); loops++; if (result != null || (analysisJob != null && analysisJob.getStatus() != null && analysisJob.getStatus() == ProjectAnalysisJob.StatusEnum.DONE)) { done = true; if (result instanceof ApiException) { if (((ApiException) result).getMessage() == "COMPUTING_IN_PROGRESS") { result = api.getAnalysisJobResults(projectId, jobId, timeout, maxResults, startIndex, lazy, format, compression); } } return result; } else { if (loops > maxLoops) { done = true; } else { synchronized (this) { try { this.wait(60 * 1000); } catch (InterruptedException ie) { // TODO Auto-generated catch block throw new ApiException(ie); } } } } } } return null; } public boolean executeFacetJob(ModelApi api, Domain domain, List<Dimension> dimensions, boolean wait) throws ApiException, InterruptedException { ProjectFacetJob job = new ProjectFacetJob(); job.setDomains(Arrays.asList(domain.getId())); ProjectFacetJobPK facetJobId = new ProjectFacetJobPK(); job.setId(facetJobId); facetJobId.setProjectId(domain.getId().getProjectId()); job = api.postFacetJob(domain.getId().getProjectId(), job, null); List<Facet> remainingFacets = job.getResults().getFacets(); int retry = 10; if (!wait) { retry = 1; wait = true; } if (wait) { int facetsNr = 0; Domain facetsDomain = api.getDomain(domain.getId().getProjectId(), domain.getId().getDomainId(), false); while (retry > 0) { // job = api.getOrStoreFacetJob(domain.getProjectId(), job.getId().getFacetJobId(), null, null); // job = api.putFacetJob(domain.getProjectId(), job, null); if (job.getStatus() == ProjectFacetJob.StatusEnum.DONE) { List<Facet> computingFacets = new ArrayList<Facet>(); if (job.getError() == null) { computingFacets.clear(); computingFacets.addAll(remainingFacets); for (Facet facet : remainingFacets) { String facetName = facet.getName(); try { facet = api.getFacet(domain.getId().getProjectId(), job.getId().getFacetJobId(), facet.getId(), null, 10, 10, 0); if (facet.isProxy() != null && facet.isProxy()) { logger.debug("Proxied facet '" + facetName + "'"); computingFacets.remove(facet); } else if (facet.isError() != null && facet.isError() == false && (facet.isDone() == true)) { if (facet.getDimension() != null && facet.getDimension().getType() == TypeEnum.CATEGORICAL) { logger.debug("Facet '" + facetName + "' done"); } computingFacets.remove(facet); } else if (facet.isDone() == true && facet.isHasMore() == false && facet.isError() == true) { logger.debug("Facet '" + facetName + "' in error " + facet.getErrorMessage()); computingFacets.remove(facet); } else if (retry == 1) { logger.debug("Ongoing processing on facet '" + facetName + "'"); } } catch (ApiException ae) { logger.debug("Error occured while checking facet '" + facetName + "' :" + ae.getMessage() + " with body " + ae.getResponseBody()); throw ae; } } facetsNr = computingFacets.size(); remainingFacets.clear(); remainingFacets.addAll(computingFacets); if (facetsNr == 0) { retry = 0; } } else { retry = 0; } } if (retry > 1) { synchronized (this) { this.wait(5 * 1000L); } } retry--; } if (job.getStatus() != ProjectFacetJob.StatusEnum.DONE) { logger.debug("Processing facet job " + job.getStatus() + " on domain" + facetsDomain.getName()); } else if (facetsNr > 0) { logger.debug("Leaving facet job processing on domain " + facetsDomain.getName() + " with " + facetsNr + " still running"); } } return true; } public ProjectAnalysisJob buildAnalysisFromBookmark(ModelApi api, Bookmark bookmark, boolean isSummary, ComparePeriod defaultComparePeriod) throws ApiException, InterruptedException { if (bookmark != null) { ProjectAnalysisJob analysis = new ProjectAnalysisJob(); DomainPK domain = api.getDomain(bookmark.getId().getProjectId(), bookmark.getConfig().getDomain(), false).getId(); // executeFacetJob(api, domain, false); FacetSelection selection = new FacetSelection(); if (bookmark.getConfig() != null && bookmark.getConfig().getSelection() != null) { selection.setFacets(bookmark.getConfig().getSelection().getFacets()); selection.setRootFacets(bookmark.getConfig().getSelection().getRootFacets()); selection.setCompareTo(bookmark.getConfig().getSelection().getCompareTo()); } if ((selection.getCompareTo() == null || selection.getCompareTo().size() == 0) && defaultComparePeriod != ComparePeriod.__NONE && bookmark.getConfig().getPeriod() != null) { if (bookmark.getConfig().getPeriod().any() != null && bookmark.getConfig().getPeriod().any().size() == 1) { FacetMemberInterval compare = new FacetMemberInterval(); compare.setType("i"); compare.setLowerBound(defaultComparePeriod.toString()); compare.setUpperBound(defaultComparePeriod.toString()); Facet facet = new Facet(); Dimension dim = api.getDimension(bookmark.getId().getProjectId(), bookmark.getConfig().getDomain(), APIUtils.splitDomainObject(bookmark.getConfig().getPeriod().any().values().iterator() .next())[1], true); facet.setDimension(dim); facet.setName(dim.getName()); facet.setId("@'" + bookmark.getConfig().getDomain() + "'.@'" + dim.getOid() + "'"); facet.setSelectedItems(new ArrayList<FacetMember>(Arrays.asList(compare))); facet.setError(false); facet.setHasMore(false); facet.setDone(true); selection.setCompareTo(new ArrayList<Facet>(Arrays.asList(facet))); } } if (selection.getCompareTo() != null && selection.getCompareTo().size() > 0) { analysis.setOptionKeys(new HashMap<String, Object>() { private static final long serialVersionUID = 8372602286359963290L; { put("applyFormat", true); put("computeGrowth", true); } }); } analysis.setSelection(selection); analysis.setAutoRun(false); List<DomainPK> domains = new ArrayList<DomainPK>(); domains.add(domain); analysis.setDomains(domains); List<Expression> facets = new ArrayList<Expression>(); List<String> dims = bookmark.getConfig().getChosenDimensions(); List<RollUp> rollups = new ArrayList<RollUp>(); List<OrderBy> orderBys = new ArrayList<OrderBy>(); if ("timeAnalysis".equals(bookmark.getConfig().getCurrentAnalysis()) && bookmark.getConfig().getPeriod() != null) { Map<String, String> periods = bookmark.getConfig().getPeriod().any(); Expression expression = new Expression(); Entry<String, String> period = periods.entrySet().iterator().next(); expression.setValue("TO_DATE(" + period.getValue() + ")"); facets.add(expression); OrderBy timeOrder = new OrderBy(); timeOrder.col(0); timeOrder.direction(DirectionEnum.DESC); orderBys.add(timeOrder); } if (isSummary == false && dims != null) { for (String dim : dims) { Expression expression = new Expression(); expression.setValue(dim); facets.add(expression); } } analysis.setFacets(facets); if (bookmark.getConfig().getRollUps() != null) { rollups.addAll(bookmark.getConfig().getRollUps()); } List<OrderBy> bookmarkOrderBys = bookmark.getConfig().getOrderBy(); if (orderBys != null && bookmarkOrderBys != null) { for (OrderBy orderBy : bookmarkOrderBys) { if (orderBy.getCol() != null || orderBy.getExpression().getValue() != null) { orderBys.add(orderBy); } } } ProjectAnalysisJobPK analysisJobPK = new ProjectAnalysisJobPK(); analysisJobPK.setProjectId(bookmark.getId().getProjectId()); analysis.setId(analysisJobPK); // Do not define an id to let it temporary List<String> mets = bookmark.getConfig().getAvailableMetrics(); ArrayList<Metric> metrics = new ArrayList<Metric>(); if (isSummary) { if (mets != null) { for (String met : mets) { if (met != null) { Metric metric = api.getMetric(bookmark.getId().getProjectId(), domain.getDomainId(), met, false); if (metric == null) { throw new ApiException("Invalid metric Id " + met); } metric.getAccessRights().clear(); metrics.add(metric); } analysis.setMetricList(metrics); } } analysis.setOptionKeys(new HashMap<String, Object>() { private static final long serialVersionUID = -3511263422949970083L; { put("applyFormat", true); put("computeGrowth", false); } }); } else { analysis.setOrderBy(orderBys); analysis.setRollups(rollups); List<ChosenMetric> choosens = bookmark.getConfig().getChosenMetrics(); if (choosens != null) { for (String met : mets) { for (ChosenMetric choosen : choosens) { if (met.equals(choosen.getId())) { if (choosen.getId() != null && choosen.getId().indexOf("@")==-1) { Metric metric = api.getMetric(bookmark.getId().getProjectId(), domain.getDomainId(), choosen.getId(), false); if (metric == null) { throw new ApiException("Invalid metric Id " + met); } metric.getAccessRights().clear(); metrics.add(metric); } else if (choosen.getId() != null) { Metric metric = new Metric(); metric.setExpression(new Expression().value(choosen.getId())); metric.setDynamic(false); metrics.add(metric); } else if (choosen.getExpression() != null) { Metric metric = new Metric(); metric.setExpression(choosen.getExpression()); metric.setDynamic(false); metrics.add(metric); } } } } analysis.setMetricList(metrics); } } return analysis; } return null; } }
src/main/java/io/bouquet/v4/client/ClientEngine.java
/******************************************************************************* * Copyright 2017 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package io.bouquet.v4.client; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import io.bouquet.v4.ApiException; import io.bouquet.v4.api.ModelApi; import io.bouquet.v4.client.CacheConfiguration.ComparePeriod; import io.bouquet.v4.model.Bookmark; import io.bouquet.v4.model.ChosenMetric; import io.bouquet.v4.model.Dimension; import io.bouquet.v4.model.Dimension.TypeEnum; import io.bouquet.v4.model.Domain; import io.bouquet.v4.model.DomainPK; import io.bouquet.v4.model.Expression; import io.bouquet.v4.model.Facet; import io.bouquet.v4.model.FacetMember; import io.bouquet.v4.model.FacetMemberInterval; import io.bouquet.v4.model.FacetSelection; import io.bouquet.v4.model.Metric; import io.bouquet.v4.model.OrderBy; import io.bouquet.v4.model.OrderBy.DirectionEnum; import io.bouquet.v4.model.ProjectAnalysisJob; import io.bouquet.v4.model.ProjectAnalysisJobPK; import io.bouquet.v4.model.ProjectFacetJob; import io.bouquet.v4.model.ProjectFacetJobPK; import io.bouquet.v4.model.RollUp; public class ClientEngine { Logger logger = Logger.getLogger(ClientEngine.class); public ClientEngine() { super(); } public void writeAnalysisResult(InputStream in, OutputStream out) throws ApiException, IOException, FileNotFoundException { if (in != null && out != null) { try { IOUtils.copy(in, out); } finally { try { in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } } public Object getAnalysisJobResults(ModelApi api, ProjectAnalysisJob analysis, Integer timeout, Integer maxResults, Integer startIndex, Boolean lazy, String format, String compression, int maxLoops) throws ApiException { boolean done = false; int loops = 0; String projectId = null; String jobId = null; Object result = null; if (analysis != null) { projectId = analysis.getId().getProjectId(); jobId = analysis.getId().getAnalysisJobId(); while (!done) { // Launch the execution result = api.getAnalysisJobResults(projectId, jobId, timeout, maxResults, startIndex, lazy, format, compression); ProjectAnalysisJob analysisJob = api.getAnalysisJob(projectId, jobId, null, 10000); loops++; if (result != null || (analysisJob != null && analysisJob.getStatus() != null && analysisJob.getStatus() == ProjectAnalysisJob.StatusEnum.DONE)) { done = true; if (result instanceof ApiException) { if (((ApiException) result).getMessage() == "COMPUTING_IN_PROGRESS") { result = api.getAnalysisJobResults(projectId, jobId, timeout, maxResults, startIndex, lazy, format, compression); } } return result; } else { if (loops > maxLoops) { done = true; } else { synchronized (this) { try { this.wait(60 * 1000); } catch (InterruptedException ie) { // TODO Auto-generated catch block throw new ApiException(ie); } } } } } } return null; } public boolean executeFacetJob(ModelApi api, Domain domain, List<Dimension> dimensions, boolean wait) throws ApiException, InterruptedException { ProjectFacetJob job = new ProjectFacetJob(); job.setDomains(Arrays.asList(domain.getId())); ProjectFacetJobPK facetJobId = new ProjectFacetJobPK(); job.setId(facetJobId); facetJobId.setProjectId(domain.getId().getProjectId()); job = api.postFacetJob(domain.getId().getProjectId(), job, null); List<Facet> remainingFacets = job.getResults().getFacets(); int retry = 10; if (!wait) { retry = 1; wait = true; } if (wait) { int facetsNr = 0; Domain facetsDomain = api.getDomain(domain.getId().getProjectId(), domain.getId().getDomainId(), false); while (retry > 0) { // job = api.getOrStoreFacetJob(domain.getProjectId(), job.getId().getFacetJobId(), null, null); // job = api.putFacetJob(domain.getProjectId(), job, null); if (job.getStatus() == ProjectFacetJob.StatusEnum.DONE) { List<Facet> computingFacets = new ArrayList<Facet>(); if (job.getError() == null) { computingFacets.clear(); computingFacets.addAll(remainingFacets); for (Facet facet : remainingFacets) { String facetName = facet.getName(); try { facet = api.getFacet(domain.getId().getProjectId(), job.getId().getFacetJobId(), facet.getId(), null, 10, 10, 0); if (facet.isProxy() != null && facet.isProxy()) { logger.debug("Proxied facet '" + facetName + "'"); computingFacets.remove(facet); } else if (facet.isError() != null && facet.isError() == false && (facet.isDone() == true)) { if (facet.getDimension() != null && facet.getDimension().getType() == TypeEnum.CATEGORICAL) { logger.debug("Facet '" + facetName + "' done"); } computingFacets.remove(facet); } else if (facet.isDone() == true && facet.isHasMore() == false && facet.isError() == true) { logger.debug("Facet '" + facetName + "' in error " + facet.getErrorMessage()); computingFacets.remove(facet); } else if (retry == 1) { logger.debug("Ongoing processing on facet '" + facetName + "'"); } } catch (ApiException ae) { logger.debug("Error occured while checking facet '" + facetName + "' :" + ae.getMessage() + " with body " + ae.getResponseBody()); throw ae; } } facetsNr = computingFacets.size(); remainingFacets.clear(); remainingFacets.addAll(computingFacets); if (facetsNr == 0) { retry = 0; } } else { retry = 0; } } if (retry > 1) { synchronized (this) { this.wait(5 * 1000L); } } retry--; } if (job.getStatus() != ProjectFacetJob.StatusEnum.DONE) { logger.debug("Processing facet job " + job.getStatus() + " on domain" + facetsDomain.getName()); } else if (facetsNr > 0) { logger.debug("Leaving facet job processing on domain " + facetsDomain.getName() + " with " + facetsNr + " still running"); } } return true; } public ProjectAnalysisJob buildAnalysisFromBookmark(ModelApi api, Bookmark bookmark, boolean isSummary, ComparePeriod defaultComparePeriod) throws ApiException, InterruptedException { if (bookmark != null) { ProjectAnalysisJob analysis = new ProjectAnalysisJob(); DomainPK domain = api.getDomain(bookmark.getId().getProjectId(), bookmark.getConfig().getDomain(), false).getId(); // executeFacetJob(api, domain, false); FacetSelection selection = new FacetSelection(); if (bookmark.getConfig() != null && bookmark.getConfig().getSelection() != null) { selection.setFacets(bookmark.getConfig().getSelection().getFacets()); selection.setRootFacets(bookmark.getConfig().getSelection().getRootFacets()); selection.setCompareTo(bookmark.getConfig().getSelection().getCompareTo()); } if ((selection.getCompareTo() == null || selection.getCompareTo().size() == 0) && defaultComparePeriod != ComparePeriod.__NONE && bookmark.getConfig().getPeriod() != null) { if (bookmark.getConfig().getPeriod().any() != null && bookmark.getConfig().getPeriod().any().size() == 1) { FacetMemberInterval compare = new FacetMemberInterval(); compare.setType("i"); compare.setLowerBound(defaultComparePeriod.toString()); compare.setUpperBound(defaultComparePeriod.toString()); Facet facet = new Facet(); Dimension dim = api.getDimension(bookmark.getId().getProjectId(), bookmark.getConfig().getDomain(), APIUtils.splitDomainObject(bookmark.getConfig().getPeriod().any().values().iterator() .next())[1], true); facet.setDimension(dim); facet.setName(dim.getName()); facet.setId("@'" + bookmark.getConfig().getDomain() + "'.@'" + dim.getOid() + "'"); facet.setSelectedItems(new ArrayList<FacetMember>(Arrays.asList(compare))); facet.setError(false); facet.setHasMore(false); facet.setDone(true); selection.setCompareTo(new ArrayList<Facet>(Arrays.asList(facet))); } } if (selection.getCompareTo() != null && selection.getCompareTo().size() > 0) { analysis.setOptionKeys(new HashMap<String, Object>() { private static final long serialVersionUID = 8372602286359963290L; { put("applyFormat", true); put("computeGrowth", true); } }); } analysis.setSelection(selection); analysis.setAutoRun(false); List<DomainPK> domains = new ArrayList<DomainPK>(); domains.add(domain); analysis.setDomains(domains); List<Expression> facets = new ArrayList<Expression>(); List<String> dims = bookmark.getConfig().getChosenDimensions(); List<RollUp> rollups = new ArrayList<RollUp>(); List<OrderBy> orderBys = new ArrayList<OrderBy>(); if ("timeAnalysis".equals(bookmark.getConfig().getCurrentAnalysis()) && bookmark.getConfig().getPeriod() != null) { Map<String, String> periods = bookmark.getConfig().getPeriod().any(); Expression expression = new Expression(); Entry<String, String> period = periods.entrySet().iterator().next(); expression.setValue("TO_DATE(" + period.getValue() + ")"); facets.add(expression); OrderBy timeOrder = new OrderBy(); timeOrder.col(0); timeOrder.direction(DirectionEnum.DESC); orderBys.add(timeOrder); } if (isSummary == false && dims != null) { for (String dim : dims) { Expression expression = new Expression(); expression.setValue(dim); facets.add(expression); } } analysis.setFacets(facets); if (bookmark.getConfig().getRollUps() != null) { rollups.addAll(bookmark.getConfig().getRollUps()); } List<OrderBy> bookmarkOrderBys = bookmark.getConfig().getOrderBy(); if (orderBys != null && bookmarkOrderBys != null) { for (OrderBy orderBy : bookmarkOrderBys) { if (orderBy.getCol() != null || orderBy.getExpression().getValue() != null) { orderBys.add(orderBy); } } } ProjectAnalysisJobPK analysisJobPK = new ProjectAnalysisJobPK(); analysisJobPK.setProjectId(bookmark.getId().getProjectId()); analysis.setId(analysisJobPK); // Do not define an id to let it temporary List<String> mets = bookmark.getConfig().getAvailableMetrics(); ArrayList<Metric> metrics = new ArrayList<Metric>(); if (isSummary) { if (mets != null) { for (String met : mets) { if (met != null) { Metric metric = api.getMetric(bookmark.getId().getProjectId(), domain.getDomainId(), met, false); if (metric == null) { throw new ApiException("Invalid metric Id " + met); } metric.getAccessRights().clear(); metrics.add(metric); } analysis.setMetricList(metrics); } } analysis.setOptionKeys(new HashMap<String, Object>() { private static final long serialVersionUID = -3511263422949970083L; { put("applyFormat", true); put("computeGrowth", false); } }); } else { analysis.setOrderBy(orderBys); analysis.setRollups(rollups); List<ChosenMetric> choosens = bookmark.getConfig().getChosenMetrics(); if (choosens != null) { for (String met : mets) { for (ChosenMetric choosen : choosens) { if (met.equals(choosen.getId())) { if (choosen.getId() != null && choosen.getId().indexOf("@")==-1) { Metric metric = api.getMetric(bookmark.getId().getProjectId(), domain.getDomainId(), choosen.getId(), false); if (metric == null) { throw new ApiException("Invalid metric Id " + met); } metric.getAccessRights().clear(); metrics.add(metric); } else if (choosen.getId() != null) { Metric metric = new Metric(); metric.setExpression(new Expression().value(choosen.getId())); metric.setDynamic(false); metrics.add(metric); } else if (choosen.getExpression() != null) { Metric metric = new Metric(); metric.setExpression(choosen.getExpression()); metric.setDynamic(false); metrics.add(metric); } } break; } } analysis.setMetricList(metrics); } } return analysis; } return null; } }
Do not break, it adds only one metric
src/main/java/io/bouquet/v4/client/ClientEngine.java
Do not break, it adds only one metric
Java
apache-2.0
c0fcc016a2613e44b6b65393b6e178da46a29594
0
palava/palava-media
/** * palava - a java-php-bridge * Copyright (C) 2007-2010 CosmoCode GmbH * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package de.cosmocode.palava.media; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import javax.persistence.*; import com.google.common.base.Function; import com.google.common.collect.Iterators; import com.google.common.collect.Maps; import de.cosmocode.commons.TrimMode; import de.cosmocode.json.JSONRenderer; import de.cosmocode.json.RenderLevel; import de.cosmocode.palava.model.base.AbstractEntity; /** * Abstract base implementation of the {@link AssetBase} interface * which uses {@link AssetMetaData} to provide JPA compliant * mapping functionality. * * @author Willi Schoenborn */ @MappedSuperclass public abstract class AbstractAsset extends AbstractEntity implements AssetBase { private static final Function<Entry<String, AssetMetaData>, Entry<String, String>> FUNCTION = new Function<Entry<String, AssetMetaData>, Entry<String, String>>() { @Override public Entry<String, String> apply(Entry<String, AssetMetaData> from) { return Maps.immutableEntry(from.getKey(), from.getValue().getValue()); } }; private String name; private String title; // TODO text/mediumtext private String description; @Column(name = "expires_at") @Temporal(TemporalType.TIMESTAMP) private Date expiresAt; @OneToMany(fetch = FetchType.LAZY, mappedBy = "asset") @MapKey(name = "key") private Map<String, AssetMetaData> metaData = Maps.newHashMap(); // hidden adapter for metaData @Transient private final transient Map<String, String> adapter = new MetaDataAdapter(); /** * A map adapter for {@link AbstractAsset#metaData} which translates * from String to {@link AssetMetaData} and vice versa. * * @author Willi Schoenborn */ private class MetaDataAdapter extends AbstractMap<String, String> { @Override public Set<Entry<String, String>> entrySet() { return new AbstractSet<Entry<String, String>>() { @Override public Iterator<Entry<String, String>> iterator() { return Iterators.transform(metaData.entrySet().iterator(), FUNCTION); } @Override public int size() { return metaData.size(); } }; } @Override public String put(String key, String value) { final AssetMetaData old = metaData.get(key); if (old == null) { final AssetMetaData data = new AssetMetaData(AbstractAsset.this, key, value); metaData.put(key, data); return null; } else { final String oldValue = old.getValue(); old.setValue(value); return oldValue; } } }; @Override public String getName() { return name; } @Override public void setName(String name) { this.name = TrimMode.NULL.apply(name); } @Override public String getTitle() { return title; } @Override public void setTitle(String title) { this.title = TrimMode.NULL.apply(title); } @Override public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = TrimMode.NULL.apply(description); } @Override public Date getExpiresAt() { return expiresAt; } @Override public void setExpiresAt(Date expiresAt) { this.expiresAt = expiresAt; } @Override public boolean isExpirable() { return getExpiresAt() != null; } @Override public boolean isExpired() { return isExpirable() && getExpiresAt().getTime() < System.currentTimeMillis(); } @Override public Map<String, String> getMetaData() { return adapter; } @Override public JSONRenderer renderAsMap(JSONRenderer renderer) { super.renderAsMap(renderer); if (renderer.eq(RenderLevel.TINY)) { renderer. key("name").value(getName()). key("title").value(getTitle()); } if (renderer.eq(RenderLevel.MEDIUM)) { renderer. key("description").value(getDescription()). key("expiresAt").value(getExpiresAt()). key("isExpirable").value(isExpirable()). key("isExpired").value(isExpired()); } if (renderer.eq(RenderLevel.LONG)) { renderer. key("metaData").object(getMetaData()); } return renderer; } }
src/main/java/de/cosmocode/palava/media/AbstractAsset.java
/** * palava - a java-php-bridge * Copyright (C) 2007-2010 CosmoCode GmbH * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package de.cosmocode.palava.media; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import javax.persistence.*; import com.google.common.base.Function; import com.google.common.collect.Iterators; import com.google.common.collect.Maps; import de.cosmocode.commons.TrimMode; import de.cosmocode.json.JSONRenderer; import de.cosmocode.json.RenderLevel; import de.cosmocode.palava.model.base.AbstractEntity; /** * Abstract base implementation of the {@link AssetBase} interface * which uses {@link AssetMetaData} to provide JPA compliant * mapping functionality. * * @author Willi Schoenborn */ @MappedSuperclass public abstract class AbstractAsset extends AbstractEntity implements AssetBase { private static final Function<Entry<String, AssetMetaData>, Entry<String, String>> FUNCTION = new Function<Entry<String, AssetMetaData>, Entry<String, String>>() { @Override public Entry<String, String> apply(Entry<String, AssetMetaData> from) { return Maps.immutableEntry(from.getKey(), from.getValue().getValue()); } }; private String name; private String title; // TODO text/mediumtext private String description; @Column(name = "expires_at") private Date expiresAt; @OneToMany(fetch = FetchType.LAZY, mappedBy = "asset") @MapKey(name = "key") private Map<String, AssetMetaData> metaData = Maps.newHashMap(); // hidden adapter for metaData @Transient private final transient Map<String, String> adapter = new MetaDataAdapter(); /** * A map adapter for {@link AbstractAsset#metaData} which translates * from String to {@link AssetMetaData} and vice versa. * * @author Willi Schoenborn */ private class MetaDataAdapter extends AbstractMap<String, String> { @Override public Set<Entry<String, String>> entrySet() { return new AbstractSet<Entry<String, String>>() { @Override public Iterator<Entry<String, String>> iterator() { return Iterators.transform(metaData.entrySet().iterator(), FUNCTION); } @Override public int size() { return metaData.size(); } }; } @Override public String put(String key, String value) { final AssetMetaData old = metaData.get(key); if (old == null) { final AssetMetaData data = new AssetMetaData(AbstractAsset.this, key, value); metaData.put(key, data); return null; } else { final String oldValue = old.getValue(); old.setValue(value); return oldValue; } } }; @Override public String getName() { return name; } @Override public void setName(String name) { this.name = TrimMode.NULL.apply(name); } @Override public String getTitle() { return title; } @Override public void setTitle(String title) { this.title = TrimMode.NULL.apply(title); } @Override public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = TrimMode.NULL.apply(description); } @Override public Date getExpiresAt() { return expiresAt; } @Override public void setExpiresAt(Date expiresAt) { this.expiresAt = expiresAt; } @Override public boolean isExpirable() { return getExpiresAt() != null; } @Override public boolean isExpired() { return isExpirable() && getExpiresAt().getTime() < System.currentTimeMillis(); } @Override public Map<String, String> getMetaData() { return adapter; } @Override public JSONRenderer renderAsMap(JSONRenderer renderer) { super.renderAsMap(renderer); if (renderer.eq(RenderLevel.TINY)) { renderer. key("name").value(getName()). key("title").value(getTitle()); } if (renderer.eq(RenderLevel.MEDIUM)) { renderer. key("description").value(getDescription()). key("expiresAt").value(getExpiresAt()). key("isExpirable").value(isExpirable()). key("isExpired").value(isExpired()); } if (renderer.eq(RenderLevel.LONG)) { renderer. key("metaData").object(getMetaData()); } return renderer; } }
added @Temporal(TemporalType.TIMESTAMP) to date fields
src/main/java/de/cosmocode/palava/media/AbstractAsset.java
added @Temporal(TemporalType.TIMESTAMP) to date fields
Java
apache-2.0
4877d996b3f47387ef71f1d2c394d19af7bacaf4
0
agwlvssainokuni/springapp,agwlvssainokuni/springapp,agwlvssainokuni/springapp,agwlvssainokuni/springapp
/* * Copyright 2014 agwlvssainokuni * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cherry.spring.common.helper.async; import static com.google.common.base.Preconditions.checkState; import static com.mysema.query.types.expr.DateTimeExpression.currentTimestamp; import static org.springframework.transaction.annotation.Propagation.REQUIRES_NEW; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.joda.time.LocalDateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jdbc.query.QueryDslJdbcOperations; import org.springframework.data.jdbc.query.SqlInsertCallback; import org.springframework.data.jdbc.query.SqlUpdateCallback; import org.springframework.transaction.annotation.Transactional; import cherry.foundation.async.AsyncProcessStore; import cherry.foundation.async.AsyncStatus; import cherry.foundation.async.FileProcessResult; import cherry.foundation.async.FileRecordInfo; import cherry.foundation.type.DeletedFlag; import cherry.goods.command.CommandResult; import cherry.goods.util.ToMapUtil; import cherry.spring.common.db.gen.query.QAsyncProcess; import cherry.spring.common.db.gen.query.QAsyncProcessCommand; import cherry.spring.common.db.gen.query.QAsyncProcessCommandArg; import cherry.spring.common.db.gen.query.QAsyncProcessCommandResult; import cherry.spring.common.db.gen.query.QAsyncProcessException; import cherry.spring.common.db.gen.query.QAsyncProcessFile; import cherry.spring.common.db.gen.query.QAsyncProcessFileArg; import cherry.spring.common.db.gen.query.QAsyncProcessFileResult; import cherry.spring.common.db.gen.query.QAsyncProcessFileResultDetail; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mysema.query.sql.dml.SQLInsertClause; import com.mysema.query.sql.dml.SQLUpdateClause; public class AsyncProcessStoreImpl implements AsyncProcessStore { @Autowired private QueryDslJdbcOperations queryDslJdbcOperations; @Autowired private ObjectMapper objectMapper; @Transactional(value = "jtaTransactionManager", propagation = REQUIRES_NEW) @Override public long createFileProcess(String launcherId, LocalDateTime dtm, final String description, final String name, final String originalFilename, final String contentType, final long size, final String handlerName, String... args) { final long asyncId = createAsyncProcess(launcherId, description, "FIL", dtm); final QAsyncProcessFile a = new QAsyncProcessFile("a"); queryDslJdbcOperations.insert(a, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(a.asyncId, asyncId); insert.set(a.paramName, name); insert.set(a.originalFilename, originalFilename); insert.set(a.contentType, contentType); insert.set(a.fileSize, size); insert.set(a.handlerName, handlerName); Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcessFile: asyncId={0}, paramName={1}, originalFilename={2}, contentType={3}, fileSize={4}, handlerName={5}", asyncId, name, originalFilename, contentType, size, handlerName); return id.longValue(); } }); final QAsyncProcessFileArg b = new QAsyncProcessFileArg("b"); for (final String arg : args) { queryDslJdbcOperations.insert(b, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(b.asyncId, asyncId); insert.set(b.argument, arg); Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcessFileArg: asyncId={0}, arg={1}", asyncId, arg); return id.longValue(); } }); } return asyncId; } @Transactional(value = "jtaTransactionManager", propagation = REQUIRES_NEW) public long createCommand(String launcherId, LocalDateTime dtm, final String description, final String command, String... args) { final long asyncId = createAsyncProcess(launcherId, description, "CMD", dtm); final QAsyncProcessCommand a = new QAsyncProcessCommand("a"); queryDslJdbcOperations.insert(a, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(a.asyncId, asyncId); insert.set(a.command, command); Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcessCommand: asyncId={0}, command={1}", asyncId, command); return id.longValue(); } }); final QAsyncProcessCommandArg b = new QAsyncProcessCommandArg("b"); for (final String arg : args) { queryDslJdbcOperations.insert(b, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(b.asyncId, asyncId); insert.set(b.argument, arg); Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcessCommandArg: asyncId={0}, arg={1}", asyncId, arg); return id.longValue(); } }); } return asyncId; } @Transactional("jtaTransactionManager") public void updateToLaunched(final long asyncId, final LocalDateTime dtm) { final QAsyncProcess a = new QAsyncProcess("a"); long count = queryDslJdbcOperations.update(a, new SqlUpdateCallback() { @Override public long doInSqlUpdateClause(SQLUpdateClause update) { update.set(a.asyncStatus, AsyncStatus.LAUNCHED.code()); update.set(a.launchedAt, dtm); update.set(a.updatedAt, currentTimestamp(LocalDateTime.class)); update.set(a.lockVersion, a.lockVersion.add(1)); update.where(a.id.eq(asyncId)); update.where(a.deletedFlg.eq(DeletedFlag.NOT_DELETED.code())); return update.execute(); } }); checkState( count == 1, "failed to update QAsyncProcess: id={0}, asyncStatus={1}, launchedAt={2}, count={3}", asyncId, AsyncStatus.LAUNCHED.code(), dtm, count); } @Transactional(propagation = REQUIRES_NEW) @Override public void updateToProcessing(final long asyncId, final LocalDateTime dtm) { final QAsyncProcess a = new QAsyncProcess("a"); long count = queryDslJdbcOperations.update(a, new SqlUpdateCallback() { @Override public long doInSqlUpdateClause(SQLUpdateClause update) { update.set(a.asyncStatus, AsyncStatus.PROCESSING.code()); update.set(a.startedAt, dtm); update.set(a.updatedAt, currentTimestamp(LocalDateTime.class)); update.set(a.lockVersion, a.lockVersion.add(1)); update.where(a.id.eq(asyncId)); update.where(a.deletedFlg.eq(DeletedFlag.NOT_DELETED.code())); return update.execute(); } }); checkState( count == 1, "failed to update QAsyncProcess: id={0}, asyncStatus={1}, startedAt={2}, count={3}", asyncId, AsyncStatus.PROCESSING.code(), dtm, count); } @Transactional(propagation = REQUIRES_NEW) @Override public void finishFileProcess(final long asyncId, final LocalDateTime dtm, final AsyncStatus status, final FileProcessResult result) { finishAsyncProcess(asyncId, dtm, status); final QAsyncProcessFileResult a = new QAsyncProcessFileResult("a"); queryDslJdbcOperations.insert(a, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(a.asyncId, asyncId); insert.set(a.totalCount, result.getTotalCount()); insert.set(a.okCount, result.getOkCount()); insert.set(a.ngCount, result.getNgCount()); Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcessFileResult: asyncId={0}, totalCount={1}, okCount={2}, ngCount={3}", asyncId, result.getTotalCount(), result.getOkCount(), result.getNgCount()); return id.longValue(); } }); final QAsyncProcessFileResultDetail b = new QAsyncProcessFileResultDetail( "b"); List<FileRecordInfo> list = (result.getNgRecordInfoList() == null ? new ArrayList<FileRecordInfo>() : result.getNgRecordInfoList()); for (final FileRecordInfo r : list) { if (r.isOk()) { continue; } queryDslJdbcOperations.insert(b, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(b.asyncId, asyncId); insert.set(b.recordNumber, r.getNumber()); insert.set(b.description, r.getDescription()); Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcessFileResultDetail: asyncId={0}, recordNumber={1}, description={2}", asyncId, r.getNumber(), r.getDescription()); return id.longValue(); } }); } } @Transactional(propagation = REQUIRES_NEW) @Override public void finishCommand(final long asyncId, final LocalDateTime dtm, final AsyncStatus status, final CommandResult result) { finishAsyncProcess(asyncId, dtm, status); final QAsyncProcessCommandResult a = new QAsyncProcessCommandResult("a"); queryDslJdbcOperations.insert(a, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(a.asyncId, asyncId); insert.set(a.exitValue, result.getExitValue()); insert.set(a.stdout, result.getStdout()); insert.set(a.stderr, result.getStderr()); Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcessCommandResult: asyncId={0}, exitValue={1}, stdout={2}, stderr={3}", asyncId, result.getExitValue(), result.getStdout(), result.getStderr()); return id.longValue(); } }); } @Transactional(propagation = REQUIRES_NEW) @Override public void finishWithException(final long asyncId, final LocalDateTime dtm, final Throwable th) { finishAsyncProcess(asyncId, dtm, AsyncStatus.EXCEPTION); final QAsyncProcessException a = new QAsyncProcessException("a"); queryDslJdbcOperations.insert(a, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(a.asyncId, asyncId); try { Map<String, Object> map = ToMapUtil.fromThrowable(th, Integer.MAX_VALUE); insert.set(a.exception, objectMapper.writeValueAsString(map)); } catch (JsonProcessingException ex) { throw new IllegalStateException(); } Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcessException: asyncId={0}, exception={1}", asyncId, th.getMessage()); return id.longValue(); } }); } private long createAsyncProcess(final String launcherId, final String description, final String asyncType, final LocalDateTime dtm) { final QAsyncProcess a = new QAsyncProcess("a"); return queryDslJdbcOperations.insert(a, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(a.launchedBy, launcherId); insert.set(a.description, description); insert.set(a.asyncType, asyncType); insert.set(a.asyncStatus, AsyncStatus.LAUNCHING.code()); insert.set(a.registeredAt, dtm); Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcess: launchedBy={0}, description={1}, asyncType={2}, asyncStatus={3}, registeredAt={4}", launcherId, description, asyncType, AsyncStatus.LAUNCHING.code(), dtm); return id.longValue(); } }); } private void finishAsyncProcess(final long asyncId, final LocalDateTime dtm, final AsyncStatus status) { final QAsyncProcess a = new QAsyncProcess("a"); long count = queryDslJdbcOperations.update(a, new SqlUpdateCallback() { @Override public long doInSqlUpdateClause(SQLUpdateClause update) { update.set(a.asyncStatus, status.code()); update.set(a.finishedAt, dtm); update.set(a.updatedAt, currentTimestamp(LocalDateTime.class)); update.set(a.lockVersion, a.lockVersion.add(1)); update.where(a.id.eq(asyncId)); update.where(a.deletedFlg.eq(DeletedFlag.NOT_DELETED.code())); return update.execute(); } }); checkState( count == 1, "failed to update QAsyncProcess: id={0}, asyncStatus={1}, finishedAt={2}, count={3}", asyncId, status.code(), dtm, count); } }
common/src/main/java/cherry/spring/common/helper/async/AsyncProcessStoreImpl.java
/* * Copyright 2014 agwlvssainokuni * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cherry.spring.common.helper.async; import static com.google.common.base.Preconditions.checkState; import static com.mysema.query.types.expr.DateTimeExpression.currentTimestamp; import static org.springframework.transaction.annotation.Propagation.REQUIRES_NEW; import java.util.Map; import org.joda.time.LocalDateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jdbc.query.QueryDslJdbcOperations; import org.springframework.data.jdbc.query.SqlInsertCallback; import org.springframework.data.jdbc.query.SqlUpdateCallback; import org.springframework.transaction.annotation.Transactional; import cherry.foundation.async.AsyncProcessStore; import cherry.foundation.async.AsyncStatus; import cherry.foundation.async.FileProcessResult; import cherry.foundation.async.FileRecordInfo; import cherry.foundation.type.DeletedFlag; import cherry.goods.command.CommandResult; import cherry.goods.util.ToMapUtil; import cherry.spring.common.db.gen.query.QAsyncProcess; import cherry.spring.common.db.gen.query.QAsyncProcessCommand; import cherry.spring.common.db.gen.query.QAsyncProcessCommandArg; import cherry.spring.common.db.gen.query.QAsyncProcessCommandResult; import cherry.spring.common.db.gen.query.QAsyncProcessException; import cherry.spring.common.db.gen.query.QAsyncProcessFile; import cherry.spring.common.db.gen.query.QAsyncProcessFileArg; import cherry.spring.common.db.gen.query.QAsyncProcessFileResult; import cherry.spring.common.db.gen.query.QAsyncProcessFileResultDetail; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mysema.query.sql.dml.SQLInsertClause; import com.mysema.query.sql.dml.SQLUpdateClause; public class AsyncProcessStoreImpl implements AsyncProcessStore { @Autowired private QueryDslJdbcOperations queryDslJdbcOperations; @Autowired private ObjectMapper objectMapper; @Transactional(value = "jtaTransactionManager", propagation = REQUIRES_NEW) @Override public long createFileProcess(String launcherId, LocalDateTime dtm, final String description, final String name, final String originalFilename, final String contentType, final long size, final String handlerName, String... args) { final long asyncId = createAsyncProcess(launcherId, description, "FIL", dtm); final QAsyncProcessFile a = new QAsyncProcessFile("a"); queryDslJdbcOperations.insert(a, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(a.asyncId, asyncId); insert.set(a.paramName, name); insert.set(a.originalFilename, originalFilename); insert.set(a.contentType, contentType); insert.set(a.fileSize, size); insert.set(a.handlerName, handlerName); Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcessFile: asyncId={0}, paramName={1}, originalFilename={2}, contentType={3}, fileSize={4}, handlerName={5}", asyncId, name, originalFilename, contentType, size, handlerName); return id.longValue(); } }); final QAsyncProcessFileArg b = new QAsyncProcessFileArg("b"); for (final String arg : args) { queryDslJdbcOperations.insert(b, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(b.asyncId, asyncId); insert.set(b.argument, arg); Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcessFileArg: asyncId={0}, arg={1}", asyncId, arg); return id.longValue(); } }); } return asyncId; } @Transactional(value = "jtaTransactionManager", propagation = REQUIRES_NEW) public long createCommand(String launcherId, LocalDateTime dtm, final String description, final String command, String... args) { final long asyncId = createAsyncProcess(launcherId, description, "CMD", dtm); final QAsyncProcessCommand a = new QAsyncProcessCommand("a"); queryDslJdbcOperations.insert(a, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(a.asyncId, asyncId); insert.set(a.command, command); Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcessCommand: asyncId={0}, command={1}", asyncId, command); return id.longValue(); } }); final QAsyncProcessCommandArg b = new QAsyncProcessCommandArg("b"); for (final String arg : args) { queryDslJdbcOperations.insert(b, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(b.asyncId, asyncId); insert.set(b.argument, arg); Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcessCommandArg: asyncId={0}, arg={1}", asyncId, arg); return id.longValue(); } }); } return asyncId; } @Transactional("jtaTransactionManager") public void updateToLaunched(final long asyncId, final LocalDateTime dtm) { final QAsyncProcess a = new QAsyncProcess("a"); long count = queryDslJdbcOperations.update(a, new SqlUpdateCallback() { @Override public long doInSqlUpdateClause(SQLUpdateClause update) { update.set(a.asyncStatus, AsyncStatus.LAUNCHED.code()); update.set(a.launchedAt, dtm); update.set(a.updatedAt, currentTimestamp(LocalDateTime.class)); update.set(a.lockVersion, a.lockVersion.add(1)); update.where(a.id.eq(asyncId)); update.where(a.deletedFlg.eq(DeletedFlag.NOT_DELETED.code())); return update.execute(); } }); checkState( count == 1, "failed to update QAsyncProcess: id={0}, asyncStatus={1}, launchedAt={2}, count={3}", asyncId, AsyncStatus.LAUNCHED.code(), dtm, count); } @Transactional(propagation = REQUIRES_NEW) @Override public void updateToProcessing(final long asyncId, final LocalDateTime dtm) { final QAsyncProcess a = new QAsyncProcess("a"); long count = queryDslJdbcOperations.update(a, new SqlUpdateCallback() { @Override public long doInSqlUpdateClause(SQLUpdateClause update) { update.set(a.asyncStatus, AsyncStatus.PROCESSING.code()); update.set(a.startedAt, dtm); update.set(a.updatedAt, currentTimestamp(LocalDateTime.class)); update.set(a.lockVersion, a.lockVersion.add(1)); update.where(a.id.eq(asyncId)); update.where(a.deletedFlg.eq(DeletedFlag.NOT_DELETED.code())); return update.execute(); } }); checkState( count == 1, "failed to update QAsyncProcess: id={0}, asyncStatus={1}, startedAt={2}, count={3}", asyncId, AsyncStatus.PROCESSING.code(), dtm, count); } @Transactional(propagation = REQUIRES_NEW) @Override public void finishFileProcess(final long asyncId, final LocalDateTime dtm, final AsyncStatus status, final FileProcessResult result) { finishAsyncProcess(asyncId, dtm, status); final QAsyncProcessFileResult a = new QAsyncProcessFileResult("a"); queryDslJdbcOperations.insert(a, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(a.asyncId, asyncId); insert.set(a.totalCount, result.getTotalCount()); insert.set(a.okCount, result.getOkCount()); insert.set(a.ngCount, result.getNgCount()); Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcessFileResult: asyncId={0}, totalCount={1}, okCount={2}, ngCount={3}", asyncId, result.getTotalCount(), result.getOkCount(), result.getNgCount()); return id.longValue(); } }); final QAsyncProcessFileResultDetail b = new QAsyncProcessFileResultDetail( "b"); for (final FileRecordInfo r : result.getNgRecordInfoList()) { if (r.isOk()) { continue; } queryDslJdbcOperations.insert(b, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(b.asyncId, asyncId); insert.set(b.recordNumber, r.getNumber()); insert.set(b.description, r.getDescription()); Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcessFileResultDetail: asyncId={0}, recordNumber={1}, description={2}", asyncId, r.getNumber(), r.getDescription()); return id.longValue(); } }); } } @Transactional(propagation = REQUIRES_NEW) @Override public void finishCommand(final long asyncId, final LocalDateTime dtm, final AsyncStatus status, final CommandResult result) { finishAsyncProcess(asyncId, dtm, status); final QAsyncProcessCommandResult a = new QAsyncProcessCommandResult("a"); queryDslJdbcOperations.insert(a, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(a.asyncId, asyncId); insert.set(a.exitValue, result.getExitValue()); insert.set(a.stdout, result.getStdout()); insert.set(a.stderr, result.getStderr()); Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcessCommandResult: asyncId={0}, exitValue={1}, stdout={2}, stderr={3}", asyncId, result.getExitValue(), result.getStdout(), result.getStderr()); return id.longValue(); } }); } @Transactional(propagation = REQUIRES_NEW) @Override public void finishWithException(final long asyncId, final LocalDateTime dtm, final Throwable th) { finishAsyncProcess(asyncId, dtm, AsyncStatus.EXCEPTION); final QAsyncProcessException a = new QAsyncProcessException("a"); queryDslJdbcOperations.insert(a, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(a.asyncId, asyncId); try { Map<String, Object> map = ToMapUtil.fromThrowable(th, Integer.MAX_VALUE); insert.set(a.exception, objectMapper.writeValueAsString(map)); } catch (JsonProcessingException ex) { throw new IllegalStateException(); } Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcessException: asyncId={0}, exception={1}", asyncId, th.getMessage()); return id.longValue(); } }); } private long createAsyncProcess(final String launcherId, final String description, final String asyncType, final LocalDateTime dtm) { final QAsyncProcess a = new QAsyncProcess("a"); return queryDslJdbcOperations.insert(a, new SqlInsertCallback() { @Override public long doInSqlInsertClause(SQLInsertClause insert) { insert.set(a.launchedBy, launcherId); insert.set(a.description, description); insert.set(a.asyncType, asyncType); insert.set(a.asyncStatus, AsyncStatus.LAUNCHING.code()); insert.set(a.registeredAt, dtm); Long id = insert.executeWithKey(Long.class); checkState( id != null, "failed to create QAsyncProcess: launchedBy={0}, description={1}, asyncType={2}, asyncStatus={3}, registeredAt={4}", launcherId, description, asyncType, AsyncStatus.LAUNCHING.code(), dtm); return id.longValue(); } }); } private void finishAsyncProcess(final long asyncId, final LocalDateTime dtm, final AsyncStatus status) { final QAsyncProcess a = new QAsyncProcess("a"); long count = queryDslJdbcOperations.update(a, new SqlUpdateCallback() { @Override public long doInSqlUpdateClause(SQLUpdateClause update) { update.set(a.asyncStatus, status.code()); update.set(a.finishedAt, dtm); update.set(a.updatedAt, currentTimestamp(LocalDateTime.class)); update.set(a.lockVersion, a.lockVersion.add(1)); update.where(a.id.eq(asyncId)); update.where(a.deletedFlg.eq(DeletedFlag.NOT_DELETED.code())); return update.execute(); } }); checkState( count == 1, "failed to update QAsyncProcess: id={0}, asyncStatus={1}, finishedAt={2}, count={3}", asyncId, status.code(), dtm, count); } }
SpringApp * 非同期実行フレームワーク。
common/src/main/java/cherry/spring/common/helper/async/AsyncProcessStoreImpl.java
SpringApp * 非同期実行フレームワーク。
Java
apache-2.0
dbe8ffd2888507579d9dcaacd770741c39bcc898
0
mikosik/smooth-build,mikosik/smooth-build
package org.smoothbuild.acceptance.cli.command; import static com.google.common.truth.Truth.assertThat; import static java.lang.String.format; import static java.nio.file.Files.exists; import static org.smoothbuild.acceptance.CommandWithArgs.buildCommand; import static org.smoothbuild.install.ProjectPaths.ARTIFACTS_PATH; import static org.smoothbuild.install.ProjectPaths.TEMPORARY_PATH; import static org.smoothbuild.util.Strings.unlines; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.smoothbuild.acceptance.AcceptanceTestCase; import org.smoothbuild.acceptance.CommandWithArgs; import org.smoothbuild.acceptance.cli.command.common.DefaultModuleTestCase; import org.smoothbuild.acceptance.cli.command.common.LockFileTestCase; import org.smoothbuild.acceptance.cli.command.common.LogLevelOptionTestCase; import org.smoothbuild.acceptance.cli.command.common.ValuesArgTestCase; import org.smoothbuild.acceptance.testing.ReportError; import org.smoothbuild.acceptance.testing.ReportInfo; import org.smoothbuild.acceptance.testing.ReportWarning; import org.smoothbuild.acceptance.testing.ReturnAbc; import org.smoothbuild.acceptance.testing.TempFilePath; import org.smoothbuild.cli.command.BuildCommand; public class BuildCommandTest { @Nested class _basic extends AcceptanceTestCase { @Test public void temp_file_is_deleted_after_build_execution() throws Exception { createNativeJar(TempFilePath.class); createUserModule(format(""" @Native("%s.function") String tempFilePath(); result = tempFilePath(); """, TempFilePath.class.getCanonicalName())); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(new File(artifactFileContentAsString("result")).exists()) .isFalse(); } @Test public void build_command_clears_artifacts_dir() throws Exception { String path = ARTIFACTS_PATH.appendPart("file.txt").toString(); createFile(path, "content"); createUserModule(""" syntactically incorrect script """); runSmoothBuild("result"); assertFinishedWithError(); assertThat(exists(absolutePath(path))) .isFalse(); } @Test public void build_command_clears_temporary_dir() throws Exception { String path = TEMPORARY_PATH.appendPart("file.txt").toString(); createFile(path, "content"); createUserModule(""" syntactically incorrect script """); runSmoothBuild("result"); assertFinishedWithError(); assertThat(exists(absolutePath(path))) .isFalse(); } } @Nested class _default_module extends DefaultModuleTestCase { @Override protected CommandWithArgs commandNameWithArgument() { return buildCommand("result"); } } @Nested class _lock_file extends LockFileTestCase { @Override protected CommandWithArgs commandNameWithArgument() { return buildCommand("result"); } } @Nested class _value_arguments extends ValuesArgTestCase { @Override protected String commandName() { return BuildCommand.NAME; } @Override protected String sectionName() { return "Building"; } } @Nested class _log_level_option extends LogLevelOptionTestCase { @Override protected void whenSmoothCommandWithOption(String option) { runSmooth(buildCommand(option, "result")); } } @Nested class _show_tasks_option { @Nested class basic extends AcceptanceTestCase { @Test public void illegal_value_causes_error() throws IOException { createUserModule(""" result = "abc"; """); runSmooth(buildCommand("--show-tasks=ILLEGAL", "result")); assertFinishedWithError(); assertSysErrContains(unlines( "Invalid value for option '--show-tasks': Unknown matcher 'ILLEGAL'.", "", "Usage:" )); } } @Nested class call_matcher extends AcceptanceTestCase { private static final String DEFINED_FUNCTION_CALL = """ myFunction() = "myLiteral"; result = myFunction(); """; private static final String DEFINED_CALL_TASK_HEADER = """ myFunction() build.smooth:2 group """; private static final String NATIVE_FUNCTION_CALL = """ result = concat(["a"], ["b"]); """; private static final String NATIVE_CALL_TASK_HEADER = """ concat() build.smooth:1 """; private static final String INTERNAL_FUNCTION_CALL = """ result = if(true, "true", "false"); """; private static final String INTERNAL_CALL_TASK_HEADER = """ if() build.smooth:1 """; @Test public void shows_call_when_enabled() throws IOException { createUserModule(DEFINED_FUNCTION_CALL); runSmooth(buildCommand("--show-tasks=call", "result")); assertFinishedWithSuccess(); assertSysOutContains(DEFINED_CALL_TASK_HEADER); } @Test public void hides_calls_when_not_enabled() throws IOException { createUserModule(DEFINED_FUNCTION_CALL); runSmooth(buildCommand("--show-tasks=none", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain(DEFINED_CALL_TASK_HEADER); } @Test public void shows_call_to_native_function_when_enabled() throws IOException { createUserModule(NATIVE_FUNCTION_CALL); runSmooth(buildCommand("--show-tasks=call", "result")); assertFinishedWithSuccess(); assertSysOutContains(NATIVE_CALL_TASK_HEADER); } @Test public void hides_call_to_native_function_when_not_enabled() throws IOException { createUserModule(NATIVE_FUNCTION_CALL); runSmooth(buildCommand("--show-tasks=none", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain(NATIVE_CALL_TASK_HEADER); } @Test public void shows_call_to_internal_if_function_when_enabled() throws IOException { createUserModule(INTERNAL_FUNCTION_CALL); runSmooth(buildCommand("--show-tasks=call", "result")); assertFinishedWithSuccess(); assertSysOutContains(INTERNAL_CALL_TASK_HEADER); } @Test public void shows_call_to_internal_if_function_when_not_enabled() throws IOException { createUserModule(INTERNAL_FUNCTION_CALL); runSmooth(buildCommand("--show-tasks=none", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain(INTERNAL_CALL_TASK_HEADER); } } @Nested class conversion_matcher extends AcceptanceTestCase { private static final String CONVERSION = """ [String] result = []; """; private static final String CONVERSION_TASK_HEADER = """ [String]<-[Nothing] build.smooth:1 """; @Test public void shows_conversion_when_enabled() throws IOException { createUserModule(CONVERSION); runSmooth(buildCommand("--show-tasks=conversion", "result")); assertFinishedWithSuccess(); assertSysOutContains(CONVERSION_TASK_HEADER); } @Test public void hides_conversion_when_not_enabled() throws IOException { createUserModule(CONVERSION); runSmooth(buildCommand("--show-tasks=none", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain(CONVERSION_TASK_HEADER); } } @Nested class field_read_matcher extends AcceptanceTestCase { private static final String FIELD_READ = """ MyStruct { String myField } aStruct = myStruct("abc"); result = aStruct.myField; """; private static final String FIELD_READ_TASK_HEADER = """ .myField build.smooth:5 """; @Test public void shows_field_read_when_enabled() throws IOException { createUserModule(FIELD_READ); runSmooth(buildCommand("--show-tasks=field", "result")); assertFinishedWithSuccess(); assertSysOutContains(FIELD_READ_TASK_HEADER); } @Test public void hides_literals_when_not_enabled() throws IOException { createUserModule(FIELD_READ); runSmooth(buildCommand("--show-tasks=none", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain(FIELD_READ_TASK_HEADER); } } @Nested class literal_matcher extends AcceptanceTestCase { private static final String LITERAL = """ result = "myLiteral"; """; private static final String LITERAL_TASK_HEADER = """ "myLiteral" build.smooth:1 """; @Test public void shows_literals_when_enabled() throws IOException { createUserModule(LITERAL); runSmooth(buildCommand("--show-tasks=literal", "result")); assertFinishedWithSuccess(); assertSysOutContains(LITERAL_TASK_HEADER); } @Test public void hides_literals_when_not_enabled() throws IOException { createUserModule(LITERAL); runSmooth(buildCommand("--show-tasks=none", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain(LITERAL_TASK_HEADER); } } @Nested class value_matcher extends AcceptanceTestCase { private static final String DEFINED_VALUE = """ myValue = "abc"; result = myValue; """; private static final String DEFINED_VALUE_TASK_HEADER = """ myValue build.smooth:2 group """; private static final String NATIVE_VALUE = format(""" @Native("%s.function") String returnAbc; result = returnAbc; """, ReturnAbc.class.getCanonicalName()); private static final String NATIVE_VALUE_TASK_HEADER = """ returnAbc build.smooth:3 """; @Test public void shows_value_when_enabled() throws IOException { createUserModule(DEFINED_VALUE); runSmooth(buildCommand("--show-tasks=value", "result")); assertFinishedWithSuccess(); assertSysOutContains(DEFINED_VALUE_TASK_HEADER); } @Test public void hides_value_when_not_enabled() throws IOException { createUserModule(DEFINED_VALUE); runSmooth(buildCommand("--show-tasks=none", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain(DEFINED_VALUE_TASK_HEADER); } @Test public void shows_native_value_when_enabled() throws IOException { createNativeJar(ReturnAbc.class); createUserModule(NATIVE_VALUE); runSmooth(buildCommand("--show-tasks=value", "result")); assertFinishedWithSuccess(); assertSysOutContains(NATIVE_VALUE_TASK_HEADER); } @Test public void hides_native_value_when_not_enabled() throws IOException { createNativeJar(ReturnAbc.class); createUserModule(NATIVE_VALUE); runSmooth(buildCommand("--show-tasks=none", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain(NATIVE_VALUE_TASK_HEADER); } } } @Nested class _when_log_level_option { @Nested class is_fatal extends AcceptanceTestCase { @Test public void then_error_log_is_not_shown() throws IOException { createNativeJar(ReportError.class); createUserModule(""" Nothing reportError(String message); result = reportError("my-error-message"); """); runSmooth(buildCommand("--log-level=fatal", "result")); assertFinishedWithError(); assertSysOutDoesNotContain("my-error-message"); } @Test public void then_warning_log_is_not_shown() throws IOException { createNativeJar(ReportWarning.class); createUserModule(format(""" @Native("%s.function") String reportWarning(String message); result = reportWarning("my-warning-message"); """, ReportWarning.class.getCanonicalName())); runSmooth(buildCommand("--log-level=fatal", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain("WARNING: my-warning-message"); } @Test public void then_info_log_is_not_shown() throws IOException { createNativeJar(ReportInfo.class); createUserModule(format(""" @Native("%s.function") String reportInfo(String message); result = reportInfo("my-info-message"); """, ReportInfo.class.getCanonicalName())); runSmooth(buildCommand("--log-level=fatal", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain("INFO: my-info-message"); } } @Nested class is_error extends AcceptanceTestCase { @Test public void then_error_log_is_shown() throws IOException { createNativeJar(ReportError.class); createUserModule(format(""" @Native("%s.function") Nothing reportError(String message); result = reportError("my-error-message"); """, ReportError.class.getCanonicalName())); runSmooth(buildCommand("--log-level=error", "result")); assertFinishedWithError(); assertSysOutContains("ERROR: my-error-message"); } @Test public void then_warning_log_is_not_shown() throws IOException { createNativeJar(ReportWarning.class); createUserModule(format(""" @Native("%s.function") String reportWarning(String message); result = reportWarning("my-warning-message"); """, ReportWarning.class.getCanonicalName())); runSmooth(buildCommand("--log-level=error", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain("my-warning-message"); } @Test public void then_info_log_is_not_shown() throws IOException { createNativeJar(ReportInfo.class); createUserModule(format(""" @Native("%s.function") String reportInfo(String message); result = reportInfo("my-info-message"); """, ReportInfo.class.getCanonicalName())); runSmooth(buildCommand("--log-level=error", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain("my-info-message"); } } @Nested class is_warning extends AcceptanceTestCase { @Test public void then_error_log_is_shown() throws IOException { createNativeJar(ReportError.class); createUserModule(format(""" @Native("%s.function") Nothing reportError(String message); result = reportError("my-error-message"); """, ReportError.class.getCanonicalName())); runSmooth(buildCommand("--log-level=warning", "result")); assertFinishedWithError(); assertSysOutContains("ERROR: my-error-message"); } @Test public void then_warning_log_is_shown() throws IOException { createNativeJar(ReportWarning.class); createUserModule(format(""" @Native("%s.function") String reportWarning(String message); result = reportWarning("my-warning-message"); """, ReportWarning.class.getCanonicalName())); runSmooth(buildCommand("--log-level=warning", "result")); assertFinishedWithSuccess(); assertSysOutContains("WARNING: my-warning-message"); } @Test public void then_info_log_is_not_shown() throws IOException { createNativeJar(ReportInfo.class); createUserModule(format(""" @Native("%s.function") String reportInfo(String message); result = reportInfo("my-info-message"); """, ReportInfo.class.getCanonicalName())); runSmooth(buildCommand("--log-level=warning", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain("my-info-message"); } } @Nested class is_info extends AcceptanceTestCase { @Test public void then_error_log_is_shown() throws IOException { createNativeJar(ReportError.class); createUserModule(format(""" @Native("%s.function") Nothing reportError(String message); result = reportError("my-error-message"); """, ReportError.class.getCanonicalName())); runSmooth(buildCommand("--log-level=info", "result")); assertFinishedWithError(); assertSysOutContains("ERROR: my-error-message"); } @Test public void then_warning_log_is_shown() throws IOException { createNativeJar(ReportWarning.class); createUserModule(format(""" @Native("%s.function") String reportWarning(String message); result = reportWarning("my-warning-message"); """, ReportWarning.class.getCanonicalName())); runSmooth(buildCommand("--log-level=info", "result")); assertFinishedWithSuccess(); assertSysOutContains("WARNING: my-warning-message"); } @Test public void then_info_log_is_shown() throws IOException { createNativeJar(ReportInfo.class); createUserModule(format(""" @Native("%s.function") String reportInfo(String message); result = reportInfo("my-info-message"); """, ReportInfo.class.getCanonicalName())); runSmooth(buildCommand("--log-level=info", "result")); assertFinishedWithSuccess(); assertSysOutContains("INFO: my-info-message"); } } } @Nested class _reported_task_header_for extends AcceptanceTestCase { @Test public void call() throws IOException { createUserModule(""" myFunction() = "abc"; result = myFunction(); """); runSmooth(buildCommand("--show-tasks=all", "result")); assertFinishedWithSuccess(); assertSysOutContains(""" myFunction() build.smooth:2 """); } @Test public void field_read() throws IOException { createUserModule(""" MyStruct { String myField } result = myStruct("abc").myField; """); runSmooth(buildCommand("--show-tasks=all", "result")); assertFinishedWithSuccess(); assertSysOutContains(""" .myField build.smooth:4 """); } @Test public void literal_array() throws IOException { createUserModule(""" result = [ "abc" ]; """); runSmooth(buildCommand("--show-tasks=all", "result")); assertFinishedWithSuccess(); assertSysOutContains(""" [String] build.smooth:1 """); } @Test public void literal_blob() throws IOException { createUserModule(""" result = 0x0102; """); runSmooth(buildCommand("--show-tasks=all", "result")); assertFinishedWithSuccess(); assertSysOutContains(""" 0x0102 build.smooth:1 """); } @Test public void literal_string() throws IOException { createUserModule(""" result = "abc"; """); runSmooth(buildCommand("--show-tasks=all", "result")); assertFinishedWithSuccess(); assertSysOutContains(""" "abc" build.smooth:1 """); } @Test public void value() throws IOException { createUserModule(""" myValue = "abc"; result = myValue; """); runSmooth(buildCommand("--show-tasks=all", "result")); assertFinishedWithSuccess(); assertSysOutContains(""" myValue build.smooth:2 group """); } } }
src/acceptance/org/smoothbuild/acceptance/cli/command/BuildCommandTest.java
package org.smoothbuild.acceptance.cli.command; import static com.google.common.truth.Truth.assertThat; import static java.lang.String.format; import static java.nio.file.Files.exists; import static org.smoothbuild.acceptance.CommandWithArgs.buildCommand; import static org.smoothbuild.install.ProjectPaths.ARTIFACTS_PATH; import static org.smoothbuild.install.ProjectPaths.TEMPORARY_PATH; import static org.smoothbuild.util.Strings.unlines; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.smoothbuild.acceptance.AcceptanceTestCase; import org.smoothbuild.acceptance.CommandWithArgs; import org.smoothbuild.acceptance.cli.command.common.DefaultModuleTestCase; import org.smoothbuild.acceptance.cli.command.common.LockFileTestCase; import org.smoothbuild.acceptance.cli.command.common.LogLevelOptionTestCase; import org.smoothbuild.acceptance.cli.command.common.ValuesArgTestCase; import org.smoothbuild.acceptance.testing.ReportError; import org.smoothbuild.acceptance.testing.ReportInfo; import org.smoothbuild.acceptance.testing.ReportWarning; import org.smoothbuild.acceptance.testing.ReturnAbc; import org.smoothbuild.acceptance.testing.TempFilePath; import org.smoothbuild.cli.command.BuildCommand; public class BuildCommandTest { @Nested class _basic extends AcceptanceTestCase { @Test public void temp_file_is_deleted_after_build_execution() throws Exception { createNativeJar(TempFilePath.class); createUserModule(format(""" @Native("%s.function") String tempFilePath(); result = tempFilePath(); """, TempFilePath.class.getCanonicalName())); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(new File(artifactFileContentAsString("result")).exists()) .isFalse(); } @Test public void build_command_clears_artifacts_dir() throws Exception { String path = ARTIFACTS_PATH.appendPart("file.txt").toString(); createFile(path, "content"); createUserModule(""" syntactically incorrect script """); runSmoothBuild("result"); assertFinishedWithError(); assertThat(exists(absolutePath(path))) .isFalse(); } @Test public void build_command_clears_temporary_dir() throws Exception { String path = TEMPORARY_PATH.appendPart("file.txt").toString(); createFile(path, "content"); createUserModule(""" syntactically incorrect script """); runSmoothBuild("result"); assertFinishedWithError(); assertThat(exists(absolutePath(path))) .isFalse(); } } @Nested class _default_module extends DefaultModuleTestCase { @Override protected CommandWithArgs commandNameWithArgument() { return buildCommand("result"); } } @Nested class _lock_file extends LockFileTestCase { @Override protected CommandWithArgs commandNameWithArgument() { return buildCommand("result"); } } @Nested class _value_arguments extends ValuesArgTestCase { @Override protected String commandName() { return BuildCommand.NAME; } @Override protected String sectionName() { return "Building"; } } @Nested class _log_level_option extends LogLevelOptionTestCase { @Override protected void whenSmoothCommandWithOption(String option) { runSmooth(buildCommand(option, "result")); } } @Nested class _show_tasks_option { @Nested class basic extends AcceptanceTestCase { @Test public void illegal_value_causes_error() throws IOException { createUserModule(""" result = "abc"; """); runSmooth(buildCommand("--show-tasks=ILLEGAL", "result")); assertFinishedWithError(); assertSysErrContains(unlines( "Invalid value for option '--show-tasks': Unknown matcher 'ILLEGAL'.", "", "Usage:" )); } } @Nested class call_matcher extends AcceptanceTestCase { private static final String DEFINED_FUNCTION_CALL = """ myFunction() = "myLiteral"; result = myFunction(); """; private static final String DEFINED_CALL_TASK_HEADER = """ myFunction() build.smooth:2 group """; private static final String NATIVE_FUNCTION_CALL = """ result = concat(["a"], ["b"]); """; private static final String NATIVE_CALL_TASK_HEADER = """ concat() build.smooth:1 """; private static final String INTERNAL_FUNCTION_CALL = """ result = if(true, "true", "false"); """; private static final String INTERNAL_CALL_TASK_HEADER = """ if() build.smooth:1 """; @Test public void shows_call_when_enabled() throws IOException { createUserModule(DEFINED_FUNCTION_CALL); runSmooth(buildCommand("--show-tasks=call", "result")); assertFinishedWithSuccess(); assertSysOutContains(DEFINED_CALL_TASK_HEADER); } @Test public void hides_calls_when_not_enabled() throws IOException { createUserModule(DEFINED_FUNCTION_CALL); runSmooth(buildCommand("--show-tasks=none", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain(DEFINED_CALL_TASK_HEADER); } @Test public void shows_call_to_native_function_when_enabled() throws IOException { createUserModule(NATIVE_FUNCTION_CALL); runSmooth(buildCommand("--show-tasks=call", "result")); assertFinishedWithSuccess(); assertSysOutContains(NATIVE_CALL_TASK_HEADER); } @Test public void hides_call_to_native_function_when_not_enabled() throws IOException { createUserModule(NATIVE_FUNCTION_CALL); runSmooth(buildCommand("--show-tasks=none", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain(NATIVE_CALL_TASK_HEADER); } @Test public void shows_call_to_internal_if_function_when_enabled() throws IOException { createUserModule(INTERNAL_FUNCTION_CALL); runSmooth(buildCommand("--show-tasks=call", "result")); assertFinishedWithSuccess(); assertSysOutContains(INTERNAL_CALL_TASK_HEADER); } @Test public void shows_call_to_internal_if_function_when_not_enabled() throws IOException { createUserModule(INTERNAL_FUNCTION_CALL); runSmooth(buildCommand("--show-tasks=none", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain(INTERNAL_CALL_TASK_HEADER); } } @Nested class conversion_matcher extends AcceptanceTestCase { private static final String CONVERSION = """ [String] result = []; """; private static final String CONVERSION_TASK_HEADER = """ [String]<-[Nothing] build.smooth:1 """; @Test public void shows_conversion_when_enabled() throws IOException { createUserModule(CONVERSION); runSmooth(buildCommand("--show-tasks=conversion", "result")); assertFinishedWithSuccess(); assertSysOutContains(CONVERSION_TASK_HEADER); } @Test public void hides_conversion_when_not_enabled() throws IOException { createUserModule(CONVERSION); runSmooth(buildCommand("--show-tasks=none", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain(CONVERSION_TASK_HEADER); } } @Nested class field_read_matcher extends AcceptanceTestCase { private static final String FIELD_READ = """ MyStruct { String myField } aStruct = myStruct("abc"); result = aStruct.myField; """; private static final String FIELD_READ_TASK_HEADER = """ .myField build.smooth:5 """; @Test public void shows_field_read_when_enabled() throws IOException { createUserModule(FIELD_READ); runSmooth(buildCommand("--show-tasks=field", "result")); assertFinishedWithSuccess(); assertSysOutContains(FIELD_READ_TASK_HEADER); } @Test public void hides_literals_when_not_enabled() throws IOException { createUserModule(FIELD_READ); runSmooth(buildCommand("--show-tasks=none", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain(FIELD_READ_TASK_HEADER); } } @Nested class literal_matcher extends AcceptanceTestCase { private static final String LITERAL = """ result = "myLiteral"; """; private static final String LITERAL_TASK_HEADER = """ "myLiteral" build.smooth:1 """; @Test public void shows_literals_when_enabled() throws IOException { createUserModule(LITERAL); runSmooth(buildCommand("--show-tasks=literal", "result")); assertFinishedWithSuccess(); assertSysOutContains(LITERAL_TASK_HEADER); } @Test public void hides_literals_when_not_enabled() throws IOException { createUserModule(LITERAL); runSmooth(buildCommand("--show-tasks=none", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain(LITERAL_TASK_HEADER); } } @Nested class value_matcher extends AcceptanceTestCase { private static final String DEFINED_VALUE = """ myValue = "abc"; result = myValue; """; private static final String DEFINED_VALUE_TASK_HEADER = """ myValue build.smooth:2 group """; private static final String NATIVE_VALUE = format(""" @Native("%s.function") String returnAbc; result = returnAbc; """, ReturnAbc.class.getCanonicalName()); private static final String NATIVE_VALUE_TASK_HEADER = """ returnAbc build.smooth:3 """; @Test public void shows_value_when_enabled() throws IOException { createUserModule(DEFINED_VALUE); runSmooth(buildCommand("--show-tasks=value", "result")); assertFinishedWithSuccess(); assertSysOutContains(DEFINED_VALUE_TASK_HEADER); } @Test public void hides_value_when_not_enabled() throws IOException { createUserModule(DEFINED_VALUE); runSmooth(buildCommand("--show-tasks=none", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain(DEFINED_VALUE_TASK_HEADER); } @Test public void shows_native_value_when_enabled() throws IOException { createNativeJar(ReturnAbc.class); createUserModule(NATIVE_VALUE); runSmooth(buildCommand("--show-tasks=value", "result")); assertFinishedWithSuccess(); assertSysOutContains(NATIVE_VALUE_TASK_HEADER); } @Test public void hides_native_value_when_not_enabled() throws IOException { createNativeJar(ReturnAbc.class); createUserModule(NATIVE_VALUE); runSmooth(buildCommand("--show-tasks=none", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain(NATIVE_VALUE_TASK_HEADER); } } } @Nested class _when_log_level_option { @Nested class is_fatal extends AcceptanceTestCase { @Test public void then_error_log_is_not_shown() throws IOException { createNativeJar(ReportError.class); createUserModule(""" Nothing reportError(String message); result = reportError("my-error-message"); """); runSmooth(buildCommand("--log-level=fatal", "result")); assertFinishedWithError(); assertSysOutDoesNotContain("my-error-message"); } @Test public void then_warning_log_is_not_shown() throws IOException { createNativeJar(ReportWarning.class); createUserModule(format(""" @Native("%s.function") String reportWarning(String message); result = reportWarning("my-warning-message"); """, ReportWarning.class.getCanonicalName())); runSmooth(buildCommand("--log-level=fatal", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain("WARNING: my-warning-message"); } @Test public void then_info_log_is_not_shown() throws IOException { createNativeJar(ReportInfo.class); createUserModule(format(""" @Native("%s.function") String reportInfo(String message); result = reportInfo("my-info-message"); """, ReportInfo.class.getCanonicalName())); runSmooth(buildCommand("--log-level=fatal", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain("INFO: my-info-message"); } } @Nested class is_error extends AcceptanceTestCase { @Test public void then_error_log_is_shown() throws IOException { createNativeJar(ReportError.class); createUserModule(format(""" @Native("%s.function") Nothing reportError(String message); result = reportError("my-error-message"); """, ReportError.class.getCanonicalName())); runSmooth(buildCommand("--log-level=error", "result")); assertFinishedWithError(); assertSysOutContains("ERROR: my-error-message"); } @Test public void then_warning_log_is_not_shown() throws IOException { createNativeJar(ReportWarning.class); createUserModule(format(""" @Native("%s.function") String reportWarning(String message); result = reportWarning("my-warning-message"); """, ReportWarning.class.getCanonicalName())); runSmooth(buildCommand("--log-level=error", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain("my-warning-message"); } @Test public void then_info_log_is_not_shown() throws IOException { createNativeJar(ReportInfo.class); createUserModule(format(""" @Native("%s.function") String reportInfo(String message); result = reportInfo("my-info-message"); """, ReportInfo.class.getCanonicalName())); runSmooth(buildCommand("--log-level=error", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain("my-info-message"); } } @Nested class is_warning extends AcceptanceTestCase { @Test public void then_error_log_is_shown() throws IOException { createNativeJar(ReportError.class); createUserModule(format(""" @Native("%s.function") Nothing reportError(String message); result = reportError("my-error-message"); """, ReportError.class.getCanonicalName())); runSmooth(buildCommand("--log-level=warning", "result")); assertFinishedWithError(); assertSysOutContains("ERROR: my-error-message"); } @Test public void then_warning_log_is_shown() throws IOException { createNativeJar(ReportWarning.class); createUserModule(format(""" @Native("%s.function") String reportWarning(String message); result = reportWarning("my-warning-message"); """, ReportWarning.class.getCanonicalName())); runSmooth(buildCommand("--log-level=warning", "result")); assertFinishedWithSuccess(); assertSysOutContains("WARNING: my-warning-message"); } @Test public void then_info_log_is_not_shown() throws IOException { createNativeJar(ReportInfo.class); createUserModule(format(""" @Native("%s.function") String reportInfo(String message); result = reportInfo("my-info-message"); """, ReportInfo.class.getCanonicalName())); runSmooth(buildCommand("--log-level=warning", "result")); assertFinishedWithSuccess(); assertSysOutDoesNotContain("my-info-message"); } } @Nested class is_info extends AcceptanceTestCase { @Test public void then_error_log_is_shown() throws IOException { createNativeJar(ReportError.class); createUserModule(format(""" @Native("%s.function") Nothing reportError(String message); result = reportError("my-error-message"); """, ReportError.class.getCanonicalName())); runSmooth(buildCommand("--log-level=info", "result")); assertFinishedWithError(); assertSysOutContains("ERROR: my-error-message"); } @Test public void then_warning_log_is_shown() throws IOException { createNativeJar(ReportWarning.class); createUserModule(format(""" @Native("%s.function") String reportWarning(String message); result = reportWarning("my-warning-message"); """, ReportWarning.class.getCanonicalName())); runSmooth(buildCommand("--log-level=info", "result")); assertFinishedWithSuccess(); assertSysOutContains("WARNING: my-warning-message"); } @Test public void then_info_log_is_shown() throws IOException { createNativeJar(ReportInfo.class); createUserModule(format(""" @Native("%s.function") String reportInfo(String message); result = reportInfo("my-info-message"); """, ReportInfo.class.getCanonicalName())); runSmooth(buildCommand("--log-level=info", "result")); assertFinishedWithSuccess(); assertSysOutContains("INFO: my-info-message"); } } } }
added BuildCommandTest._reported_task_header_for
src/acceptance/org/smoothbuild/acceptance/cli/command/BuildCommandTest.java
added BuildCommandTest._reported_task_header_for
Java
apache-2.0
ec5308a736224a0c3ad4581c7b59bc8a3629baa5
0
anchela/jackrabbit-oak,anchela/jackrabbit-oak,amit-jain/jackrabbit-oak,trekawek/jackrabbit-oak,anchela/jackrabbit-oak,mreutegg/jackrabbit-oak,anchela/jackrabbit-oak,trekawek/jackrabbit-oak,anchela/jackrabbit-oak,amit-jain/jackrabbit-oak,apache/jackrabbit-oak,amit-jain/jackrabbit-oak,amit-jain/jackrabbit-oak,mreutegg/jackrabbit-oak,amit-jain/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,trekawek/jackrabbit-oak,trekawek/jackrabbit-oak,trekawek/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,apache/jackrabbit-oak
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.plugins.value; import javax.jcr.RepositoryException; import org.apache.jackrabbit.oak.api.Blob; /** * TODO: document */ public interface OakValue { Blob getBlob() throws RepositoryException; /** * Returns the Oak internal String representation of a value. Thus, similar * to {@link javax.jcr.Value#getString()} but ignoring any JCR specific namespace * mapping. * @return A String representation of the value of this property. */ String getOakString() throws RepositoryException; }
oak-store-spi/src/main/java/org/apache/jackrabbit/oak/plugins/value/OakValue.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.plugins.value; import javax.jcr.RepositoryException; import org.apache.jackrabbit.oak.api.Blob; /** * TODO: document */ public interface OakValue { Blob getBlob() throws RepositoryException; /** * Same as {@link #getString()} unless that names and paths are returned in their * Oak representation instead of being mapped to their JCR representation. * @return A String representation of the value of this property. */ String getOakString() throws RepositoryException; }
OAK-6150: Javadoc plugin fails on Java 8 (fixing OakValue) git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1793657 13f79535-47bb-0310-9956-ffa450edef68
oak-store-spi/src/main/java/org/apache/jackrabbit/oak/plugins/value/OakValue.java
OAK-6150: Javadoc plugin fails on Java 8 (fixing OakValue)
Java
apache-2.0
5f30b48f0f2bd8c7402193fb89d3bfd055d7f29e
0
rpuch/superfly,payneteasy/superfly,payneteasy/superfly,rpuch/superfly,rpuch/superfly,rpuch/superfly,payneteasy/superfly,payneteasy/superfly
package com.payneteasy.superfly.service.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import org.springframework.transaction.annotation.Transactional; import com.payneteasy.superfly.api.ActionDescription; import com.payneteasy.superfly.api.SSOAction; import com.payneteasy.superfly.api.SSORole; import com.payneteasy.superfly.api.SSOUser; import com.payneteasy.superfly.api.SSOUserWithActions; import com.payneteasy.superfly.dao.ActionDao; import com.payneteasy.superfly.dao.UserDao; import com.payneteasy.superfly.model.ActionToSave; import com.payneteasy.superfly.model.AuthAction; import com.payneteasy.superfly.model.AuthRole; import com.payneteasy.superfly.model.RegisterUser; import com.payneteasy.superfly.model.UserWithActions; import com.payneteasy.superfly.service.InternalSSOService; @Transactional public class InternalSSOServiceImpl implements InternalSSOService { private static final Logger logger = LoggerFactory .getLogger(InternalSSOServiceImpl.class); private UserDao userDao; private ActionDao actionDao; @Required public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Required public void setActionDao(ActionDao actionDao) { this.actionDao = actionDao; } public SSOUser authenticate(String username, String password, String subsystemIdentifier, String userIpAddress, String sessionInfo) { SSOUser ssoUser; List<AuthRole> authRoles = userDao.authenticate(username, password, subsystemIdentifier, userIpAddress, sessionInfo); if (authRoles != null && !authRoles.isEmpty()) { Map<SSORole, SSOAction[]> actionsMap = new HashMap<SSORole, SSOAction[]>( authRoles.size()); for (AuthRole authRole : authRoles) { SSORole ssoRole = new SSORole(authRole.getRoleName()); SSOAction[] actions = convertToSSOActions(authRole.getActions()); actionsMap.put(ssoRole, actions); } Map<String, String> preferences = Collections.emptyMap(); ssoUser = new SSOUser(username, actionsMap, preferences); ssoUser.setSessionId(String .valueOf(authRoles.get(0).getSessionId())); } else { ssoUser = null; } return ssoUser; } protected SSOAction[] convertToSSOActions(List<AuthAction> authActions) { SSOAction[] actions = new SSOAction[authActions.size()]; for (int i = 0; i < authActions.size(); i++) { AuthAction authAction = authActions.get(i); SSOAction ssoAction = new SSOAction(authAction.getActionName(), authAction.isLogAction()); actions[i] = ssoAction; } return actions; } public void saveSystemData(String subsystemIdentifier, ActionDescription[] actionDescriptions) { List<ActionToSave> actions = convertActionDescriptions(actionDescriptions); actionDao.saveActions(subsystemIdentifier, actions); if (logger.isDebugEnabled()) { logger.debug("Saved actions for subsystem " + subsystemIdentifier + ": " + actions.size()); logger.debug("Actions are: " + Arrays.asList(actionDescriptions)); } } private List<ActionToSave> convertActionDescriptions( ActionDescription[] actionDescriptions) { List<ActionToSave> actions = new ArrayList<ActionToSave>( actionDescriptions.length); for (ActionDescription description : actionDescriptions) { ActionToSave action = new ActionToSave(); action.setName(description.getName()); action.setDescription(description.getDescription()); actions.add(action); } return actions; } public List<SSOUserWithActions> getUsersWithActions( String subsystemIdentifier, String principalName) { List<UserWithActions> users = userDao.getUsersAndActions( subsystemIdentifier, principalName); List<SSOUserWithActions> result = new ArrayList<SSOUserWithActions>( users.size()); for (UserWithActions user : users) { result.add(convertToSSOUser(user)); } return result; } public void registerUser(String username, String password, String email, long subsystemId, String principalName) { RegisterUser registerUser = new RegisterUser(); registerUser.setUsername(username); registerUser.setEmail(email); registerUser.setPassword(password); registerUser.setPrincipalName(principalName); registerUser.setSubsystemId(subsystemId); userDao.registerUser(registerUser); } protected SSOUserWithActions convertToSSOUser(UserWithActions user) { return new SSOUserWithActions(user.getUsername(), user.getEmail(), convertToSSOActions(user.getActions())); } }
superfly-service/src/main/java/com/payneteasy/superfly/service/impl/InternalSSOServiceImpl.java
package com.payneteasy.superfly.service.impl; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import org.springframework.transaction.annotation.Transactional; import com.payneteasy.superfly.api.ActionDescription; import com.payneteasy.superfly.api.SSOAction; import com.payneteasy.superfly.api.SSORole; import com.payneteasy.superfly.api.SSOUser; import com.payneteasy.superfly.api.SSOUserWithActions; import com.payneteasy.superfly.dao.ActionDao; import com.payneteasy.superfly.dao.UserDao; import com.payneteasy.superfly.model.ActionToSave; import com.payneteasy.superfly.model.AuthAction; import com.payneteasy.superfly.model.AuthRole; import com.payneteasy.superfly.model.RegisterUser; import com.payneteasy.superfly.model.UserWithActions; import com.payneteasy.superfly.service.InternalSSOService; @Transactional public class InternalSSOServiceImpl implements InternalSSOService { private static final Logger logger = LoggerFactory .getLogger(InternalSSOServiceImpl.class); private UserDao userDao; private ActionDao actionDao; @Required public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Required public void setActionDao(ActionDao actionDao) { this.actionDao = actionDao; } public SSOUser authenticate(String username, String password, String subsystemIdentifier, String userIpAddress, String sessionInfo) { SSOUser ssoUser; List<AuthRole> authRoles = userDao.authenticate(username, password, subsystemIdentifier, userIpAddress, sessionInfo); if (authRoles != null && !authRoles.isEmpty()) { Map<SSORole, SSOAction[]> actionsMap = new HashMap<SSORole, SSOAction[]>( authRoles.size()); for (AuthRole authRole : authRoles) { SSORole ssoRole = new SSORole(authRole.getRoleName()); SSOAction[] actions = convertToSSOActions(authRole.getActions()); actionsMap.put(ssoRole, actions); } Map<String, String> preferences = Collections.emptyMap(); ssoUser = new SSOUser(username, actionsMap, preferences); ssoUser.setSessionId(String .valueOf(authRoles.get(0).getSessionId())); } else { ssoUser = null; } return ssoUser; } protected SSOAction[] convertToSSOActions(List<AuthAction> authActions) { SSOAction[] actions = new SSOAction[authActions.size()]; for (int i = 0; i < authActions.size(); i++) { AuthAction authAction = authActions.get(i); SSOAction ssoAction = new SSOAction(authAction.getActionName(), authAction.isLogAction()); actions[i] = ssoAction; } return actions; } public void saveSystemData(String subsystemIdentifier, ActionDescription[] actionDescriptions) { List<ActionToSave> actions = convertActionDescriptions(actionDescriptions); actionDao.saveActions(subsystemIdentifier, actions); logger.debug("Saved actions for subsystem " + subsystemIdentifier + ": " + actions.size()); } private List<ActionToSave> convertActionDescriptions( ActionDescription[] actionDescriptions) { List<ActionToSave> actions = new ArrayList<ActionToSave>( actionDescriptions.length); for (ActionDescription description : actionDescriptions) { ActionToSave action = new ActionToSave(); action.setName(description.getName()); action.setDescription(description.getDescription()); actions.add(action); } return actions; } public List<SSOUserWithActions> getUsersWithActions( String subsystemIdentifier, String principalName) { List<UserWithActions> users = userDao.getUsersAndActions( subsystemIdentifier, principalName); List<SSOUserWithActions> result = new ArrayList<SSOUserWithActions>( users.size()); for (UserWithActions user : users) { result.add(convertToSSOUser(user)); } return result; } public void registerUser(String username, String password, String email, long subsystemId, String principalName) { RegisterUser registerUser = new RegisterUser(); registerUser.setUsername(username); registerUser.setEmail(email); registerUser.setPassword(password); registerUser.setPrincipalName(principalName); registerUser.setSubsystemId(subsystemId); userDao.registerUser(registerUser); } protected SSOUserWithActions convertToSSOUser(UserWithActions user) { return new SSOUserWithActions(user.getUsername(), user.getEmail(), convertToSSOActions(user.getActions())); } }
More logging (dumping actions which were sent by subsystem git-svn-id: 638359b6fa53408d39dd6e7322cef4747caf6c31@462 11a29e22-99e0-9bb7-d19e-9a0993c63ea3
superfly-service/src/main/java/com/payneteasy/superfly/service/impl/InternalSSOServiceImpl.java
More logging (dumping actions which were sent by subsystem
Java
apache-2.0
67ac37dee15aa62b39bb97ee3bffc70be410a177
0
apache/groovy,apache/groovy,apache/groovy,paulk-asert/groovy,apache/incubator-groovy,paulk-asert/groovy,apache/incubator-groovy,paulk-asert/groovy,apache/groovy,apache/incubator-groovy,apache/incubator-groovy,paulk-asert/groovy
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.groovy.util.concurrent; import java.util.EnumSet; /** * This is a basic implementation of a map able to forget its keys could be weak/soft/strong references. This * bases on {@link ConcurrentReferenceHashMap}, thus it is safe for concurrency. * This map compares keys through references. * * @param <K> the key type * @param <V> the value type * @since 4.0.0 */ public class ManagedIdentityConcurrentMap<K, V> extends ConcurrentReferenceHashMap<K, V> { private static final long serialVersionUID = 1046734443288902802L; /** * Creates a new, empty map with the key weak reference */ public ManagedIdentityConcurrentMap() { this(ReferenceType.WEAK); } /** * Creates a new, empty map with the key weak reference and the specified initial capacity * * @param initialCapacity initial capacity */ public ManagedIdentityConcurrentMap(int initialCapacity) { this(ReferenceType.WEAK, initialCapacity); } /** * Creates a new, empty map with the specified key reference type * * @param keyType key reference type */ public ManagedIdentityConcurrentMap(ReferenceType keyType) { super(keyType, ReferenceType.STRONG, EnumSet.of(Option.IDENTITY_COMPARISONS)); } /** * Creates a new, empty map with the specified key reference type and initial capacity * * @param keyType key reference type * @param initialCapacity the initial capacity */ public ManagedIdentityConcurrentMap(ReferenceType keyType, int initialCapacity) { super(initialCapacity, keyType, ReferenceType.STRONG, EnumSet.of(Option.IDENTITY_COMPARISONS)); } /** * Get the key specified value, or put the default value and return it if the key is absent * * @param key the key to look up * @param value the default value if the key is absent * @return the value */ public V getOrPut(K key, V value) { return this.applyIfAbsent(key, k -> value); } }
src/main/java/org/apache/groovy/util/concurrent/ManagedIdentityConcurrentMap.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.groovy.util.concurrent; import java.util.EnumSet; /** * This is a basic implementation of a map able to forget its keys. This * map uses internally a ConcurrentHashMap, thus should be safe for concurrency. * hashcode and equals are used to find the entries and should thus be implemented * properly for the keys. This map does not support null keys. * * @param <K> the key type * @param <V> the value type * @since 4.0.0 */ public class ManagedIdentityConcurrentMap<K, V> extends ConcurrentReferenceHashMap<K, V> { public ManagedIdentityConcurrentMap() { this(ReferenceType.WEAK); } public ManagedIdentityConcurrentMap(int initialCapacity) { this(ReferenceType.WEAK, initialCapacity); } public ManagedIdentityConcurrentMap(ReferenceType keyType) { super(keyType, ReferenceType.STRONG, EnumSet.of(Option.IDENTITY_COMPARISONS)); } public ManagedIdentityConcurrentMap(ReferenceType keyType, int initialCapacity) { super(initialCapacity, keyType, ReferenceType.STRONG, EnumSet.of(Option.IDENTITY_COMPARISONS)); } /** * Get the key specified value, or put the default value and return it if the key is absent * * @param key the key to look up * @param value the default value if the key is absent * @return the value */ public V getOrPut(K key, V value) { return this.applyIfAbsent(key, k -> value); } }
Tweak javadoc for `ManagedIdentityConcurrentMap` and add the missing `serialVersionUID`
src/main/java/org/apache/groovy/util/concurrent/ManagedIdentityConcurrentMap.java
Tweak javadoc for `ManagedIdentityConcurrentMap` and add the missing `serialVersionUID`
Java
bsd-3-clause
3ebd31816db27e1b6c3683785ba551e39434445e
0
spals/oembed4j
package net.spals.oembed4j.client; import net.spals.oembed4j.client.registry.DefaultOEmbedRegistry; import net.spals.oembed4j.client.registry.OEmbedRegistry; import net.spals.oembed4j.model.OEmbedRequest; import net.spals.oembed4j.model.OEmbedResponse; import net.spals.oembed4j.model.OEmbedType; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.net.URI; import java.util.Optional; import static net.spals.oembed4j.client.registry.DefaultOEmbedRegistry.DEFAULT_OEMBED_PROVIDER_URI; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; /** * Unit tests for {@link JerseyOEmbedClient} * * @author tkral */ public class JerseyOEmbedClientTest { private OEmbedClient oEmbedClient; @BeforeClass void classSetup() { final OEmbedRegistry registry = DefaultOEmbedRegistry.loadFromURI(DEFAULT_OEMBED_PROVIDER_URI); this.oEmbedClient = JerseyOEmbedClient.create(registry); } @AfterClass void classTearDown() { this.oEmbedClient.close(); } @DataProvider Object[][] executeProvider() { // Spot check common oEmbed providers return new Object[][] { flickr(), vimeo(), youTube(), }; } @Test(enabled = false, dataProvider = "executeProvider") public void testExecute(final URI resourceURI, final OEmbedResponse expectedResponse) { final OEmbedRequest request = new OEmbedRequest.Builder().setResourceURI(resourceURI).build(); final Optional<OEmbedResponse> response = oEmbedClient.execute(request); assertThat(response, not(Optional.empty())); assertThat(response.get(), is(expectedResponse)); } private Object[] flickr() { final URI uri = URI.create("https://www.flickr.com/photos/lilithis/2207159142/in/photolist" + "-4n3gvY-6i4qpS-oztpWs-74scWq-9XLrR4-qYAD3D-oztstS-e6u5Ej-drMXnV" + "-nXnhrm-9pcCvQ-qJMG4L-bXqvdN-fTMsFJ-aDqw2i-dGpYSH-9yhe1y-dw3Lkk" + "-oztsCu-48pLfd-mbmQ8B-sd77Bo-gu8Wa-8HhZTe-qLVZYW-fZh6UW-7b4y4a" + "-abGk8F-4HauQG-mjuMaD-fZgT9e-avqKos-7c8PDh-fJDXRa-jgG2MB-djzdH3" + "-nNqZfY-bZ2XPu-fZgaN7-broQ6u-92DZ8q-aAZG8X-oKG9Sj-4x7r8n-qJc99b" + "-oQWRV8-4BignY-dxTfvt-84219z-bqLqDp"); final OEmbedResponse expectedResponse = new OEmbedResponse.Builder() .setAuthorName("Lilithis") .setAuthorURI(URI.create("https://www.flickr.com/photos/lilithis/")) .setCacheAge(3600L) .setHeight(500) .setHtml("<a data-flickr-embed=\"true\" href=\"https://www.flickr.com/photos/lilithis/2207159142/\" title=\"Cat by Lilithis, on Flickr\">" + "<img src=\"https://farm3.staticflickr.com/2106/2207159142_8206ab6984.jpg\" width=\"334\" height=\"500\" alt=\"Cat\">" + "</a>" + "<script async src=\"https://embedr.flickr.com/assets/client-code.js\" charset=\"utf-8\">" + "</script>") .setProviderName("Flickr") .setProviderURI(URI.create("https://www.flickr.com/")) .setThumbnailHeight(150) .setThumbnailURI(URI.create("https://farm3.staticflickr.com/2106/2207159142_8206ab6984_q.jpg")) .setThumbnailWidth(150) .setTitle("Cat") .setType(OEmbedType.photo) .setUrl("https://farm3.staticflickr.com/2106/2207159142_8206ab6984.jpg") .setWidth(334) .putCustomProperties("flickr_type", "photo") .putCustomProperties("license", "Attribution-ShareAlike License") .putCustomProperties("license_id", "5") .putCustomProperties("license_url", "https://creativecommons.org/licenses/by-sa/2.0/") .putCustomProperties("web_page", "https://www.flickr.com/photos/lilithis/2207159142/") .putCustomProperties("web_page_short_url", "https://flic.kr/p/4n3gvY") .build(); return new Object[]{uri, expectedResponse}; } private Object[] vimeo() { final URI uri = URI.create("https://vimeo.com/189789787"); final OEmbedResponse expectedResponse = new OEmbedResponse.Builder() .setAuthorName("Uncorked Productions") .setAuthorURI(URI.create("https://vimeo.com/uncorkedprods")) .setHeight(338) .setHtml("<iframe src=\"https://player.vimeo.com/video/189789787\" width=\"640\" height=\"338\" frameborder=\"0\" title=\"Maxine the Fluffy Corgi\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>") .setProviderName("Vimeo") .setProviderURI(URI.create("https://vimeo.com/")) .setThumbnailHeight(337) .setThumbnailURI(URI.create("https://i.vimeocdn.com/video/600355807_640.jpg")) .setThumbnailWidth(640) .setTitle("Maxine the Fluffy Corgi") .setType(OEmbedType.video) .setWidth(640) .putCustomProperties("description", "Short legs. Big city.\n\nhttps://www.instagram.com/madmax_fluffyroad/\n\nmade by: bryan reisberg (& Maxine's owner)\ncamera: owen levelle\nvoice: jon st. john") .putCustomProperties("duration", 34) .putCustomProperties("is_plus", 0) .putCustomProperties("thumbnail_url_with_play_button", "https://i.vimeocdn.com/filter/overlay?src0=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F600355807_640.jpg&src1=http%3A%2F%2Ff.vimeocdn.com%2Fp%2Fimages%2Fcrawler_play.png") .putCustomProperties("upload_date", "2016-11-01 10:40:37") .putCustomProperties("uri", "/videos/189789787") .putCustomProperties("video_id", 189789787) .build(); return new Object[]{uri, expectedResponse}; } private Object[] youTube() { final URI uri = URI.create("https://www.youtube.com/watch?v=qtNI1WbOp5Q"); final OEmbedResponse expectedResponse = new OEmbedResponse.Builder() .setAuthorName("Real Grumpy Cat") .setAuthorURI(URI.create("https://www.youtube.com/user/SevereAvoidance")) .setHeight(270) .setHtml("<iframe width=\"480\" height=\"270\" src=\"https://www.youtube.com/embed/qtNI1WbOp5Q?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe>") .setProviderName("YouTube") .setProviderURI(URI.create("https://www.youtube.com/")) .setThumbnailHeight(360) .setThumbnailURI(URI.create("https://i.ytimg.com/vi/qtNI1WbOp5Q/hqdefault.jpg")) .setThumbnailWidth(480) .setTitle("Grumpy Cat's Worst #IceBucketChallenge Ever!") .setType(OEmbedType.video) .setWidth(480) .build(); return new Object[]{uri, expectedResponse}; } }
client-test/src/test/java/net/spals/oembed4j/client/JerseyOEmbedClientTest.java
package net.spals.oembed4j.client; import net.spals.oembed4j.client.registry.DefaultOEmbedRegistry; import net.spals.oembed4j.client.registry.OEmbedRegistry; import net.spals.oembed4j.model.OEmbedRequest; import net.spals.oembed4j.model.OEmbedResponse; import net.spals.oembed4j.model.OEmbedType; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.net.URI; import java.util.Optional; import static net.spals.oembed4j.client.registry.DefaultOEmbedRegistry.DEFAULT_OEMBED_PROVIDER_URI; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; /** * Unit tests for {@link JerseyOEmbedClient} * * @author tkral */ public class JerseyOEmbedClientTest { private OEmbedClient oEmbedClient; @BeforeClass void classSetup() { final OEmbedRegistry registry = DefaultOEmbedRegistry.loadFromURI(DEFAULT_OEMBED_PROVIDER_URI); this.oEmbedClient = JerseyOEmbedClient.create(registry); } @AfterClass void classTearDown() { this.oEmbedClient.close(); } @DataProvider Object[][] executeProvider() { // final URI vimeoURI = URI.create("https://vimeo.com/189789787"); // final URI youTubeURI = {URI.create("https://www.youtube.com/watch?v=qtNI1WbOp5Q"); // Spot check common oEmbed providers return new Object[][] { flickr(), }; } @Test(enabled = false, dataProvider = "executeProvider") public void testExecute(final URI resourceURI, final OEmbedResponse expectedResponse) { final OEmbedRequest request = new OEmbedRequest.Builder().setResourceURI(resourceURI).build(); final Optional<OEmbedResponse> response = oEmbedClient.execute(request); assertThat(response, not(Optional.empty())); assertThat(response.get(), is(expectedResponse)); } private Object[] flickr() { final URI uri = URI.create("https://www.flickr.com/photos/lilithis/2207159142/in/photolist" + "-4n3gvY-6i4qpS-oztpWs-74scWq-9XLrR4-qYAD3D-oztstS-e6u5Ej-drMXnV" + "-nXnhrm-9pcCvQ-qJMG4L-bXqvdN-fTMsFJ-aDqw2i-dGpYSH-9yhe1y-dw3Lkk" + "-oztsCu-48pLfd-mbmQ8B-sd77Bo-gu8Wa-8HhZTe-qLVZYW-fZh6UW-7b4y4a" + "-abGk8F-4HauQG-mjuMaD-fZgT9e-avqKos-7c8PDh-fJDXRa-jgG2MB-djzdH3" + "-nNqZfY-bZ2XPu-fZgaN7-broQ6u-92DZ8q-aAZG8X-oKG9Sj-4x7r8n-qJc99b" + "-oQWRV8-4BignY-dxTfvt-84219z-bqLqDp"); final OEmbedResponse expectedResponse = new OEmbedResponse.Builder() .setAuthorName("Lilithis") .setAuthorURI(URI.create("https://www.flickr.com/photos/lilithis/")) .setCacheAge(3600L) .setHeight(500) .setHtml("<a data-flickr-embed=\"true\" href=\"https://www.flickr.com/photos/lilithis/2207159142/\" title=\"Cat by Lilithis, on Flickr\">" + "<img src=\"https://farm3.staticflickr.com/2106/2207159142_8206ab6984.jpg\" width=\"334\" height=\"500\" alt=\"Cat\">" + "</a>" + "<script async src=\"https://embedr.flickr.com/assets/client-code.js\" charset=\"utf-8\">" + "</script>") .setProviderName("Flickr") .setProviderURI(URI.create("https://www.flickr.com/")) .setThumbnailHeight(150) .setThumbnailURI(URI.create("https://farm3.staticflickr.com/2106/2207159142_8206ab6984_q.jpg")) .setThumbnailWidth(150) .setTitle("Cat") .setType(OEmbedType.photo) .setUrl("https://farm3.staticflickr.com/2106/2207159142_8206ab6984.jpg") .setWidth(334) .putCustomProperties("flickr_type", "photo") .putCustomProperties("license", "Attribution-ShareAlike License") .putCustomProperties("license_id", "5") .putCustomProperties("license_url", "https://creativecommons.org/licenses/by-sa/2.0/") .putCustomProperties("web_page", "https://www.flickr.com/photos/lilithis/2207159142/") .putCustomProperties("web_page_short_url", "https://flic.kr/p/4n3gvY") .build(); return new Object[]{uri, expectedResponse}; } }
Complete client tests
client-test/src/test/java/net/spals/oembed4j/client/JerseyOEmbedClientTest.java
Complete client tests
Java
bsd-3-clause
102d055c6675206a74fe4e8bdbd23010536a8b87
0
svn2github/xstream,svn2github/xstream
/* * Copyright (C) 2009 XStream Committers. * All rights reserved. * * Created on 20. August 2009 by Joerg Schaible */ package com.thoughtworks.xstream.io.json; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.core.util.FastStack; import com.thoughtworks.xstream.io.AbstractWriter; import com.thoughtworks.xstream.io.naming.NameCoder; import com.thoughtworks.xstream.io.naming.NoNameCoder; /** * An abstract implementation of a writer that calls abstract methods to build JSON structures. * Note, that XStream's implicit collection feature is not compatible with any kind of JSON * syntax. * * @author J&ouml;rg Schaible * @since upcoming */ public abstract class AbstractJsonWriter extends AbstractWriter { /** * DROP_ROOT_MODE drops the JSON root node. * <p> * The root node is the first level of the JSON object i.e. * * <pre> * { &quot;person&quot;: { * &quot;name&quot;: &quot;Joe&quot; * }} * </pre> * * will be written without root simply as * * <pre> * { * &quot;name&quot;: &quot;Joe&quot; * } * </pre> * * Without a root node, the top level element might now also be an array. However, it is * possible to generate invalid JSON unless {@link #STRICT_MODE} is also set. * </p> * * @since 1.3.1 */ public static final int DROP_ROOT_MODE = 1; /** * STRICT_MODE prevents invalid JSON for single value objects when dropping the root. * <p> * The mode is only useful in combination with the {@link #DROP_ROOT_MODE}. An object with a * single value as first node i.e. * * <pre> * { &quot;name&quot;: &quot;Joe&quot; } * </pre> * * is simply written as * * <pre> * &quot;Joe&quot; * </pre> * * However, this is no longer valid JSON. Therefore you can activate {@link #STRICT_MODE} * and a {@link ConversionException} is thrown instead. * </p> * * @since 1.3.1 */ public static final int STRICT_MODE = 2; // TODO: Javadoc public static final int EXPLICIT_MODE = 4; public static class Type { public static Type STRING = new Type(); public static Type NUMBER = new Type(); public static Type BOOLEAN = new Type(); } private static class Status { public final static Status OBJECT = new Status("object"); public final static Status PROPERTY = new Status("property"); public final static Status VALUE = new Status("value"); public final static Status END = new Status("end"); public final static Status ARRAY = new Status("array"); public final static Status ELEMENT = new Status("element"); public final static Status VIRTUAL = new Status("virtual"); private final String name; private Status(String name) { this.name = name; } public String toString() { return name; } } private static final List<Class> NUMBER_TYPES = Arrays.asList(new Class[]{ byte.class, Byte.class, short.class, Short.class, int.class, Integer.class, long.class, Long.class, float.class, Float.class, double.class, Double.class}); private int mode; private FastStack statusStack = new FastStack(32); private FastStack typeStack = new FastStack(16); /** * Construct a JSON writer. * * @since upcoming */ public AbstractJsonWriter() { this(new NoNameCoder()); } /** * Construct a JSON writer with a special mode. * * @param mode a bit mask of the mode constants * @since upcoming */ public AbstractJsonWriter(int mode) { this(mode, new NoNameCoder()); } /** * Construct a JSON writer with a special name coder. * * @param nameCoder the name coder to use * @since upcoming */ public AbstractJsonWriter(NameCoder nameCoder) { this(0, nameCoder); } /** * Construct a JSON writer with a special mode and name coder. * * @param mode a bit mask of the mode constants * @param nameCoder the name coder to use * @since upcoming */ public AbstractJsonWriter(int mode, NameCoder nameCoder) { super(nameCoder); this.mode = mode; } /** * {@inheritDoc} */ public void startNode(String name, Class clazz) { if (statusStack.size() == 0) { statusStack.push(Status.OBJECT); if ((mode & DROP_ROOT_MODE) == 0) { startObject(name); } } else { Class type = (Class)typeStack.peek(); Status status = (Status)statusStack.peek(); if (isArray(type)) { if (status == Status.OBJECT || status == Status.VIRTUAL || status == Status.PROPERTY || status == Status.VALUE) { if (status == Status.PROPERTY || status == Status.VIRTUAL) { nextElement(); addLabel("$"); } if (status == Status.VALUE) { statusStack.replaceSilently(Status.ARRAY); } else { statusStack.replaceSilently(Status.ARRAY); } startArray(); statusStack.push(Status.OBJECT); if ((mode & EXPLICIT_MODE) != 0) { startObject(name); } } else if (status == Status.END) { if ((mode & EXPLICIT_MODE) != 0) { endObject(); } statusStack.popSilently(); status = (Status)statusStack.peek(); if (status == Status.ARRAY) { statusStack.replaceSilently(Status.ELEMENT); } else if (status != Status.ELEMENT) { throw new IllegalStateException("Cannot add new array element"); } nextElement(); statusStack.push(Status.OBJECT); if ((mode & EXPLICIT_MODE) != 0) { startObject(name); } } else { throw new IllegalStateException("Cannot start new array element"); } } else if (status == Status.VALUE) { statusStack.replaceSilently(Status.OBJECT); startObject(name); } else if (status == Status.PROPERTY || status == Status.END || status == Status.VIRTUAL) { statusStack.replaceSilently(Status.PROPERTY); nextElement(); addLabel(name); } else { throw new IllegalStateException("Cannot start new element"); } } statusStack.push(Status.VALUE); typeStack.push(clazz == null ? String.class : clazz); } /** * {@inheritDoc} */ public void startNode(String name) { startNode(name, String.class); } /** * {@inheritDoc} */ public void addAttribute(String name, String value) { Class type = (Class)typeStack.peek(); if ((mode & EXPLICIT_MODE) != 0 || !isArray(type)) { Status status = (Status)statusStack.peek(); if (status == Status.VALUE) { statusStack.replaceSilently(Status.VIRTUAL); startObject("@" + name); } else if (status == Status.PROPERTY || status == Status.VIRTUAL) { nextElement(); addLabel("@" + name); } else { throw new IllegalStateException("Cannot add attribute"); } addValue(value, Type.STRING); } } /** * {@inheritDoc} */ public void setValue(String text) { Status status = (Status)statusStack.peek(); Class type = (Class)typeStack.peek(); if (status == Status.PROPERTY || status == Status.VIRTUAL) { nextElement(); addLabel("$"); statusStack.replaceSilently(Status.END); } else if (status == Status.VALUE) { statusStack.popSilently(); typeStack.popSilently(); if ((mode & STRICT_MODE) != 0 && typeStack.size() == 0) { throw new ConversionException("Single value cannot be root element"); } } else { throw new IllegalStateException("Cannot set value"); } if ((type == Character.class || type == Character.TYPE) && "".equals(text)) { text = "\u0000"; } addValue(text, getType(type)); } /** * {@inheritDoc} */ public void endNode() { Status status = (Status)statusStack.peek(); if (status == Status.END) { statusStack.popSilently(); Class type = (Class)typeStack.pop(); status = (Status)statusStack.peek(); if (isArray(type)) { if ((mode & EXPLICIT_MODE) != 0) { endObject(); } if (status == Status.ELEMENT || status == Status.ARRAY) { endArray(); statusStack.popSilently(); status = (Status)statusStack.peek(); } else { throw new IllegalStateException("Cannot end array"); } if (status == Status.VIRTUAL) { statusStack.popSilently(); endObject(); status = (Status)statusStack.peek(); } } else if (status != Status.OBJECT && status != Status.PROPERTY) { throw new IllegalStateException("Cannot end object"); } else { endObject(); } } else if (status == Status.VALUE || status == Status.VIRTUAL) { statusStack.popSilently(); Class type = (Class)typeStack.pop(); if (status == Status.VIRTUAL && (mode & EXPLICIT_MODE) != 0) { nextElement(); addLabel("$"); } if (isArray(type)) { startArray(); endArray(); } else if ((mode & EXPLICIT_MODE) != 0 || status == Status.VALUE) { startObject(null); endObject(); } if (status == Status.VIRTUAL) { endObject(); } status = (Status)statusStack.peek(); } if (status == Status.PROPERTY || status == Status.OBJECT) { if (typeStack.size() == 0) { status = (Status)statusStack.pop(); if (status != Status.OBJECT) { throw new IllegalStateException("Cannot end object"); } if ((mode & DROP_ROOT_MODE) == 0) { endObject(); } } else { statusStack.replaceSilently(Status.END); } } else { throw new IllegalStateException("Cannot end object"); } } private Type getType(Class clazz) { return NUMBER_TYPES.contains(clazz) ? Type.NUMBER : (clazz == Boolean.class || clazz == Boolean.TYPE) ? Type.BOOLEAN : Type.STRING; } private boolean isArray(Class clazz) { return clazz.isArray() || Collection.class.isAssignableFrom(clazz) || Map.class.isAssignableFrom(clazz) || (((mode & EXPLICIT_MODE) == 0) && Map.Entry.class.isAssignableFrom(clazz)); } /** * Start a JSON object. * * @param name the object's name (may be <code>null</code> for an empty object) * @since upcoming */ protected abstract void startObject(String name); /** * Add a label to a JSON object. * * @param name the label's name * @since upcoming */ protected abstract void addLabel(String name); /** * Add a value to a JSON object's label or to an array. * * @param value the value itself * @param type the JSON type * @since upcoming */ protected abstract void addValue(String value, Type type); /** * Start a JSON array. * * @since upcoming */ protected abstract void startArray(); /** * Prepare a JSON object or array for another element. * * @since upcoming */ protected abstract void nextElement(); /** * End the JSON array. * * @since upcoming */ protected abstract void endArray(); /** * End the JSON object. * * @since upcoming */ protected abstract void endObject(); }
xstream/src/java/com/thoughtworks/xstream/io/json/AbstractJsonWriter.java
/* * Copyright (C) 2009 XStream Committers. * All rights reserved. * * Created on 20. August 2009 by Joerg Schaible */ package com.thoughtworks.xstream.io.json; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.core.util.FastStack; import com.thoughtworks.xstream.io.AbstractWriter; import com.thoughtworks.xstream.io.naming.NameCoder; import com.thoughtworks.xstream.io.naming.NoNameCoder; /** * An abstract implementation of a writer that calls abstract methods to build JSON structures. * Note, that XStream's implicit collection feature is not compatible with any kind of JSON * syntax. * * @author J&ouml;rg Schaible * @since upcoming */ public abstract class AbstractJsonWriter extends AbstractWriter { /** * DROP_ROOT_MODE drops the JSON root node. * <p> * The root node is the first level of the JSON object i.e. * * <pre> * { &quot;person&quot;: { * &quot;name&quot;: &quot;Joe&quot; * }} * </pre> * * will be written without root simply as * * <pre> * { * &quot;name&quot;: &quot;Joe&quot; * } * </pre> * * Without a root node, the top level element might now also be an array. However, it is * possible to generate invalid JSON unless {@link #STRICT_MODE} is also set. * </p> * * @since 1.3.1 */ public static final int DROP_ROOT_MODE = 1; /** * STRICT_MODE prevents invalid JSON for single value objects when dropping the root. * <p> * The mode is only useful in combination with the {@link #DROP_ROOT_MODE}. An object with a * single value as first node i.e. * * <pre> * { &quot;name&quot;: &quot;Joe&quot; } * </pre> * * is simply written as * * <pre> * &quot;Joe&quot; * </pre> * * However, this is no longer valid JSON. Therefore you can activate {@link #STRICT_MODE} * and a {@link ConversionException} is thrown instead. * </p> * * @since 1.3.1 */ public static final int STRICT_MODE = 2; // TODO: Javadoc public static final int EXPLICIT_MODE = 4; public enum Type { STRING, NUMBER, BOOLEAN } private static class Status { public final static Status OBJECT = new Status("object"); public final static Status PROPERTY = new Status("property"); public final static Status VALUE = new Status("value"); public final static Status END = new Status("end"); public final static Status ARRAY = new Status("array"); public final static Status ELEMENT = new Status("element"); public final static Status VIRTUAL = new Status("virtual"); private final String name; private Status(String name) { this.name = name; } @Override public String toString() { return name; } } private static final List<Class> NUMBER_TYPES = Arrays.asList(new Class[]{ byte.class, Byte.class, short.class, Short.class, int.class, Integer.class, long.class, Long.class, float.class, Float.class, double.class, Double.class}); private int mode; private FastStack statusStack = new FastStack(32); private FastStack typeStack = new FastStack(16); /** * Construct a JSON writer. * * @since upcoming */ public AbstractJsonWriter() { this(new NoNameCoder()); } /** * Construct a JSON writer with a special mode. * * @param mode a bit mask of the mode constants * @since upcoming */ public AbstractJsonWriter(int mode) { this(mode, new NoNameCoder()); } /** * Construct a JSON writer with a special name coder. * * @param nameCoder the name coder to use * @since upcoming */ public AbstractJsonWriter(NameCoder nameCoder) { this(0, nameCoder); } /** * Construct a JSON writer with a special mode and name coder. * * @param mode a bit mask of the mode constants * @param nameCoder the name coder to use * @since upcoming */ public AbstractJsonWriter(int mode, NameCoder nameCoder) { super(nameCoder); this.mode = mode; } @Override public void startNode(String name, Class clazz) { if (statusStack.size() == 0) { statusStack.push(Status.OBJECT); if ((mode & DROP_ROOT_MODE) == 0) { startObject(name); } } else { Class type = (Class)typeStack.peek(); Status status = (Status)statusStack.peek(); if (isArray(type)) { if (status == Status.OBJECT || status == Status.VIRTUAL || status == Status.PROPERTY || status == Status.VALUE) { if (status == Status.PROPERTY || status == Status.VIRTUAL) { nextElement(); addLabel("$"); } if (status == Status.VALUE) { statusStack.replaceSilently(Status.ARRAY); } else { statusStack.replaceSilently(Status.ARRAY); } startArray(); statusStack.push(Status.OBJECT); if ((mode & EXPLICIT_MODE) != 0) { startObject(name); } } else if (status == Status.END) { if ((mode & EXPLICIT_MODE) != 0) { endObject(); } statusStack.popSilently(); status = (Status)statusStack.peek(); if (status == Status.ARRAY) { statusStack.replaceSilently(Status.ELEMENT); } else if (status != Status.ELEMENT) { throw new IllegalStateException("Cannot add new array element"); } nextElement(); statusStack.push(Status.OBJECT); if ((mode & EXPLICIT_MODE) != 0) { startObject(name); } } else { throw new IllegalStateException("Cannot start new array element"); } } else if (status == Status.VALUE) { statusStack.replaceSilently(Status.OBJECT); startObject(name); } else if (status == Status.PROPERTY || status == Status.END || status == Status.VIRTUAL) { statusStack.replaceSilently(Status.PROPERTY); nextElement(); addLabel(name); } else { throw new IllegalStateException("Cannot start new element"); } } statusStack.push(Status.VALUE); typeStack.push(clazz == null ? String.class : clazz); } /** * {@inheritDoc} */ public void startNode(String name) { startNode(name, String.class); } /** * {@inheritDoc} */ public void addAttribute(String name, String value) { Class type = (Class)typeStack.peek(); if ((mode & EXPLICIT_MODE) != 0 || !isArray(type)) { Status status = (Status)statusStack.peek(); if (status == Status.VALUE) { statusStack.replaceSilently(Status.VIRTUAL); startObject("@" + name); } else if (status == Status.PROPERTY || status == Status.VIRTUAL) { nextElement(); addLabel("@" + name); } else { throw new IllegalStateException("Cannot add attribute"); } addValue(value, Type.STRING); } } /** * {@inheritDoc} */ public void setValue(String text) { Status status = (Status)statusStack.peek(); Class type = (Class)typeStack.peek(); if (status == Status.PROPERTY || status == Status.VIRTUAL) { nextElement(); addLabel("$"); statusStack.replaceSilently(Status.END); } else if (status == Status.VALUE) { statusStack.popSilently(); typeStack.popSilently(); if ((mode & STRICT_MODE) != 0 && typeStack.size() == 0) { throw new ConversionException("Single value cannot be root element"); } } else { throw new IllegalStateException("Cannot set value"); } if ((type == Character.class || type == Character.TYPE) && "".equals(text)) { text = "\u0000"; } addValue(text, getType(type)); } /** * {@inheritDoc} */ public void endNode() { Status status = (Status)statusStack.peek(); if (status == Status.END) { statusStack.popSilently(); Class type = (Class)typeStack.pop(); status = (Status)statusStack.peek(); if (isArray(type)) { if ((mode & EXPLICIT_MODE) != 0) { endObject(); } if (status == Status.ELEMENT || status == Status.ARRAY) { endArray(); statusStack.popSilently(); status = (Status)statusStack.peek(); } else { throw new IllegalStateException("Cannot end array"); } if (status == Status.VIRTUAL) { statusStack.popSilently(); endObject(); status = (Status)statusStack.peek(); } } else if (status != Status.OBJECT && status != Status.PROPERTY) { throw new IllegalStateException("Cannot end object"); } else { endObject(); } } else if (status == Status.VALUE || status == Status.VIRTUAL) { statusStack.popSilently(); Class type = (Class)typeStack.pop(); if (status == Status.VIRTUAL && (mode & EXPLICIT_MODE) != 0) { nextElement(); addLabel("$"); } if (isArray(type)) { startArray(); endArray(); } else if ((mode & EXPLICIT_MODE) != 0 || status == Status.VALUE) { startObject(null); endObject(); } if (status == Status.VIRTUAL) { endObject(); } status = (Status)statusStack.peek(); } if (status == Status.PROPERTY || status == Status.OBJECT) { if (typeStack.size() == 0) { status = (Status)statusStack.pop(); if (status != Status.OBJECT) { throw new IllegalStateException("Cannot end object"); } if ((mode & DROP_ROOT_MODE) == 0) { endObject(); } } else { statusStack.replaceSilently(Status.END); } } else { throw new IllegalStateException("Cannot end object"); } } private Type getType(Class clazz) { return NUMBER_TYPES.contains(clazz) ? Type.NUMBER : (clazz == Boolean.class || clazz == Boolean.TYPE) ? Type.BOOLEAN : Type.STRING; } private boolean isArray(Class clazz) { return clazz.isArray() || Collection.class.isAssignableFrom(clazz) || Map.class.isAssignableFrom(clazz) || (((mode & EXPLICIT_MODE) == 0) && Map.Entry.class.isAssignableFrom(clazz)); } /** * Start a JSON object. * * @param name the object's name (may be <code>null</code> for an empty object) * @since upcoming */ protected abstract void startObject(String name); /** * Add a label to a JSON object. * * @param name the label's name * @since upcoming */ protected abstract void addLabel(String name); /** * Add a value to a JSON object's label or to an array. * * @param value the value itself * @param type the JSON type * @since upcoming */ protected abstract void addValue(String value, Type type); /** * Start a JSON array. * * @since upcoming */ protected abstract void startArray(); /** * Prepare a JSON object or array for another element. * * @since upcoming */ protected abstract void nextElement(); /** * End the JSON array. * * @since upcoming */ protected abstract void endArray(); /** * End the JSON object. * * @since upcoming */ protected abstract void endObject(); }
No annotations. git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@1709 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e
xstream/src/java/com/thoughtworks/xstream/io/json/AbstractJsonWriter.java
No annotations.
Java
bsd-3-clause
0dfa1459b871cc98355e0e4eb1ae22dc4bb29c93
0
yotchang4s/cafebabepy
package org.cafebabepy.runtime.module.builtins; import org.cafebabepy.annotation.DefineCafeBabePyFunction; import org.cafebabepy.annotation.DefineCafeBabePyModule; import org.cafebabepy.runtime.PyObject; import org.cafebabepy.runtime.Python; import org.cafebabepy.runtime.module.AbstractCafeBabePyModule; import java.util.HashSet; import java.util.Set; /** * Created by yotchang4s on 2017/05/12. */ @DefineCafeBabePyModule(name = "builtins") public class PyBuiltinsModule extends AbstractCafeBabePyModule { public PyBuiltinsModule(Python runtime) { super(runtime); } @DefineCafeBabePyFunction(name = "isinstance") public PyObject isInstance(PyObject object, PyObject classInfo) { if (classInfo == null || (!classInfo.isType() && classInfo instanceof PyTupleType)) { throw this.runtime.newRaiseTypeError( "isinstance() arg 2 must be a type or tuple of types"); } Set<PyObject> objectTypeSet = new HashSet<>(); appendIntoObjectTypeSet(objectTypeSet, object); if (objectTypeSet.contains(object)) { return this.runtime.True(); } return this.runtime.False(); } private void appendIntoObjectTypeSet(Set<PyObject> objectTypeSet, PyObject type) { objectTypeSet.add(type); if (type instanceof PyTypeType) { if (objectTypeSet.contains(type)) { return; } } else if (type instanceof PyObjectType) { if (objectTypeSet.contains(type)) { return; } } else if (type instanceof PyTupleType) { this.runtime.iter(type, t -> appendIntoObjectTypeSet(objectTypeSet, t)); } type.getSuperTypes().forEach(t -> appendIntoObjectTypeSet(objectTypeSet, t)); } }
src/main/java/org/cafebabepy/runtime/module/builtins/PyBuiltinsModule.java
package org.cafebabepy.runtime.module.builtins; import org.cafebabepy.annotation.DefineCafeBabePyFunction; import org.cafebabepy.annotation.DefineCafeBabePyModule; import org.cafebabepy.runtime.PyObject; import org.cafebabepy.runtime.Python; import org.cafebabepy.runtime.module.AbstractCafeBabePyModule; import java.util.HashSet; import java.util.Set; /** * Created by yotchang4s on 2017/05/12. */ @DefineCafeBabePyModule(name = "builtins") public class PyBuiltinsModule extends AbstractCafeBabePyModule { public PyBuiltinsModule(Python runtime) { super(runtime); } @DefineCafeBabePyFunction(name = "issubclass") public PyObject isSubClass(PyObject clazz, PyObject classInfo) { if (clazz == null || !clazz.isType()) { throw this.runtime.newRaiseTypeError( "issubclass() arg 1 must be a class"); } Set<PyObject> classInfoSet = new HashSet<>(); appendIntoClassInfoSet(classInfoSet, classInfo); if (classInfoSet.contains(classInfo)) { return this.runtime.True(); } else { return this.runtime.False(); } } private void appendIntoClassInfoSet(Set<PyObject> classInfoSet, PyObject classinfo) { if (classinfo == null || !classinfo.isType()) { throw this.runtime.newRaiseTypeError( "issubclass() arg 2 must be a class or tuple of classes"); } else if (classinfo.getType() instanceof PyTupleType) { this.runtime.iter(classinfo, c -> appendIntoClassInfoSet(classInfoSet, c)); } else { classInfoSet.add(classinfo); } } }
Rename oops!! issubclass to isinstance
src/main/java/org/cafebabepy/runtime/module/builtins/PyBuiltinsModule.java
Rename oops!! issubclass to isinstance
Java
bsd-3-clause
2f2592583ff3c1c36855a3034f47d12b1a7c140c
0
ctrimble/JavaCL,ctrimble/JavaCL,ctrimble/JavaCL,n0mer/JavaCL,n0mer/JavaCL,n0mer/JavaCL
/* * JavaCL - Java API and utilities for OpenCL * http://javacl.googlecode.com/ * * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Olivier Chafik nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.nativelibs4java.opencl; import static com.nativelibs4java.opencl.CLException.error; import static com.nativelibs4java.opencl.JavaCL.CL; import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; import java.util.Arrays; import com.nativelibs4java.opencl.library.OpenCLLibrary; import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; import com.nativelibs4java.util.EnumValue; import com.nativelibs4java.util.EnumValues; import com.nativelibs4java.util.ValuedEnum; import com.ochafik.lang.jnaerator.runtime.NativeSize; import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; import com.sun.jna.Callback; import com.sun.jna.Memory; import com.sun.jna.Pointer; /** * OpenCL event object.<br/> * Event objects can be used to refer to a kernel execution command (clEnqueueNDRangeKernel, clEnqueueTask, clEnqueueNativeKernel), or read, write, map and copy commands on memory objects (clEnqueue{Read|Write|Map}{Buffer|Image}, clEnqueueCopy{Buffer|Image}, clEnqueueCopyBufferToImage, or clEnqueueCopyImageToBuffer).<br/> * An event object can be used to track the execution status of a command. <br/> * The API calls that enqueue commands to a command-queue create a new event object that is returned in the event argument. <br/> * In case of an error enqueuing the command in the command-queue the event argument does not return an event object.<br/> * The execution status of an enqueued command at any given point in time can be CL_QUEUED (command has been enqueued in the command-queue), CL_SUBMITTED (enqueued command has been submitted by the host to the device associated with the command-queue), CL_RUNNING (device is currently executing this command), CL_COMPLETE (command has successfully completed) or the appropriate error code if the command was abnormally terminated (this may be caused by a bad memory access etc.). <br/> * The error code returned by a terminated command is a negative integer value. <br/> * A command is considered to be complete if its execution status is CL_COMPLETE or is a negative integer value.<br/> * If the execution of a command is terminated, the command-queue associated with this terminated command, and the associated context (and all other command-queues in this context) may no longer be available. <br/> * The behavior of OpenCL API calls that use this context (and command-queues associated with this context) are now considered to be implementation- defined. <br/> * The user registered callback function specified when context is created can be used to report appropriate error information.<br/> * * @author ochafik */ public class CLEvent extends CLAbstractEntity<cl_event> { private static CLInfoGetter<cl_event> infos = new CLInfoGetter<cl_event>() { @Override protected int getInfo(cl_event entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut) { return CL.clGetEventInfo(entity, infoTypeEnum, size, out, sizeOut); } }; private static CLInfoGetter<cl_event> profilingInfos = new CLInfoGetter<cl_event>() { @Override protected int getInfo(cl_event entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut) { return CL.clGetEventProfilingInfo(entity, infoTypeEnum, size, out, sizeOut); } }; CLEvent(cl_event evt) { super(evt, false); } CLEvent() { super(null, true); } public interface EventCallback { public void callback(CLEvent event, int executionStatus); } /** * Registers a user callback function for the completion execution status (CL_COMPLETE). <br/> * @param callback * @throws UnsupportedOperationException in OpenCL 1.0 * @since OpenCL 1.1 */ public void setCompletionCallback(final EventCallback callback) { setCallback(CL_COMPLETE, callback); } /** * Registers a user callback function for a specific command execution status. <br/> * The registered callback function will be called when the execution status of command associated with event changes to the execution status specified by command_exec_status. * @param commandExecStatus specifies the command execution status for which the callback is registered. The command execution callback values for which a callback can be registered are: CL_COMPLETE. There is no guarantee that the callback functions registered for various execution status values for an event will be called in the exact order that the execution status of a command changes. * @param callback * @throws UnsupportedOperationException in OpenCL 1.0 * @since OpenCL 1.1 */ public void setCallback(int commandExecStatus, final EventCallback callback) { try { error(CL.clSetEventCallback(getEntity(), commandExecStatus, new clSetEventCallback_arg1_callback() { public void invoke(OpenCLLibrary.cl_event evt, int executionStatus, Pointer voidPtr1) { callback.callback(CLEvent.this, executionStatus); } }, null)); } catch (Throwable th) { // TODO check if supposed to handle OpenCL 1.1 throw new UnsupportedOperationException("Cannot set event callback (OpenCL 1.1 feature).", th); } } static boolean noEvents = false; public static void setNoEvents(boolean noEvents) { CLEvent.noEvents = noEvents; } static CLEvent createEvent(final CLQueue queue, cl_event evt) { return createEvent(queue, evt, false); } static CLEvent createEvent(final CLQueue queue, cl_event evt, boolean isUserEvent) { if (noEvents && queue != null) { if (evt != null) CL.clReleaseEvent(evt); evt = null; if (isUserEvent) return new CLUserEvent() { volatile boolean waited = false; @Override public synchronized void waitFor() { if (!waited) { queue.finish(); waited = true; } } }; return new CLEvent() { volatile boolean waited = false; @Override public synchronized void waitFor() { if (!waited) { queue.finish(); waited = true; } } }; } if (evt == null) return null; return isUserEvent ? new CLUserEvent(evt) : new CLEvent(evt); } static CLEvent createEvent(CLQueue queue, cl_event[] evt1) { if (evt1 == null) return null; return createEvent(queue, evt1[0]); } /** * Wait for this event, blocking the caller thread independently of any queue until all of the command associated with this events completes. */ public void waitFor() { if (entity == null) return; waitFor(this); } /** * Wait for events, blocking the caller thread independently of any queue until all of the commands associated with the events completed. * @param eventsToWaitFor List of events which completion is to be waited for */ public static void waitFor(CLEvent... eventsToWaitFor) { if (eventsToWaitFor.length == 0) return; try { cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); if (evts == null || evts.length == 0) return; error(CL.clWaitForEvents(evts.length, evts)); } catch (Exception ex) { throw new RuntimeException("Exception while waiting for events " + Arrays.asList(eventsToWaitFor), ex); } } /** * Invoke an action in a separate thread only after completion of the command associated with this event.<br/> * Returns immediately. * @param action an action to be ran * @throws IllegalArgumentException if action is null */ public void invokeUponCompletion(final Runnable action) { invokeUponCompletion(action, this); } /** * Invoke an action in a separate thread only after completion of all of the commands associated with the specified events.<br/> * Returns immediately. * @param action an action to be ran * @param eventsToWaitFor list of events which commands's completion should be waited for before the action is ran * @throws IllegalArgumentException if action is null */ public static void invokeUponCompletion(final Runnable action, final CLEvent... eventsToWaitFor) { if (action == null) throw new IllegalArgumentException("Null action !"); new Thread() { public void run() { waitFor(eventsToWaitFor); action.run(); } }.start(); } static cl_event[] new_event_out(CLEvent[] eventsToWaitFor) { return noEvents || eventsToWaitFor == null ? null : new cl_event[1]; } static cl_event[] to_cl_event_array(CLEvent... events) { if (events == null) return null; if (noEvents) { for (CLEvent evt : events) if (evt != null) evt.waitFor(); return null; } int n = events.length; if (n == 0) return null; int nonNulls = 0; for (int i = 0; i < n; i++) if (events[i] != null && events[i].getEntity() != null) nonNulls++; if (nonNulls == 0) return null; cl_event[] event_wait_list = new cl_event[nonNulls]; int iDest = 0; for (int i = 0; i < n; i++) { CLEvent event = events[i]; if (event == null || event.getEntity() == null) continue; event_wait_list[iDest] = event.getEntity(); iDest++; } return event_wait_list; } @Override protected void clear() { error(CL.clReleaseEvent(getEntity())); } /** Values for CL_EVENT_COMMAND_EXECUTION_STATUS */ public enum CommandExecutionStatus implements ValuedEnum { /** command has been enqueued in the command-queue */ Queued(CL_QUEUED), /** enqueued command has been submitted by the host to the device associated with the command-queue */ Submitted(CL_SUBMITTED), /** device is currently executing this command */ Running(CL_RUNNING), /** the command has completed */ Complete(CL_COMPLETE); CommandExecutionStatus(long value) { this.value = value; } long value; @Override public long value() { return value; } public static CommandExecutionStatus getEnum(long v) { return EnumValues.getEnum(v, CommandExecutionStatus.class); } } /** * Return the execution status of the command identified by event. <br/> * @throws CLException is the execution status denotes an error */ public CommandExecutionStatus getCommandExecutionStatus() { int v = infos.getInt(getEntity(), CL_EVENT_COMMAND_EXECUTION_STATUS); CommandExecutionStatus status = CommandExecutionStatus.getEnum(v); if (status == null) error(v); return status; } /** * Return the execution status of the command identified by event. <br/> * @throws CLException is the execution status denotes an error */ @InfoName("CL_EVENT_COMMAND_EXECUTION_STATUS") public int getCommandExecutionStatusValue() { return infos.getInt(getEntity(), CL_EVENT_COMMAND_EXECUTION_STATUS); } /** Values for CL_EVENT_COMMAND_TYPE */ public enum CommandType implements ValuedEnum { NDRangeKernel(CL_COMMAND_NDRANGE_KERNEL), Task(CL_COMMAND_TASK), NativeKernel(CL_COMMAND_NATIVE_KERNEL), ReadBuffer(CL_COMMAND_READ_BUFFER), WriteBuffer(CL_COMMAND_WRITE_BUFFER), CopyBuffer(CL_COMMAND_COPY_BUFFER), ReadImage(CL_COMMAND_READ_IMAGE), WriteImage(CL_COMMAND_WRITE_IMAGE), CopyImage(CL_COMMAND_COPY_IMAGE), CopyBufferToImage(CL_COMMAND_COPY_BUFFER_TO_IMAGE), CopyImageToBuffer(CL_COMMAND_COPY_IMAGE_TO_BUFFER), MapBuffer(CL_COMMAND_MAP_BUFFER), CommandMapImage(CL_COMMAND_MAP_IMAGE), UnmapMemObject(CL_COMMAND_UNMAP_MEM_OBJECT), Marker(CL_COMMAND_MARKER), AcquireGLObjects(CL_COMMAND_ACQUIRE_GL_OBJECTS), ReleaseGLObjects(CL_COMMAND_RELEASE_GL_OBJECTS); CommandType(long value) { this.value = value; } long value; @Override public long value() { return value; } public static CommandType getEnum(long v) { return EnumValues.getEnum(v, CommandType.class); } } /** * Return the command associated with event. */ @InfoName("CL_EVENT_COMMAND_TYPE") public CommandType getCommandType() { return CommandType.getEnum(infos.getInt(getEntity(), CL_EVENT_COMMAND_TYPE)); } /** * A 64-bit value that describes the current device time counter in nanoseconds when the command identified by event is enqueued in a command-queue by the host. */ @InfoName("CL_CL_PROFILING_COMMAND_QUEUED") public long getProfilingCommandQueued() { return profilingInfos.getIntOrLong(getEntity(), CL_PROFILING_COMMAND_QUEUED); } /** * A 64-bit value that describes the current device time counter in nanoseconds when the command identified by event that has been enqueued is submitted by the host to the device associated with the command- queue. */ @InfoName("CL_CL_PROFILING_COMMAND_SUBMIT") public long getProfilingCommandSubmit() { return profilingInfos.getIntOrLong(getEntity(), CL_PROFILING_COMMAND_SUBMIT); } /** * A 64-bit value that describes the current device time counter in nanoseconds when the command identified by event starts execution on the device. */ @InfoName("CL_CL_PROFILING_COMMAND_START") public long getProfilingCommandStart() { return profilingInfos.getIntOrLong(getEntity(), CL_PROFILING_COMMAND_START); } /** * A 64-bit value that describes the current device time counter in nanoseconds when the command identified by event has finished execution on the device. */ @InfoName("CL_CL_PROFILING_COMMAND_END") public long getProfilingCommandEnd() { return profilingInfos.getIntOrLong(getEntity(), CL_PROFILING_COMMAND_END); } @Override public String toString() { return "Event {commandType: " + getCommandType() + "}"; } }
libraries/OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLEvent.java
/* * JavaCL - Java API and utilities for OpenCL * http://javacl.googlecode.com/ * * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Olivier Chafik nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.nativelibs4java.opencl; import static com.nativelibs4java.opencl.CLException.error; import static com.nativelibs4java.opencl.JavaCL.CL; import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; import java.util.Arrays; import com.nativelibs4java.opencl.library.OpenCLLibrary; import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_event; import com.nativelibs4java.util.EnumValue; import com.nativelibs4java.util.EnumValues; import com.nativelibs4java.util.ValuedEnum; import com.ochafik.lang.jnaerator.runtime.NativeSize; import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; import com.sun.jna.Callback; import com.sun.jna.Memory; import com.sun.jna.Pointer; /** * OpenCL event object.<br/> * Event objects can be used to refer to a kernel execution command (clEnqueueNDRangeKernel, clEnqueueTask, clEnqueueNativeKernel), or read, write, map and copy commands on memory objects (clEnqueue{Read|Write|Map}{Buffer|Image}, clEnqueueCopy{Buffer|Image}, clEnqueueCopyBufferToImage, or clEnqueueCopyImageToBuffer).<br/> * An event object can be used to track the execution status of a command. <br/> * The API calls that enqueue commands to a command-queue create a new event object that is returned in the event argument. <br/> * In case of an error enqueuing the command in the command-queue the event argument does not return an event object.<br/> * The execution status of an enqueued command at any given point in time can be CL_QUEUED (command has been enqueued in the command-queue), CL_SUBMITTED (enqueued command has been submitted by the host to the device associated with the command-queue), CL_RUNNING (device is currently executing this command), CL_COMPLETE (command has successfully completed) or the appropriate error code if the command was abnormally terminated (this may be caused by a bad memory access etc.). <br/> * The error code returned by a terminated command is a negative integer value. <br/> * A command is considered to be complete if its execution status is CL_COMPLETE or is a negative integer value.<br/> * If the execution of a command is terminated, the command-queue associated with this terminated command, and the associated context (and all other command-queues in this context) may no longer be available. <br/> * The behavior of OpenCL API calls that use this context (and command-queues associated with this context) are now considered to be implementation- defined. <br/> * The user registered callback function specified when context is created can be used to report appropriate error information.<br/> * * @author ochafik */ public class CLEvent extends CLAbstractEntity<cl_event> { private static CLInfoGetter<cl_event> infos = new CLInfoGetter<cl_event>() { @Override protected int getInfo(cl_event entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut) { return CL.clGetEventInfo(entity, infoTypeEnum, size, out, sizeOut); } }; private static CLInfoGetter<cl_event> profilingInfos = new CLInfoGetter<cl_event>() { @Override protected int getInfo(cl_event entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut) { return CL.clGetEventProfilingInfo(entity, infoTypeEnum, size, out, sizeOut); } }; CLEvent(cl_event evt) { super(evt, false); } CLEvent() { super(null, true); } public interface EventCallback { public void callback(CLEvent event, int executionStatus); } /** * Registers a user callback function for the completion execution status (CL_COMPLETE). <br/> * @param callback * @throws UnsupportedOperationException in OpenCL 1.0 * @since OpenCL 1.1 */ public void setCompletionCallback(final EventCallback callback) { setCallback(CL_COMPLETE, callback); } /** * Registers a user callback function for a specific command execution status. <br/> * The registered callback function will be called when the execution status of command associated with event changes to the execution status specified by command_exec_status. * @param commandExecStatus specifies the command execution status for which the callback is registered. The command execution callback values for which a callback can be registered are: CL_COMPLETE. There is no guarantee that the callback functions registered for various execution status values for an event will be called in the exact order that the execution status of a command changes. * @param callback * @throws UnsupportedOperationException in OpenCL 1.0 * @since OpenCL 1.1 */ public void setCallback(int commandExecStatus, final EventCallback callback) { try { error(CL.clSetEventCallback(getEntity(), commandExecStatus, new clSetEventCallback_arg1_callback() { public void invoke(OpenCLLibrary.cl_event evt, int executionStatus, Pointer voidPtr1) { callback.callback(CLEvent.this, executionStatus); } }, null)); } catch (Throwable th) { // TODO check if supposed to handle OpenCL 1.1 throw new UnsupportedOperationException("Cannot set event callback (OpenCL 1.1 feature).", th); } } static boolean noEvents = false; public static void setNoEvents(boolean noEvents) { CLEvent.noEvents = noEvents; } static CLEvent createEvent(final CLQueue queue, cl_event evt) { return createEvent(queue, evt, false); } static CLEvent createEvent(final CLQueue queue, cl_event evt, boolean isUserEvent) { if (noEvents && queue != null) { if (evt != null) CL.clReleaseEvent(evt); evt = null; if (isUserEvent) return new CLUserEvent() { volatile boolean waited = false; @Override public synchronized void waitFor() { if (!waited) { queue.finish(); waited = true; } } }; return new CLEvent() { volatile boolean waited = false; @Override public synchronized void waitFor() { if (!waited) { queue.finish(); waited = true; } } }; } if (evt == null) return null; return isUserEvent ? new CLUserEvent(evt) : new CLEvent(evt); } static CLEvent createEvent(CLQueue queue, cl_event[] evt1) { if (evt1 == null) return null; return createEvent(queue, evt1[0]); } /** * Wait for this event, blocking the caller thread independently of any queue until all of the command associated with this events completes. */ public void waitFor() { if (entity == null) return; waitFor(this); } /** * Wait for events, blocking the caller thread independently of any queue until all of the commands associated with the events completed. * @param eventsToWaitFor List of events which completion is to be waited for */ public static void waitFor(CLEvent... eventsToWaitFor) { if (eventsToWaitFor.length == 0) return; try { cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor); if (evts == null || evts.length == 0) return; error(CL.clWaitForEvents(evts.length, evts)); } catch (Exception ex) { throw new RuntimeException("Exception while waiting for events " + Arrays.asList(eventsToWaitFor), ex); } } /** * Invoke an action in a separate thread only after completion of the command associated with this event.<br/> * Returns immediately. * @param action an action to be ran * @throws IllegalArgumentException if action is null */ public void invokeUponCompletion(final Runnable action) { invokeUponCompletion(action, this); } /** * Invoke an action in a separate thread only after completion of all of the commands associated with the specified events.<br/> * Returns immediately. * @param action an action to be ran * @param eventsToWaitFor list of events which commands's completion should be waited for before the action is ran * @throws IllegalArgumentException if action is null */ public static void invokeUponCompletion(final Runnable action, final CLEvent... eventsToWaitFor) { if (action == null) throw new IllegalArgumentException("Null action !"); new Thread() { public void run() { waitFor(eventsToWaitFor); action.run(); } }.start(); } static cl_event[] new_event_out(CLEvent[] eventsToWaitFor) { return noEvents || eventsToWaitFor == null ? null : new cl_event[1]; } static cl_event[] to_cl_event_array(CLEvent... events) { if (noEvents) { for (CLEvent evt : events) if (evt != null) evt.waitFor(); return null; } int n = events.length; if (n == 0) return null; int nonNulls = 0; for (int i = 0; i < n; i++) if (events[i] != null && events[i].getEntity() != null) nonNulls++; if (nonNulls == 0) return null; cl_event[] event_wait_list = new cl_event[nonNulls]; int iDest = 0; for (int i = 0; i < n; i++) { CLEvent event = events[i]; if (event == null || event.getEntity() == null) continue; event_wait_list[iDest] = event.getEntity(); iDest++; } return event_wait_list; } @Override protected void clear() { error(CL.clReleaseEvent(getEntity())); } /** Values for CL_EVENT_COMMAND_EXECUTION_STATUS */ public enum CommandExecutionStatus implements ValuedEnum { /** command has been enqueued in the command-queue */ Queued(CL_QUEUED), /** enqueued command has been submitted by the host to the device associated with the command-queue */ Submitted(CL_SUBMITTED), /** device is currently executing this command */ Running(CL_RUNNING), /** the command has completed */ Complete(CL_COMPLETE); CommandExecutionStatus(long value) { this.value = value; } long value; @Override public long value() { return value; } public static CommandExecutionStatus getEnum(long v) { return EnumValues.getEnum(v, CommandExecutionStatus.class); } } /** * Return the execution status of the command identified by event. <br/> * @throws CLException is the execution status denotes an error */ public CommandExecutionStatus getCommandExecutionStatus() { int v = infos.getInt(getEntity(), CL_EVENT_COMMAND_EXECUTION_STATUS); CommandExecutionStatus status = CommandExecutionStatus.getEnum(v); if (status == null) error(v); return status; } /** * Return the execution status of the command identified by event. <br/> * @throws CLException is the execution status denotes an error */ @InfoName("CL_EVENT_COMMAND_EXECUTION_STATUS") public int getCommandExecutionStatusValue() { return infos.getInt(getEntity(), CL_EVENT_COMMAND_EXECUTION_STATUS); } /** Values for CL_EVENT_COMMAND_TYPE */ public enum CommandType implements ValuedEnum { NDRangeKernel(CL_COMMAND_NDRANGE_KERNEL), Task(CL_COMMAND_TASK), NativeKernel(CL_COMMAND_NATIVE_KERNEL), ReadBuffer(CL_COMMAND_READ_BUFFER), WriteBuffer(CL_COMMAND_WRITE_BUFFER), CopyBuffer(CL_COMMAND_COPY_BUFFER), ReadImage(CL_COMMAND_READ_IMAGE), WriteImage(CL_COMMAND_WRITE_IMAGE), CopyImage(CL_COMMAND_COPY_IMAGE), CopyBufferToImage(CL_COMMAND_COPY_BUFFER_TO_IMAGE), CopyImageToBuffer(CL_COMMAND_COPY_IMAGE_TO_BUFFER), MapBuffer(CL_COMMAND_MAP_BUFFER), CommandMapImage(CL_COMMAND_MAP_IMAGE), UnmapMemObject(CL_COMMAND_UNMAP_MEM_OBJECT), Marker(CL_COMMAND_MARKER), AcquireGLObjects(CL_COMMAND_ACQUIRE_GL_OBJECTS), ReleaseGLObjects(CL_COMMAND_RELEASE_GL_OBJECTS); CommandType(long value) { this.value = value; } long value; @Override public long value() { return value; } public static CommandType getEnum(long v) { return EnumValues.getEnum(v, CommandType.class); } } /** * Return the command associated with event. */ @InfoName("CL_EVENT_COMMAND_TYPE") public CommandType getCommandType() { return CommandType.getEnum(infos.getInt(getEntity(), CL_EVENT_COMMAND_TYPE)); } /** * A 64-bit value that describes the current device time counter in nanoseconds when the command identified by event is enqueued in a command-queue by the host. */ @InfoName("CL_CL_PROFILING_COMMAND_QUEUED") public long getProfilingCommandQueued() { return profilingInfos.getIntOrLong(getEntity(), CL_PROFILING_COMMAND_QUEUED); } /** * A 64-bit value that describes the current device time counter in nanoseconds when the command identified by event that has been enqueued is submitted by the host to the device associated with the command- queue. */ @InfoName("CL_CL_PROFILING_COMMAND_SUBMIT") public long getProfilingCommandSubmit() { return profilingInfos.getIntOrLong(getEntity(), CL_PROFILING_COMMAND_SUBMIT); } /** * A 64-bit value that describes the current device time counter in nanoseconds when the command identified by event starts execution on the device. */ @InfoName("CL_CL_PROFILING_COMMAND_START") public long getProfilingCommandStart() { return profilingInfos.getIntOrLong(getEntity(), CL_PROFILING_COMMAND_START); } /** * A 64-bit value that describes the current device time counter in nanoseconds when the command identified by event has finished execution on the device. */ @InfoName("CL_CL_PROFILING_COMMAND_END") public long getProfilingCommandEnd() { return profilingInfos.getIntOrLong(getEntity(), CL_PROFILING_COMMAND_END); } @Override public String toString() { return "Event {commandType: " + getCommandType() + "}"; } }
JavaCL: fix NPE that happens with null varargs CLEvent[] array
libraries/OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLEvent.java
JavaCL: fix NPE that happens with null varargs CLEvent[] array
Java
mit
d5e78d71c90c4ee7c712747dd98f65c6a3db5525
0
crispab/codekvast,crispab/codekvast,crispab/codekvast,crispab/codekvast,crispab/codekvast,crispab/codekvast
product/server/backoffice/src/main/java/io/codekvast/backoffice/loadgenerator/LoadGenerator.java
package io.codekvast.backoffice.loadgenerator; import io.codekvast.common.messaging.EventService; import io.codekvast.common.messaging.model.InvocationDataReceivedEvent; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Profile; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * Helper class for locating a memory leak. * * @author [email protected] */ @Component @Profile("load-generator") @RequiredArgsConstructor public class LoadGenerator { private final EventService eventService; @Scheduled(fixedDelay = 10) public void sendEvent() { eventService.send(InvocationDataReceivedEvent.sample()); } }
Deleted helper LoadGenerator.java
product/server/backoffice/src/main/java/io/codekvast/backoffice/loadgenerator/LoadGenerator.java
Deleted helper LoadGenerator.java
Java
mit
1778c92f6617c28d9f6679574744970095dc9de0
0
WonderCsabo/robolectric,zhongyu05/robolectric,rongou/robolectric,plackemacher/robolectric,gb112211/robolectric,cc12703/robolectric,tmrudick/robolectric,tec27/robolectric,tyronen/robolectric,cc12703/robolectric,cc12703/robolectric,charlesmunger/robolectric,spotify/robolectric,1zaman/robolectric,karlicoss/robolectric,ocadotechnology/robolectric,cesar1000/robolectric,amarts/robolectric,toluju/robolectric,pivotal-oscar/robolectric,gb112211/robolectric,jingle1267/robolectric,mag/robolectric,kriegfrj/robolectric,hgl888/robolectric,jingle1267/robolectric,diegotori/robolectric,tuenti/robolectric,tyronen/robolectric,fiower/robolectric,yuzhong-google/robolectric,charlesmunger/robolectric,holmari/robolectric,rongou/robolectric,WonderCsabo/robolectric,ChengCorp/robolectric,zbsz/robolectric,rongou/robolectric,spotify/robolectric,gb112211/robolectric,davidsun/robolectric,gabrielduque/robolectric,tuenti/robolectric,pivotal-oscar/robolectric,erichaugh/robolectric,toluju/robolectric,jongerrish/robolectric,tjohn/robolectric,kriegfrj/robolectric,zbsz/robolectric,rburgst/robolectric,gruszczy/robolectric,ChengCorp/robolectric,wyvx/robolectric,lexs/robolectric,amarts/robolectric,holmari/robolectric,jongerrish/robolectric,rburgst/robolectric,svenji/robolectric,VikingDen/robolectric,gabrielduque/robolectric,pivotal-oscar/robolectric,mag/robolectric,tmrudick/robolectric,paulpv/robolectric,yuzhong-google/robolectric,trevorrjohn/robolectric,jongerrish/robolectric,tec27/robolectric,cesar1000/robolectric,plackemacher/robolectric,tjohn/robolectric,macklinu/robolectric,gabrielduque/robolectric,erichaugh/robolectric,toluju/robolectric,jongerrish/robolectric,gruszczy/robolectric,svenji/robolectric,tjohn/robolectric,davidsun/robolectric,paulpv/robolectric,lexs/robolectric,WonderCsabo/robolectric,eric-kansas/robolectric,spotify/robolectric,zbsz/robolectric,VikingDen/robolectric,eric-kansas/robolectric,ocadotechnology/robolectric,davidsun/robolectric,wyvx/robolectric,gruszczy/robolectric,lexs/robolectric,trevorrjohn/robolectric,macklinu/robolectric,diegotori/robolectric,charlesmunger/robolectric,tec27/robolectric,ocadotechnology/robolectric,amarts/robolectric,tmrudick/robolectric,1zaman/robolectric,yuzhong-google/robolectric,fiower/robolectric,VikingDen/robolectric,wyvx/robolectric,hgl888/robolectric,1zaman/robolectric,holmari/robolectric,svenji/robolectric,tuenti/robolectric,erichaugh/robolectric,plackemacher/robolectric,paulpv/robolectric,hgl888/robolectric,eric-kansas/robolectric,macklinu/robolectric,trevorrjohn/robolectric,zhongyu05/robolectric,diegotori/robolectric,tyronen/robolectric,karlicoss/robolectric,fiower/robolectric,jingle1267/robolectric,ChengCorp/robolectric,karlicoss/robolectric,zhongyu05/robolectric,kriegfrj/robolectric,cesar1000/robolectric,rburgst/robolectric,mag/robolectric
package org.robolectric; import android.app.Activity; import android.graphics.Color; import org.fest.util.Lists; import org.robolectric.res.*; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import static android.content.pm.ApplicationInfo.FLAG_ALLOW_BACKUP; import static android.content.pm.ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA; import static android.content.pm.ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING; import static android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE; import static android.content.pm.ApplicationInfo.FLAG_HAS_CODE; import static android.content.pm.ApplicationInfo.FLAG_KILL_AFTER_RESTORE; import static android.content.pm.ApplicationInfo.FLAG_PERSISTENT; import static android.content.pm.ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS; import static android.content.pm.ApplicationInfo.FLAG_RESTORE_ANY_VERSION; import static android.content.pm.ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS; import static android.content.pm.ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS; import static android.content.pm.ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES; import static android.content.pm.ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS; import static android.content.pm.ApplicationInfo.FLAG_TEST_ONLY; import static android.content.pm.ApplicationInfo.FLAG_VM_SAFE_MODE; public class AndroidManifest { private final FsFile androidManifestFile; private final FsFile resDirectory; private final FsFile assetsDirectory; private boolean manifestIsParsed; private String applicationName; private String applicationLabel; private String rClassName; private String packageName; private String processName; private String themeRef; private String labelRef; private Integer targetSdkVersion; private Integer minSdkVersion; private int versionCode; private String versionName; private int applicationFlags; private final List<ContentProviderData> providers = new ArrayList<ContentProviderData>(); private final List<ReceiverAndIntentFilter> receivers = new ArrayList<ReceiverAndIntentFilter>(); private final Map<String, ActivityData> activityDatas = new LinkedHashMap<String, ActivityData>(); private MetaData applicationMetaData; private List<AndroidManifest> libraryManifests; /** * Creates a Robolectric configuration using default Android files relative to the specified base directory. * <p/> * The manifest will be baseDir/AndroidManifest.xml, res will be baseDir/res, and assets in baseDir/assets. * * @param baseDir the base directory of your Android project * @deprecated Use {@link #AndroidManifest(org.robolectric.res.FsFile, org.robolectric.res.FsFile, org.robolectric.res.FsFile)} instead.} */ public AndroidManifest(final File baseDir) { this(Fs.newFile(baseDir)); } public AndroidManifest(final FsFile androidManifestFile, final FsFile resDirectory) { this(androidManifestFile, resDirectory, resDirectory.getParent().join("assets")); } /** * @deprecated Use {@link #AndroidManifest(org.robolectric.res.FsFile, org.robolectric.res.FsFile, org.robolectric.res.FsFile)} instead.} */ public AndroidManifest(final FsFile baseDir) { this(baseDir.join("AndroidManifest.xml"), baseDir.join("res"), baseDir.join("assets")); } /** * Creates a Robolectric configuration using specified locations. * * @param androidManifestFile location of the AndroidManifest.xml file * @param resDirectory location of the res directory * @param assetsDirectory location of the assets directory */ public AndroidManifest(FsFile androidManifestFile, FsFile resDirectory, FsFile assetsDirectory) { this.androidManifestFile = androidManifestFile; this.resDirectory = resDirectory; this.assetsDirectory = assetsDirectory; } public String getThemeRef(Class<? extends Activity> activityClass) { ActivityData activityData = getActivityData(activityClass.getName()); String themeRef = activityData != null ? activityData.getThemeRef() : null; if (themeRef == null) { themeRef = getThemeRef(); } return themeRef; } public String getRClassName() throws Exception { parseAndroidManifest(); return rClassName; } public Class getRClass() { try { String rClassName = getRClassName(); return Class.forName(rClassName); } catch (Exception e) { return null; } } public void validate() { if (!androidManifestFile.exists() || !androidManifestFile.isFile()) { throw new RuntimeException(androidManifestFile + " not found or not a file; it should point to your project's AndroidManifest.xml"); } } void parseAndroidManifest() { if (manifestIsParsed) { return; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); InputStream inputStream = androidManifestFile.getInputStream(); Document manifestDocument = db.parse(inputStream); inputStream.close(); if (packageName == null) { packageName = getTagAttributeText(manifestDocument, "manifest", "package"); } versionCode = getTagAttributeIntValue(manifestDocument, "manifest", "android:versionCode", 0); versionName = getTagAttributeText(manifestDocument, "manifest", "android:versionName"); rClassName = packageName + ".R"; applicationName = getTagAttributeText(manifestDocument, "application", "android:name"); applicationLabel = getTagAttributeText(manifestDocument, "application", "android:label"); minSdkVersion = getTagAttributeIntValue(manifestDocument, "uses-sdk", "android:minSdkVersion"); targetSdkVersion = getTagAttributeIntValue(manifestDocument, "uses-sdk", "android:targetSdkVersion"); processName = getTagAttributeText(manifestDocument, "application", "android:process"); if (processName == null) { processName = packageName; } themeRef = getTagAttributeText(manifestDocument, "application", "android:theme"); labelRef = getTagAttributeText(manifestDocument, "application", "android:label"); parseApplicationFlags(manifestDocument); parseReceivers(manifestDocument); parseActivities(manifestDocument); parseApplicationMetaData(manifestDocument); parseContentProviders(manifestDocument); } catch (Exception ignored) { ignored.printStackTrace(); } manifestIsParsed = true; } private void parseContentProviders(Document manifestDocument) { Node application = manifestDocument.getElementsByTagName("application").item(0); if (application == null) return; for (Node contentProviderNode : getChildrenTags(application, "provider")) { Node nameItem = contentProviderNode.getAttributes().getNamedItem("android:name"); Node authorityItem = contentProviderNode.getAttributes().getNamedItem("android:authorities"); if (nameItem != null && authorityItem != null) { providers.add(new ContentProviderData(resolveClassRef(nameItem.getTextContent()), authorityItem.getTextContent())); } } } private void parseReceivers(final Document manifestDocument) { Node application = manifestDocument.getElementsByTagName("application").item(0); if (application == null) return; for (Node receiverNode : getChildrenTags(application, "receiver")) { Node namedItem = receiverNode.getAttributes().getNamedItem("android:name"); if (namedItem == null) continue; String receiverName = resolveClassRef(namedItem.getTextContent()); MetaData metaData = new MetaData(getChildrenTags(receiverNode, "meta-data")); for (Node intentFilterNode : getChildrenTags(receiverNode, "intent-filter")) { List<String> actions = new ArrayList<String>(); for (Node actionNode : getChildrenTags(intentFilterNode, "action")) { Node nameNode = actionNode.getAttributes().getNamedItem("android:name"); if (nameNode != null) { actions.add(nameNode.getTextContent()); } } receivers.add(new ReceiverAndIntentFilter(receiverName, actions, metaData)); } } } private void parseActivities(final Document manifestDocument) { Node application = manifestDocument.getElementsByTagName("application").item(0); if (application == null) return; for (Node activityNode : getChildrenTags(application, "activity")) { final NamedNodeMap attributes = activityNode.getAttributes(); final int attrCount = attributes.getLength(); final List<IntentFilterData> intentFilterData = parseIntentFilters(activityNode); final HashMap<String, String> activityAttrs = new HashMap<String, String>(attrCount); for(int i = 0; i < attrCount; i++) { Node attr = attributes.item(i); String v = attr.getNodeValue(); if( v != null) { activityAttrs.put(attr.getNodeName(), v); } } String activityName = resolveClassRef(activityAttrs.get(ActivityData.getNameAttr("android"))); if (activityName == null) { continue; } activityAttrs.put(ActivityData.getNameAttr("android"), activityName); activityDatas.put(activityName, new ActivityData(activityAttrs, intentFilterData)); } } private List<IntentFilterData> parseIntentFilters(final Node activityNode) { ArrayList<IntentFilterData> intentFilterDatas = new ArrayList<IntentFilterData>(); for (Node n : getChildrenTags(activityNode, "intent-filter")) { ArrayList<String> actionNames = new ArrayList<String>(); ArrayList<String> categories = new ArrayList<String>(); //should only be one action. for (Node action : getChildrenTags(n, "action")) { NamedNodeMap attributes = action.getAttributes(); Node actionNameNode = attributes.getNamedItem("android:name"); if (actionNameNode != null) { actionNames.add(actionNameNode.getNodeValue()); } } for (Node category : getChildrenTags(n, "category")) { NamedNodeMap attributes = category.getAttributes(); Node categoryNameNode = attributes.getNamedItem("android:name"); if (categoryNameNode != null) { categories.add(categoryNameNode.getNodeValue()); } } intentFilterDatas.add(new IntentFilterData(actionNames, categories)); } return intentFilterDatas; } /*** * Attempt to parse a string in to it's appropriate type * @param value Value to parse * @return Parsed result */ private static Object parseValue(String value) { if (value == null) { return null; } else if ("true".equals(value)) { return true; } else if ("false".equals(value)) { return false; } else if (value.startsWith("#")) { // if it's a color, add it and continue try { return Color.parseColor(value); } catch (IllegalArgumentException e) { /* Not a color */ } } else if (value.contains(".")) { // most likely a float try { return Float.parseFloat(value); } catch (NumberFormatException e) { // Not a float } } else { // if it's an int, add it and continue try { return Integer.parseInt(value); } catch (NumberFormatException ei) { // Not an int } } // Not one of the above types, keep as String return value; } /*** * Allows {@link org.robolectric.res.builder.RobolectricPackageManager} to provide * a resource index for initialising the resource attributes in all the metadata elements * @param resLoader used for getting resource IDs from string identifiers */ public void initMetaData(ResourceLoader resLoader) { applicationMetaData.init(resLoader, packageName); for (ReceiverAndIntentFilter receiver : receivers) { receiver.metaData.init(resLoader, packageName); } } private void parseApplicationMetaData(final Document manifestDocument) { Node application = manifestDocument.getElementsByTagName("application").item(0); if (application == null) return; applicationMetaData = new MetaData(getChildrenTags(application, "meta-data")); } private String resolveClassRef(String maybePartialClassName) { return (maybePartialClassName.startsWith(".")) ? packageName + maybePartialClassName : maybePartialClassName; } private List<Node> getChildrenTags(final Node node, final String tagName) { List<Node> children = new ArrayList<Node>(); for (int i = 0; i < node.getChildNodes().getLength(); i++) { Node childNode = node.getChildNodes().item(i); if (childNode.getNodeName().equalsIgnoreCase(tagName)) { children.add(childNode); } } return children; } private void parseApplicationFlags(final Document manifestDocument) { applicationFlags = getApplicationFlag(manifestDocument, "android:allowBackup", FLAG_ALLOW_BACKUP); applicationFlags += getApplicationFlag(manifestDocument, "android:allowClearUserData", FLAG_ALLOW_CLEAR_USER_DATA); applicationFlags += getApplicationFlag(manifestDocument, "android:allowTaskReparenting", FLAG_ALLOW_TASK_REPARENTING); applicationFlags += getApplicationFlag(manifestDocument, "android:debuggable", FLAG_DEBUGGABLE); applicationFlags += getApplicationFlag(manifestDocument, "android:hasCode", FLAG_HAS_CODE); applicationFlags += getApplicationFlag(manifestDocument, "android:killAfterRestore", FLAG_KILL_AFTER_RESTORE); applicationFlags += getApplicationFlag(manifestDocument, "android:persistent", FLAG_PERSISTENT); applicationFlags += getApplicationFlag(manifestDocument, "android:resizeable", FLAG_RESIZEABLE_FOR_SCREENS); applicationFlags += getApplicationFlag(manifestDocument, "android:restoreAnyVersion", FLAG_RESTORE_ANY_VERSION); applicationFlags += getApplicationFlag(manifestDocument, "android:largeScreens", FLAG_SUPPORTS_LARGE_SCREENS); applicationFlags += getApplicationFlag(manifestDocument, "android:normalScreens", FLAG_SUPPORTS_NORMAL_SCREENS); applicationFlags += getApplicationFlag(manifestDocument, "android:anyDensity", FLAG_SUPPORTS_SCREEN_DENSITIES); applicationFlags += getApplicationFlag(manifestDocument, "android:smallScreens", FLAG_SUPPORTS_SMALL_SCREENS); applicationFlags += getApplicationFlag(manifestDocument, "android:testOnly", FLAG_TEST_ONLY); applicationFlags += getApplicationFlag(manifestDocument, "android:vmSafeMode", FLAG_VM_SAFE_MODE); } private int getApplicationFlag(final Document doc, final String attribute, final int attributeValue) { String flagString = getTagAttributeText(doc, "application", attribute); return "true".equalsIgnoreCase(flagString) ? attributeValue : 0; } private Integer getTagAttributeIntValue(final Document doc, final String tag, final String attribute) { return getTagAttributeIntValue(doc, tag, attribute, null); } private Integer getTagAttributeIntValue(final Document doc, final String tag, final String attribute, final Integer defaultValue) { String valueString = getTagAttributeText(doc, tag, attribute); if (valueString != null) { return Integer.parseInt(valueString); } return defaultValue; } public String getApplicationName() { parseAndroidManifest(); return applicationName; } public String getActivityLabel(Class<? extends Activity> activity) { parseAndroidManifest(); ActivityData data = getActivityData(activity.getName()); return (data != null && data.getLabel() != null) ? data.getLabel() : applicationLabel; } public void setPackageName(String packageName) { this.packageName = packageName; } public String getPackageName() { parseAndroidManifest(); return packageName; } public int getVersionCode() { return versionCode; } public String getVersionName() { return versionName; } public String getLabelRef() { return labelRef; } public int getMinSdkVersion() { parseAndroidManifest(); return minSdkVersion == null ? 1 : minSdkVersion; } public int getTargetSdkVersion() { parseAndroidManifest(); return targetSdkVersion == null ? getMinSdkVersion() : targetSdkVersion; } public int getApplicationFlags() { parseAndroidManifest(); return applicationFlags; } public String getProcessName() { parseAndroidManifest(); return processName; } public Map<String, Object> getApplicationMetaData() { parseAndroidManifest(); return applicationMetaData.valueMap; } public ResourcePath getResourcePath() { validate(); return new ResourcePath(getRClass(), getPackageName(), resDirectory, assetsDirectory); } public List<ResourcePath> getIncludedResourcePaths() { Collection<ResourcePath> resourcePaths = new LinkedHashSet<ResourcePath>(); // Needs stable ordering and no duplicates resourcePaths.add(getResourcePath()); for (AndroidManifest libraryManifest : getLibraryManifests()) { resourcePaths.addAll(libraryManifest.getIncludedResourcePaths()); } return Lists.newArrayList(resourcePaths); } public List<ContentProviderData> getContentProviders() { parseAndroidManifest(); return providers; } protected void createLibraryManifests() { libraryManifests = new ArrayList<AndroidManifest>(); List<FsFile> libraryBaseDirs = findLibraries(); for (FsFile libraryBaseDir : libraryBaseDirs) { AndroidManifest libraryManifest = createLibraryAndroidManifest(libraryBaseDir); libraryManifest.createLibraryManifests(); libraryManifests.add(libraryManifest); } } protected List<FsFile> findLibraries() { FsFile baseDir = getBaseDir(); List<FsFile> libraryBaseDirs = new ArrayList<FsFile>(); Properties properties = getProperties(baseDir.join("project.properties")); // get the project.properties overrides and apply them (if any) Properties overrideProperties = getProperties(baseDir.join("test-project.properties")); if (overrideProperties!=null) properties.putAll(overrideProperties); if (properties != null) { int libRef = 1; String lib; while ((lib = properties.getProperty("android.library.reference." + libRef)) != null) { FsFile libraryBaseDir = baseDir.join(lib); if (libraryBaseDir.isDirectory()) { // Ignore directories without any files FsFile[] libraryBaseDirFiles = libraryBaseDir.listFiles(); if (libraryBaseDirFiles != null && libraryBaseDirFiles.length > 0) { libraryBaseDirs.add(libraryBaseDir); } } libRef++; } } return libraryBaseDirs; } protected FsFile getBaseDir() { return getResDirectory().getParent(); } protected AndroidManifest createLibraryAndroidManifest(FsFile libraryBaseDir) { return new AndroidManifest(libraryBaseDir); } public List<AndroidManifest> getLibraryManifests() { if (libraryManifests == null) createLibraryManifests(); return Collections.unmodifiableList(libraryManifests); } private static Properties getProperties(FsFile propertiesFile) { if (!propertiesFile.exists()) return null; Properties properties = new Properties(); InputStream stream; try { stream = propertiesFile.getInputStream(); } catch (IOException e) { throw new RuntimeException(e); } try { try { properties.load(stream); } finally { stream.close(); } } catch (IOException e) { throw new RuntimeException(e); } return properties; } public FsFile getResDirectory() { return resDirectory; } public FsFile getAssetsDirectory() { return assetsDirectory; } public int getReceiverCount() { parseAndroidManifest(); return receivers.size(); } public String getReceiverClassName(final int receiverIndex) { parseAndroidManifest(); return receivers.get(receiverIndex).getBroadcastReceiverClassName(); } public List<String> getReceiverIntentFilterActions(final int receiverIndex) { parseAndroidManifest(); return receivers.get(receiverIndex).getIntentFilterActions(); } public Map<String, Object> getReceiverMetaData(final int receiverIndex) { parseAndroidManifest(); return receivers.get(receiverIndex).getMetaData().valueMap; } private static String getTagAttributeText(final Document doc, final String tag, final String attribute) { NodeList elementsByTagName = doc.getElementsByTagName(tag); for (int i = 0; i < elementsByTagName.getLength(); ++i) { Node item = elementsByTagName.item(i); Node namedItem = item.getAttributes().getNamedItem(attribute); if (namedItem != null) { return namedItem.getTextContent(); } } return null; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AndroidManifest that = (AndroidManifest) o; if (androidManifestFile != null ? !androidManifestFile.equals(that.androidManifestFile) : that.androidManifestFile != null) return false; if (assetsDirectory != null ? !assetsDirectory.equals(that.assetsDirectory) : that.assetsDirectory != null) return false; if (resDirectory != null ? !resDirectory.equals(that.resDirectory) : that.resDirectory != null) return false; return true; } @Override public int hashCode() { int result = androidManifestFile != null ? androidManifestFile.hashCode() : 0; result = 31 * result + (resDirectory != null ? resDirectory.hashCode() : 0); result = 31 * result + (assetsDirectory != null ? assetsDirectory.hashCode() : 0); return result; } public ActivityData getActivityData(String activityClassName) { return activityDatas.get(activityClassName); } public String getThemeRef() { return themeRef; } public Map<String, ActivityData> getActivityDatas() { parseAndroidManifest(); return activityDatas; } private static final class MetaData { private final Map<String, Object> valueMap = new LinkedHashMap<String, Object>(); private final Map<String, VALUE_TYPE> typeMap = new LinkedHashMap<String, VALUE_TYPE>(); private boolean initialised; public MetaData(List<Node> nodes) { for (Node metaNode : nodes) { NamedNodeMap attributes = metaNode.getAttributes(); Node nameAttr = attributes.getNamedItem("android:name"); Node valueAttr = attributes.getNamedItem("android:value"); Node resourceAttr = attributes.getNamedItem("android:resource"); if (valueAttr != null) { valueMap.put(nameAttr.getNodeValue(), valueAttr.getNodeValue()); typeMap.put(nameAttr.getNodeValue(), VALUE_TYPE.VALUE); } else if (resourceAttr != null) { valueMap.put(nameAttr.getNodeValue(), resourceAttr.getNodeValue()); typeMap.put(nameAttr.getNodeValue(), VALUE_TYPE.RESOURCE); } } } public void init(ResourceLoader resLoader, String packageName) { ResourceIndex resIndex = resLoader.getResourceIndex(); if (!initialised) { for (Map.Entry<String,MetaData.VALUE_TYPE> entry : typeMap.entrySet()) { String value = valueMap.get(entry.getKey()).toString(); if (value.startsWith("@")) { ResName resName = ResName.qualifyResName(value.substring(1), packageName, null); switch (entry.getValue()) { case RESOURCE: // Was provided by resource attribute, store resource ID valueMap.put(entry.getKey(), resIndex.getResourceId(resName)); break; case VALUE: // Was provided by value attribute, need to parse it TypedResource<?> typedRes = resLoader.getValue(resName, ""); // The typed resource's data is always a String, so need to parse the value. switch (typedRes.getResType()) { case BOOLEAN: case COLOR: case INTEGER: case FLOAT: valueMap.put(entry.getKey(),parseValue(typedRes.getData().toString())); break; default: valueMap.put(entry.getKey(),typedRes.getData()); } break; } } else if (entry.getValue() == MetaData.VALUE_TYPE.VALUE) { // Raw value, so parse it in to the appropriate type and store it valueMap.put(entry.getKey(), parseValue(value)); } } // Finished parsing, mark as initialised initialised = true; } } private enum VALUE_TYPE { RESOURCE, VALUE } } private static class ReceiverAndIntentFilter { private final List<String> intentFilterActions; private final String broadcastReceiverClassName; private final MetaData metaData; public ReceiverAndIntentFilter(final String broadcastReceiverClassName, final List<String> intentFilterActions, final MetaData metaData) { this.broadcastReceiverClassName = broadcastReceiverClassName; this.intentFilterActions = intentFilterActions; this.metaData = metaData; } public String getBroadcastReceiverClassName() { return broadcastReceiverClassName; } public List<String> getIntentFilterActions() { return intentFilterActions; } public MetaData getMetaData() { return metaData; } } }
src/main/java/org/robolectric/AndroidManifest.java
package org.robolectric; import android.app.Activity; import android.graphics.Color; import org.fest.util.Lists; import org.robolectric.res.*; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import static android.content.pm.ApplicationInfo.FLAG_ALLOW_BACKUP; import static android.content.pm.ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA; import static android.content.pm.ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING; import static android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE; import static android.content.pm.ApplicationInfo.FLAG_HAS_CODE; import static android.content.pm.ApplicationInfo.FLAG_KILL_AFTER_RESTORE; import static android.content.pm.ApplicationInfo.FLAG_PERSISTENT; import static android.content.pm.ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS; import static android.content.pm.ApplicationInfo.FLAG_RESTORE_ANY_VERSION; import static android.content.pm.ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS; import static android.content.pm.ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS; import static android.content.pm.ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES; import static android.content.pm.ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS; import static android.content.pm.ApplicationInfo.FLAG_TEST_ONLY; import static android.content.pm.ApplicationInfo.FLAG_VM_SAFE_MODE; public class AndroidManifest { private final FsFile androidManifestFile; private final FsFile resDirectory; private final FsFile assetsDirectory; private boolean manifestIsParsed; private String applicationName; private String applicationLabel; private String rClassName; private String packageName; private String processName; private String themeRef; private String labelRef; private Integer targetSdkVersion; private Integer minSdkVersion; private int versionCode; private String versionName; private int applicationFlags; private final List<ContentProviderData> providers = new ArrayList<ContentProviderData>(); private final List<ReceiverAndIntentFilter> receivers = new ArrayList<ReceiverAndIntentFilter>(); private final Map<String, ActivityData> activityDatas = new LinkedHashMap<String, ActivityData>(); private MetaData applicationMetaData; private List<AndroidManifest> libraryManifests; /** * Creates a Robolectric configuration using default Android files relative to the specified base directory. * <p/> * The manifest will be baseDir/AndroidManifest.xml, res will be baseDir/res, and assets in baseDir/assets. * * @param baseDir the base directory of your Android project * @deprecated Use {@link #AndroidManifest(org.robolectric.res.FsFile, org.robolectric.res.FsFile, org.robolectric.res.FsFile)} instead.} */ public AndroidManifest(final File baseDir) { this(Fs.newFile(baseDir)); } public AndroidManifest(final FsFile androidManifestFile, final FsFile resDirectory) { this(androidManifestFile, resDirectory, resDirectory.getParent().join("assets")); } /** * @deprecated Use {@link #AndroidManifest(org.robolectric.res.FsFile, org.robolectric.res.FsFile, org.robolectric.res.FsFile)} instead.} */ public AndroidManifest(final FsFile baseDir) { this(baseDir.join("AndroidManifest.xml"), baseDir.join("res"), baseDir.join("assets")); } /** * Creates a Robolectric configuration using specified locations. * * @param androidManifestFile location of the AndroidManifest.xml file * @param resDirectory location of the res directory * @param assetsDirectory location of the assets directory */ public AndroidManifest(FsFile androidManifestFile, FsFile resDirectory, FsFile assetsDirectory) { this.androidManifestFile = androidManifestFile; this.resDirectory = resDirectory; this.assetsDirectory = assetsDirectory; } public String getThemeRef(Class<? extends Activity> activityClass) { ActivityData activityData = getActivityData(activityClass.getName()); String themeRef = activityData != null ? activityData.getThemeRef() : null; if (themeRef == null) { themeRef = getThemeRef(); } return themeRef; } public String getRClassName() throws Exception { parseAndroidManifest(); return rClassName; } public Class getRClass() { try { String rClassName = getRClassName(); return Class.forName(rClassName); } catch (Exception e) { return null; } } public void validate() { if (!androidManifestFile.exists() || !androidManifestFile.isFile()) { throw new RuntimeException(androidManifestFile + " not found or not a file; it should point to your project's AndroidManifest.xml"); } } void parseAndroidManifest() { if (manifestIsParsed) { return; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); InputStream inputStream = androidManifestFile.getInputStream(); Document manifestDocument = db.parse(inputStream); inputStream.close(); if (packageName == null) { packageName = getTagAttributeText(manifestDocument, "manifest", "package"); } versionCode = getTagAttributeIntValue(manifestDocument, "manifest", "android:versionCode", 0); versionName = getTagAttributeText(manifestDocument, "manifest", "android:versionName"); rClassName = packageName + ".R"; applicationName = getTagAttributeText(manifestDocument, "application", "android:name"); applicationLabel = getTagAttributeText(manifestDocument, "application", "android:label"); minSdkVersion = getTagAttributeIntValue(manifestDocument, "uses-sdk", "android:minSdkVersion"); targetSdkVersion = getTagAttributeIntValue(manifestDocument, "uses-sdk", "android:targetSdkVersion"); processName = getTagAttributeText(manifestDocument, "application", "android:process"); if (processName == null) { processName = packageName; } themeRef = getTagAttributeText(manifestDocument, "application", "android:theme"); labelRef = getTagAttributeText(manifestDocument, "application", "android:label"); parseApplicationFlags(manifestDocument); parseReceivers(manifestDocument); parseActivities(manifestDocument); parseApplicationMetaData(manifestDocument); parseContentProviders(manifestDocument); } catch (Exception ignored) { ignored.printStackTrace(); } manifestIsParsed = true; } private void parseContentProviders(Document manifestDocument) { Node application = manifestDocument.getElementsByTagName("application").item(0); if (application == null) return; for (Node contentProviderNode : getChildrenTags(application, "provider")) { Node nameItem = contentProviderNode.getAttributes().getNamedItem("android:name"); Node authorityItem = contentProviderNode.getAttributes().getNamedItem("android:authorities"); if (nameItem != null && authorityItem != null) { providers.add(new ContentProviderData(resolveClassRef(nameItem.getTextContent()), authorityItem.getTextContent())); } } } private void parseReceivers(final Document manifestDocument) { Node application = manifestDocument.getElementsByTagName("application").item(0); if (application == null) return; for (Node receiverNode : getChildrenTags(application, "receiver")) { Node namedItem = receiverNode.getAttributes().getNamedItem("android:name"); if (namedItem == null) continue; String receiverName = resolveClassRef(namedItem.getTextContent()); MetaData metaData = new MetaData(getChildrenTags(receiverNode, "meta-data")); for (Node intentFilterNode : getChildrenTags(receiverNode, "intent-filter")) { List<String> actions = new ArrayList<String>(); for (Node actionNode : getChildrenTags(intentFilterNode, "action")) { Node nameNode = actionNode.getAttributes().getNamedItem("android:name"); if (nameNode != null) { actions.add(nameNode.getTextContent()); } } receivers.add(new ReceiverAndIntentFilter(receiverName, actions, metaData)); } } } private void parseActivities(final Document manifestDocument) { Node application = manifestDocument.getElementsByTagName("application").item(0); if (application == null) return; for (Node activityNode : getChildrenTags(application, "activity")) { final NamedNodeMap attributes = activityNode.getAttributes(); final int attrCount = attributes.getLength(); final List<IntentFilterData> intentFilterData = parseIntentFilters(activityNode); final HashMap<String, String> activityAttrs = new HashMap<String, String>(attrCount); for(int i = 0; i < attrCount; i++) { Node attr = attributes.item(i); String v = attr.getNodeValue(); if( v != null) { activityAttrs.put(attr.getNodeName(), v); } } String activityName = resolveClassRef(activityAttrs.get(ActivityData.getNameAttr("android"))); if (activityName == null) { continue; } activityAttrs.put(ActivityData.getNameAttr("android"), activityName); activityDatas.put(activityName, new ActivityData(activityAttrs, intentFilterData)); } } private List<IntentFilterData> parseIntentFilters(final Node activityNode) { ArrayList<IntentFilterData> intentFilterDatas = new ArrayList<IntentFilterData>(); for (Node n : getChildrenTags(activityNode, "intent-filter")) { ArrayList<String> actionNames = new ArrayList<String>(); ArrayList<String> categories = new ArrayList<String>(); //should only be one action. for (Node action : getChildrenTags(n, "action")) { NamedNodeMap attributes = action.getAttributes(); Node actionNameNode = attributes.getNamedItem("android:name"); if (actionNameNode != null) { actionNames.add(actionNameNode.getNodeValue()); } } for (Node category : getChildrenTags(n, "category")) { NamedNodeMap attributes = category.getAttributes(); Node categoryNameNode = attributes.getNamedItem("android:name"); if (categoryNameNode != null) { categories.add(categoryNameNode.getNodeValue()); } } intentFilterDatas.add(new IntentFilterData(actionNames, categories)); } return intentFilterDatas; } /*** * Attempt to parse a string in to it's appropriate type * @param value Value to parse * @return Parsed result */ private static Object parseValue(String value) { if (value == null) { return null; } else if ("true".equals(value)) { return true; } else if ("false".equals(value)) { return false; } else if (value.startsWith("#")) { // if it's a color, add it and continue try { return Color.parseColor(value); } catch (IllegalArgumentException e) { /* Not a color */ } } else if (value.contains(".")) { // most likely a float try { return Float.parseFloat(value); } catch (NumberFormatException e) { // Not a float } } else { // if it's an int, add it and continue try { return Integer.parseInt(value); } catch (NumberFormatException ei) { // Not an int } } // Not one of the above types, keep as String return value; } /*** * Allows {@link org.robolectric.res.builder.RobolectricPackageManager} to provide * a resource index for initialising the resource attributes in all the metadata elements * @param resLoader used for getting resource IDs from string identifiers */ public void initMetaData(ResourceLoader resLoader) { applicationMetaData.init(resLoader, packageName); for (ReceiverAndIntentFilter receiver : receivers) { receiver.metaData.init(resLoader, packageName); } } private void parseApplicationMetaData(final Document manifestDocument) { Node application = manifestDocument.getElementsByTagName("application").item(0); if (application == null) return; applicationMetaData = new MetaData(getChildrenTags(application, "meta-data")); } private String resolveClassRef(String maybePartialClassName) { return (maybePartialClassName.startsWith(".")) ? packageName + maybePartialClassName : maybePartialClassName; } private List<Node> getChildrenTags(final Node node, final String tagName) { List<Node> children = new ArrayList<Node>(); for (int i = 0; i < node.getChildNodes().getLength(); i++) { Node childNode = node.getChildNodes().item(i); if (childNode.getNodeName().equalsIgnoreCase(tagName)) { children.add(childNode); } } return children; } private void parseApplicationFlags(final Document manifestDocument) { applicationFlags = getApplicationFlag(manifestDocument, "android:allowBackup", FLAG_ALLOW_BACKUP); applicationFlags += getApplicationFlag(manifestDocument, "android:allowClearUserData", FLAG_ALLOW_CLEAR_USER_DATA); applicationFlags += getApplicationFlag(manifestDocument, "android:allowTaskReparenting", FLAG_ALLOW_TASK_REPARENTING); applicationFlags += getApplicationFlag(manifestDocument, "android:debuggable", FLAG_DEBUGGABLE); applicationFlags += getApplicationFlag(manifestDocument, "android:hasCode", FLAG_HAS_CODE); applicationFlags += getApplicationFlag(manifestDocument, "android:killAfterRestore", FLAG_KILL_AFTER_RESTORE); applicationFlags += getApplicationFlag(manifestDocument, "android:persistent", FLAG_PERSISTENT); applicationFlags += getApplicationFlag(manifestDocument, "android:resizeable", FLAG_RESIZEABLE_FOR_SCREENS); applicationFlags += getApplicationFlag(manifestDocument, "android:restoreAnyVersion", FLAG_RESTORE_ANY_VERSION); applicationFlags += getApplicationFlag(manifestDocument, "android:largeScreens", FLAG_SUPPORTS_LARGE_SCREENS); applicationFlags += getApplicationFlag(manifestDocument, "android:normalScreens", FLAG_SUPPORTS_NORMAL_SCREENS); applicationFlags += getApplicationFlag(manifestDocument, "android:anyDensity", FLAG_SUPPORTS_SCREEN_DENSITIES); applicationFlags += getApplicationFlag(manifestDocument, "android:smallScreens", FLAG_SUPPORTS_SMALL_SCREENS); applicationFlags += getApplicationFlag(manifestDocument, "android:testOnly", FLAG_TEST_ONLY); applicationFlags += getApplicationFlag(manifestDocument, "android:vmSafeMode", FLAG_VM_SAFE_MODE); } private int getApplicationFlag(final Document doc, final String attribute, final int attributeValue) { String flagString = getTagAttributeText(doc, "application", attribute); return "true".equalsIgnoreCase(flagString) ? attributeValue : 0; } private Integer getTagAttributeIntValue(final Document doc, final String tag, final String attribute) { return getTagAttributeIntValue(doc, tag, attribute, null); } private Integer getTagAttributeIntValue(final Document doc, final String tag, final String attribute, final Integer defaultValue) { String valueString = getTagAttributeText(doc, tag, attribute); if (valueString != null) { return Integer.parseInt(valueString); } return defaultValue; } public String getApplicationName() { parseAndroidManifest(); return applicationName; } public String getActivityLabel(Class<? extends Activity> activity) { parseAndroidManifest(); ActivityData data = getActivityData(activity.getName()); return (data != null && data.getLabel() != null) ? data.getLabel() : applicationLabel; } public void setPackageName(String packageName) { this.packageName = packageName; } public String getPackageName() { parseAndroidManifest(); return packageName; } public int getVersionCode() { return versionCode; } public String getVersionName() { return versionName; } public String getLabelRef() { return labelRef; } public int getMinSdkVersion() { parseAndroidManifest(); return minSdkVersion == null ? 1 : minSdkVersion; } public int getTargetSdkVersion() { parseAndroidManifest(); return targetSdkVersion == null ? getMinSdkVersion() : targetSdkVersion; } public int getApplicationFlags() { parseAndroidManifest(); return applicationFlags; } public String getProcessName() { parseAndroidManifest(); return processName; } public Map<String, Object> getApplicationMetaData() { parseAndroidManifest(); return applicationMetaData.valueMap; } public ResourcePath getResourcePath() { validate(); return new ResourcePath(getRClass(), getPackageName(), resDirectory, assetsDirectory); } public List<ResourcePath> getIncludedResourcePaths() { Collection<ResourcePath> resourcePaths = new LinkedHashSet<ResourcePath>(); // Needs stable ordering and no duplicates resourcePaths.add(getResourcePath()); for (AndroidManifest libraryManifest : getLibraryManifests()) { resourcePaths.addAll(libraryManifest.getIncludedResourcePaths()); } return Lists.newArrayList(resourcePaths); } public List<ContentProviderData> getContentProviders() { parseAndroidManifest(); return providers; } protected void createLibraryManifests() { libraryManifests = new ArrayList<AndroidManifest>(); List<FsFile> libraryBaseDirs = findLibraries(); for (FsFile libraryBaseDir : libraryBaseDirs) { AndroidManifest libraryManifest = createLibraryAndroidManifest(libraryBaseDir); libraryManifest.createLibraryManifests(); libraryManifests.add(libraryManifest); } } protected List<FsFile> findLibraries() { FsFile baseDir = getBaseDir(); List<FsFile> libraryBaseDirs = new ArrayList<FsFile>(); Properties properties = getProperties(baseDir.join("project.properties")); // get the project.properties overrides and apply them (if any) Properties overrideProperties = getProperties(baseDir.join("test-project.properties")); if (overrideProperties!=null) properties.putAll(overrideProperties); if (properties != null) { int libRef = 1; String lib; while ((lib = properties.getProperty("android.library.reference." + libRef)) != null) { FsFile libraryBaseDir = baseDir.join(lib); if (libraryBaseDir.exists()) { libraryBaseDirs.add(libraryBaseDir); } libRef++; } } return libraryBaseDirs; } protected FsFile getBaseDir() { return getResDirectory().getParent(); } protected AndroidManifest createLibraryAndroidManifest(FsFile libraryBaseDir) { return new AndroidManifest(libraryBaseDir); } public List<AndroidManifest> getLibraryManifests() { if (libraryManifests == null) createLibraryManifests(); return Collections.unmodifiableList(libraryManifests); } private static Properties getProperties(FsFile propertiesFile) { if (!propertiesFile.exists()) return null; Properties properties = new Properties(); InputStream stream; try { stream = propertiesFile.getInputStream(); } catch (IOException e) { throw new RuntimeException(e); } try { try { properties.load(stream); } finally { stream.close(); } } catch (IOException e) { throw new RuntimeException(e); } return properties; } public FsFile getResDirectory() { return resDirectory; } public FsFile getAssetsDirectory() { return assetsDirectory; } public int getReceiverCount() { parseAndroidManifest(); return receivers.size(); } public String getReceiverClassName(final int receiverIndex) { parseAndroidManifest(); return receivers.get(receiverIndex).getBroadcastReceiverClassName(); } public List<String> getReceiverIntentFilterActions(final int receiverIndex) { parseAndroidManifest(); return receivers.get(receiverIndex).getIntentFilterActions(); } public Map<String, Object> getReceiverMetaData(final int receiverIndex) { parseAndroidManifest(); return receivers.get(receiverIndex).getMetaData().valueMap; } private static String getTagAttributeText(final Document doc, final String tag, final String attribute) { NodeList elementsByTagName = doc.getElementsByTagName(tag); for (int i = 0; i < elementsByTagName.getLength(); ++i) { Node item = elementsByTagName.item(i); Node namedItem = item.getAttributes().getNamedItem(attribute); if (namedItem != null) { return namedItem.getTextContent(); } } return null; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AndroidManifest that = (AndroidManifest) o; if (androidManifestFile != null ? !androidManifestFile.equals(that.androidManifestFile) : that.androidManifestFile != null) return false; if (assetsDirectory != null ? !assetsDirectory.equals(that.assetsDirectory) : that.assetsDirectory != null) return false; if (resDirectory != null ? !resDirectory.equals(that.resDirectory) : that.resDirectory != null) return false; return true; } @Override public int hashCode() { int result = androidManifestFile != null ? androidManifestFile.hashCode() : 0; result = 31 * result + (resDirectory != null ? resDirectory.hashCode() : 0); result = 31 * result + (assetsDirectory != null ? assetsDirectory.hashCode() : 0); return result; } public ActivityData getActivityData(String activityClassName) { return activityDatas.get(activityClassName); } public String getThemeRef() { return themeRef; } public Map<String, ActivityData> getActivityDatas() { parseAndroidManifest(); return activityDatas; } private static final class MetaData { private final Map<String, Object> valueMap = new LinkedHashMap<String, Object>(); private final Map<String, VALUE_TYPE> typeMap = new LinkedHashMap<String, VALUE_TYPE>(); private boolean initialised; public MetaData(List<Node> nodes) { for (Node metaNode : nodes) { NamedNodeMap attributes = metaNode.getAttributes(); Node nameAttr = attributes.getNamedItem("android:name"); Node valueAttr = attributes.getNamedItem("android:value"); Node resourceAttr = attributes.getNamedItem("android:resource"); if (valueAttr != null) { valueMap.put(nameAttr.getNodeValue(), valueAttr.getNodeValue()); typeMap.put(nameAttr.getNodeValue(), VALUE_TYPE.VALUE); } else if (resourceAttr != null) { valueMap.put(nameAttr.getNodeValue(), resourceAttr.getNodeValue()); typeMap.put(nameAttr.getNodeValue(), VALUE_TYPE.RESOURCE); } } } public void init(ResourceLoader resLoader, String packageName) { ResourceIndex resIndex = resLoader.getResourceIndex(); if (!initialised) { for (Map.Entry<String,MetaData.VALUE_TYPE> entry : typeMap.entrySet()) { String value = valueMap.get(entry.getKey()).toString(); if (value.startsWith("@")) { ResName resName = ResName.qualifyResName(value.substring(1), packageName, null); switch (entry.getValue()) { case RESOURCE: // Was provided by resource attribute, store resource ID valueMap.put(entry.getKey(), resIndex.getResourceId(resName)); break; case VALUE: // Was provided by value attribute, need to parse it TypedResource<?> typedRes = resLoader.getValue(resName, ""); // The typed resource's data is always a String, so need to parse the value. switch (typedRes.getResType()) { case BOOLEAN: case COLOR: case INTEGER: case FLOAT: valueMap.put(entry.getKey(),parseValue(typedRes.getData().toString())); break; default: valueMap.put(entry.getKey(),typedRes.getData()); } break; } } else if (entry.getValue() == MetaData.VALUE_TYPE.VALUE) { // Raw value, so parse it in to the appropriate type and store it valueMap.put(entry.getKey(), parseValue(value)); } } // Finished parsing, mark as initialised initialised = true; } } private enum VALUE_TYPE { RESOURCE, VALUE } } private static class ReceiverAndIntentFilter { private final List<String> intentFilterActions; private final String broadcastReceiverClassName; private final MetaData metaData; public ReceiverAndIntentFilter(final String broadcastReceiverClassName, final List<String> intentFilterActions, final MetaData metaData) { this.broadcastReceiverClassName = broadcastReceiverClassName; this.intentFilterActions = intentFilterActions; this.metaData = metaData; } public String getBroadcastReceiverClassName() { return broadcastReceiverClassName; } public List<String> getIntentFilterActions() { return intentFilterActions; } public MetaData getMetaData() { return metaData; } } }
Ignore empty library directories when parsing project.properties. Closes #1057. Fixes #973.
src/main/java/org/robolectric/AndroidManifest.java
Ignore empty library directories when parsing project.properties.
Java
mit
b3bcba82ebffa43deb7e0a4d24fea04a3568705d
0
binaryoverload/FlareBot,FlareBot/FlareBot
package stream.flarebot.flarebot; import io.prometheus.client.Histogram; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.OnlineStatus; import net.dv8tion.jda.core.Permission; import net.dv8tion.jda.core.entities.*; import net.dv8tion.jda.core.events.DisconnectEvent; import net.dv8tion.jda.core.events.Event; import net.dv8tion.jda.core.events.ReadyEvent; import net.dv8tion.jda.core.events.StatusChangeEvent; import net.dv8tion.jda.core.events.guild.GuildJoinEvent; import net.dv8tion.jda.core.events.guild.GuildLeaveEvent; import net.dv8tion.jda.core.events.guild.member.GuildMemberJoinEvent; import net.dv8tion.jda.core.events.guild.voice.GuildVoiceJoinEvent; import net.dv8tion.jda.core.events.guild.voice.GuildVoiceLeaveEvent; import net.dv8tion.jda.core.events.guild.voice.GuildVoiceMoveEvent; import net.dv8tion.jda.core.events.message.guild.GenericGuildMessageEvent; import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.core.events.message.react.MessageReactionAddEvent; import net.dv8tion.jda.core.events.role.RoleDeleteEvent; import net.dv8tion.jda.core.events.user.UserOnlineStatusUpdateEvent; import net.dv8tion.jda.core.exceptions.InsufficientPermissionException; import net.dv8tion.jda.core.hooks.ListenerAdapter; import okhttp3.Request; import okhttp3.RequestBody; import org.json.JSONObject; import org.slf4j.Logger; import stream.flarebot.flarebot.commands.Command; import stream.flarebot.flarebot.commands.CommandType; import stream.flarebot.flarebot.commands.music.SkipCommand; import stream.flarebot.flarebot.commands.secret.update.UpdateCommand; import stream.flarebot.flarebot.database.RedisController; import stream.flarebot.flarebot.metrics.Metrics; import stream.flarebot.flarebot.mod.modlog.ModlogEvent; import stream.flarebot.flarebot.mod.modlog.ModlogHandler; import stream.flarebot.flarebot.objects.GuildWrapper; import stream.flarebot.flarebot.objects.PlayerCache; import stream.flarebot.flarebot.objects.Welcome; import stream.flarebot.flarebot.util.Constants; import stream.flarebot.flarebot.util.MessageUtils; import stream.flarebot.flarebot.util.WebUtils; import stream.flarebot.flarebot.util.buttons.ButtonUtil; import stream.flarebot.flarebot.util.errorhandling.Markers; import stream.flarebot.flarebot.util.general.GeneralUtils; import stream.flarebot.flarebot.util.general.GuildUtils; import stream.flarebot.flarebot.util.general.VariableUtils; import stream.flarebot.flarebot.util.objects.ButtonGroup; import stream.flarebot.flarebot.util.votes.VoteUtil; import java.awt.*; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.util.*; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; import java.util.stream.Collectors; public class Events extends ListenerAdapter { public static final ThreadGroup COMMAND_THREADS = new ThreadGroup("Command Threads"); private static final ExecutorService COMMAND_POOL = Executors.newFixedThreadPool(4, r -> new Thread(COMMAND_THREADS, r, "Command Pool-" + COMMAND_THREADS.activeCount())); private static final List<Long> removedByMe = new ArrayList<>(); private final Logger LOGGER = FlareBot.getLog(this.getClass()); private final Pattern multiSpace = Pattern.compile(" {2,}"); private FlareBot flareBot; private Map<String, Integer> spamMap = new ConcurrentHashMap<>(); private final Map<Integer, Long> shardEventTime = new HashMap<>(); private final AtomicInteger commandCounter = new AtomicInteger(0); private Map<Long, Double> maxButtonClicksPerSec = new HashMap<>(); private Map<Long, List<Double>> buttonClicksPerSec = new HashMap<>(); Events(FlareBot bot) { this.flareBot = bot; } @Override public void onMessageReactionAdd(MessageReactionAddEvent event) { if (!event.getGuild().getSelfMember().hasPermission(event.getTextChannel(), Permission.MESSAGE_READ)) return; if (event.getUser().isBot()) return; if (ButtonUtil.isButtonMessage(event.getMessageId())) { for (ButtonGroup.Button button : ButtonUtil.getButtonGroup(event.getMessageId()).getButtons()) { if ((event.getReactionEmote() != null && event.getReactionEmote().isEmote() && event.getReactionEmote().getIdLong() == button.getEmoteId()) || (button.getUnicode() != null && event.getReactionEmote().getName().equals(button.getUnicode()))) { try { event.getChannel().getMessageById(event.getMessageId()).queue(message -> { for (MessageReaction reaction : message.getReactions()) { if (reaction.getReactionEmote().equals(event.getReactionEmote())) { reaction.removeReaction(event.getUser()).queue(); } } }); } catch (InsufficientPermissionException e) { event.getGuild().getOwner().getUser().openPrivateChannel().queue(privateChannel -> { privateChannel.sendMessage("I cannot remove reactions from messages in the channel: " + event.getChannel().getName() + "! Please give me the `MESSAGE_HISTORY` permission to allow me to do this!").queue(); }, ignored -> {}); } button.onClick(ButtonUtil.getButtonGroup(event.getMessageId()).getOwner(), event.getUser()); String emote = event.getReactionEmote() != null ? event.getReactionEmote().getName() + "(" + event.getReactionEmote().getId() + ")" : button.getUnicode(); Metrics.buttonsPressed.labels(emote, ButtonUtil.getButtonGroup(event.getMessageId()).getName()).inc(); if (!event.getGuild().getSelfMember().hasPermission(Permission.MESSAGE_MANAGE)) { return; } return; } } } if (!FlareBotManager.instance().getGuild(event.getGuild().getId()).getBetaAccess()) return; if (!event.getReactionEmote().getName().equals("\uD83D\uDCCC")) return; // Check if it's a :pushpin: event.getChannel().getMessageById(event.getMessageId()).queue(message -> { MessageReaction reaction = message.getReactions().stream().filter(r -> r.getReactionEmote().getName() .equals(event.getReactionEmote().getName())).findFirst().orElse(null); if (reaction != null) { if (reaction.getCount() == 5) { message.pin().queue((aVoid) -> event.getChannel().getHistory().retrievePast(1).complete().get(0) .delete().queue()); } } }); } @Override public void onReady(ReadyEvent event) { if (FlareBot.instance().isReady()) FlareBot.instance().run(); } @Override public void onGuildMemberJoin(GuildMemberJoinEvent event) { if (event.getMember().getUser().isBot() || event.getMember().getUser().isFake()) return; PlayerCache cache = flareBot.getPlayerCache(event.getMember().getUser().getId()); cache.setLastSeen(LocalDateTime.now()); GuildWrapper wrapper = FlareBotManager.instance().getGuild(event.getGuild().getId()); if (wrapper == null) return; if (wrapper.isBlocked()) return; if (flareBot.getManager().getGuild(event.getGuild().getId()).getWelcome() != null) { Welcome welcome = wrapper.getWelcome(); if ((welcome.getChannelId() != null && Getters.getChannelById(welcome.getChannelId()) != null) || welcome.isDmEnabled()) { if (welcome.getChannelId() != null && Getters.getChannelById(welcome.getChannelId()) != null && welcome.isGuildEnabled()) { TextChannel channel = Getters.getChannelById(welcome.getChannelId()); if (channel == null || !channel.canTalk()) { welcome.setGuildEnabled(false); MessageUtils.sendPM(event.getGuild().getOwner().getUser(), "Cannot send welcome messages in " + (channel == null ? welcome.getChannelId() : channel.getAsMention()) + " due to this, welcomes have been disabled!"); return; } if (welcome.isGuildEnabled()) { String guildMsg = VariableUtils.parseVariables(welcome.getRandomGuildMessage(), wrapper, null, event.getUser()); // Deprecated values guildMsg = guildMsg .replace("%user%", event.getMember().getUser().getName()) .replace("%guild%", event.getGuild().getName()) .replace("%mention%", event.getMember().getUser().getAsMention()); channel.sendMessage(guildMsg).queue(); if (guildMsg.contains("%user%") || guildMsg.contains("%guild%") || guildMsg.contains("%mention%")) { MessageUtils.sendPM(event.getGuild().getOwner().getUser(), "Your guild welcome message contains deprecated variables! " + "Please check the docs at the link below for a list of all the " + "variables you can use!\n" + "https://docs.flarebot.stream/variables"); } } } if (welcome.isDmEnabled()) { if (event.getMember().getUser().isBot()) return; // We can't DM other bots. String dmMsg = VariableUtils.parseVariables(welcome.getRandomDmMessage(), wrapper, null, event.getUser()); // Deprecated values dmMsg = dmMsg .replace("%user%", event.getMember().getUser().getName()) .replace("%guild%", event.getGuild().getName()) .replace("%mention%", event.getMember().getUser().getAsMention()); MessageUtils.sendPM(event.getMember().getUser(), dmMsg); if (dmMsg.contains("%user%") || dmMsg.contains("%guild%") || dmMsg.contains("%mention%")) { MessageUtils.sendPM(event.getGuild().getOwner().getUser(), "Your DM welcome message contains deprecated variables! " + "Please check the docs at the link below for a list of all the " + "variables you can use!\n" + "https://docs.flarebot.stream/variables"); } } } else welcome.setGuildEnabled(false); } if (event.getMember().getUser().isBot()) return; if (!wrapper.getAutoAssignRoles().isEmpty()) { Set<String> autoAssignRoles = wrapper.getAutoAssignRoles(); List<Role> roles = new ArrayList<>(); for (String s : autoAssignRoles) { Role role = event.getGuild().getRoleById(s); if (role != null) { roles.add(role); } else autoAssignRoles.remove(s); } try { event.getGuild().getController().addRolesToMember(event.getMember(), roles).queue((n) -> { }, e1 -> handle(e1, event, roles)); StringBuilder sb = new StringBuilder("```\n"); for (Role role : roles) { sb.append(role.getName()).append(" (").append(role.getId()).append(")\n"); } sb.append("```"); ModlogHandler.getInstance().postToModlog(wrapper, ModlogEvent.FLAREBOT_AUTOASSIGN_ROLE, event.getUser(), new MessageEmbed.Field("Roles", sb.toString(), false)); } catch (Exception e1) { handle(e1, event, roles); } } } private void handle(Throwable e1, GuildMemberJoinEvent event, List<Role> roles) { if (!e1.getMessage().startsWith("Can't modify a role with higher")) { MessageUtils.sendPM(event.getGuild().getOwner().getUser(), "**Could not auto assign a role!**\n" + e1.getMessage()); return; } MessageUtils.sendPM(event.getGuild().getOwner().getUser(), "**Hello!\nI am here to tell you that I could not give the role(s) ```\n" + roles.stream().map(Role::getName).collect(Collectors.joining("\n")) + "\n``` to one of your new users!\n" + "Please move one of the following roles so they are higher up than any of the above: \n```" + event.getGuild().getSelfMember().getRoles().stream() .map(Role::getName) .collect(Collectors.joining("\n")) + "``` in your server's role tab!**"); } @Override public void onGuildJoin(GuildJoinEvent event) { if (event.getJDA().getStatus() == JDA.Status.CONNECTED && event.getGuild().getSelfMember().getJoinDate().plusMinutes(2).isAfter(OffsetDateTime.now())) { Constants.getGuildLogChannel().sendMessage(new EmbedBuilder() .setColor(new Color(96, 230, 144)) .setThumbnail(event.getGuild().getIconUrl()) .setFooter(event.getGuild().getId(), event.getGuild().getIconUrl()) .setAuthor(event.getGuild().getName(), null, event.getGuild().getIconUrl()) .setTimestamp(event.getGuild().getSelfMember().getJoinDate()) .setDescription("Guild Created: `" + event.getGuild().getName() + "` :smile: :heart:\n" + "Guild Owner: " + event.getGuild().getOwner().getUser().getName() + "\nGuild Members: " + event.getGuild().getMembers().size()).build()).queue(); } } @Override public void onGuildLeave(GuildLeaveEvent event) { Constants.getGuildLogChannel().sendMessage(new EmbedBuilder() .setColor(new Color(244, 23, 23)) .setThumbnail(event.getGuild().getIconUrl()) .setFooter(event.getGuild().getId(), event.getGuild().getIconUrl()) .setTimestamp(OffsetDateTime.now()) .setAuthor(event.getGuild().getName(), null, event.getGuild().getIconUrl()) .setDescription("Guild Deleted: `" + event.getGuild().getName() + "` L :broken_heart:\n" + "Guild Owner: " + (event.getGuild().getOwner() != null ? event.getGuild().getOwner().getUser().getName() : "Non-existent, they had to much L")).build()).queue(); } @Override public void onGuildVoiceJoin(GuildVoiceJoinEvent event) { if (event.getMember().getUser().equals(event.getJDA().getSelfUser()) && flareBot.getMusicManager() .hasPlayer(event.getGuild().getId())) { flareBot.getMusicManager().getPlayer(event.getGuild().getId()).setPaused(false); } if (event.getMember().getUser().equals(event.getJDA().getSelfUser())) return; if (event.getGuild().getSelfMember().getVoiceState().getChannel() == null) return; if (VoteUtil.contains(SkipCommand.getSkipUUID(), event.getGuild()) && event.getChannelJoined().getIdLong() == event.getGuild().getSelfMember().getVoiceState().getChannel().getIdLong()) { VoteUtil.getVoteGroup(SkipCommand.getSkipUUID(), event.getGuild()).addAllowedUser(event.getMember().getUser()); } } @Override public void onGuildVoiceLeave(GuildVoiceLeaveEvent event) { if (event.getMember().getUser().getIdLong() == event.getJDA().getSelfUser().getIdLong()) { if (flareBot.getMusicManager().hasPlayer(event.getGuild().getId())) { flareBot.getMusicManager().getPlayer(event.getGuild().getId()).setPaused(true); } if (Getters.getActiveVoiceChannels() == 0 && FlareBot.NOVOICE_UPDATING.get()) { Constants.getImportantLogChannel() .sendMessage("I am now updating, there are no voice channels active!").queue(); UpdateCommand.update(true, null); } } else { handleVoiceConnectivity(event.getChannelLeft()); } if (event.getMember().getUser().equals(event.getJDA().getSelfUser())) return; if (VoteUtil.contains(SkipCommand.getSkipUUID(), event.getGuild()) && event.getChannelLeft().getIdLong() == event.getGuild().getSelfMember().getVoiceState().getChannel().getIdLong()) { VoteUtil.getVoteGroup(SkipCommand.getSkipUUID(), event.getGuild()).remoreAllowedUser(event.getMember().getUser()); } } private void handleVoiceConnectivity(VoiceChannel channel) { if (channel.getMembers().contains(channel.getGuild().getSelfMember()) && (channel.getMembers().size() < 2 || channel.getMembers() .stream().filter(m -> m.getUser().isBot()).count() == channel.getMembers().size())) { channel.getGuild().getAudioManager().closeAudioConnection(); } } @Override public void onGuildVoiceMove(GuildVoiceMoveEvent event) { handleVoiceConnectivity(event.getChannelJoined()); } @Override public void onGuildMessageReceived(GuildMessageReceivedEvent event) { PlayerCache cache = flareBot.getPlayerCache(event.getAuthor().getId()); cache.setLastMessage(LocalDateTime.from(event.getMessage().getCreationTime())); cache.setLastSeen(LocalDateTime.now()); cache.setLastSpokeGuild(event.getGuild().getId()); if (event.getAuthor().isBot()) return; String message = multiSpace.matcher(event.getMessage().getContentRaw()).replaceAll(" "); if (message.startsWith("" + FlareBotManager.instance().getGuild(getGuildId(event)).getPrefix())) { List<Permission> perms = event.getChannel().getGuild().getSelfMember().getPermissions(event.getChannel()); if (!perms.contains(Permission.ADMINISTRATOR)) { if (!perms.contains(Permission.MESSAGE_WRITE)) { return; } if (!perms.contains(Permission.MESSAGE_EMBED_LINKS)) { event.getChannel().sendMessage("Hey! I can't be used here." + "\nI do not have the `Embed Links` permission! Please go to your permissions and give me Embed Links." + "\nThanks :D").queue(); return; } } String command = message.substring(1); String[] args = new String[0]; if (message.contains(" ")) { command = command.substring(0, message.indexOf(" ") - 1); args = message.substring(message.indexOf(" ") + 1).split(" "); } Command cmd = FlareBot.getCommandManager().getCommand(command, event.getAuthor()); if (cmd != null) handleCommand(event, cmd, args); } else { if (FlareBotManager.instance().getGuild(getGuildId(event)).getPrefix() != Constants.COMMAND_CHAR && (message.startsWith("_prefix")) || message.startsWith(event.getGuild().getSelfMember().getAsMention())) { event.getChannel().sendMessage(MessageUtils.getEmbed(event.getAuthor()) .setDescription("The server prefix is `" + FlareBotManager .instance().getGuild(getGuildId(event)).getPrefix() + "`") .build()).queue(); } if (!message.isEmpty()) { RedisController.set(event.getMessageId(), GeneralUtils.getRedisMessageJson(event.getMessage()), "nx", "ex", 86400); } } } @Override public void onUserOnlineStatusUpdate(UserOnlineStatusUpdateEvent event) { if (event.getPreviousOnlineStatus() == OnlineStatus.OFFLINE) { flareBot.getPlayerCache(event.getUser().getId()).setLastSeen(LocalDateTime.now()); } } @Override public void onStatusChange(StatusChangeEvent event) { if (FlareBot.EXITING.get()) return; String statusHook = FlareBot.getStatusHook(); if (statusHook == null) return; Request.Builder request = new Request.Builder().url(statusHook); RequestBody body = RequestBody.create(WebUtils.APPLICATION_JSON, new JSONObject() .put("content", String.format("onStatusChange: %s -> %s SHARD: %d", event.getOldStatus(), event.getStatus(), event.getJDA().getShardInfo() != null ? event.getJDA().getShardInfo().getShardId() : null)).toString()); WebUtils.postAsync(request.post(body)); } @Override public void onDisconnect(DisconnectEvent event) { if (event.isClosedByServer()) LOGGER.error(Markers.NO_ANNOUNCE, String.format("---- DISCONNECT [SERVER] CODE: [%d] %s%n", event.getServiceCloseFrame() .getCloseCode(), event .getCloseCode())); else LOGGER.error(Markers.NO_ANNOUNCE, String.format("---- DISCONNECT [CLIENT] CODE: [%d] %s%n", event.getClientCloseFrame() .getCloseCode(), event .getClientCloseFrame().getCloseReason())); } @Override public void onRoleDelete(RoleDeleteEvent event) { if (FlareBotManager.instance().getGuild(event.getGuild().getId()) == null) return; if (FlareBotManager.instance().getGuild(event.getGuild().getId()).getSelfAssignRoles().contains(event.getRole().getId())) { FlareBotManager.instance().getGuild(event.getGuild().getId()).getSelfAssignRoles().remove(event.getRole().getId()); } } private void handleCommand(GuildMessageReceivedEvent event, Command cmd, String[] args) { Metrics.commandsReceived.labels(cmd.getClass().getSimpleName()).inc(); GuildWrapper guild = flareBot.getManager().getGuild(event.getGuild().getId()); if (cmd.getType().isInternal()) { if (GeneralUtils.canRunInternalCommand(cmd.getType(), event.getAuthor())) { dispatchCommand(cmd, args, event, guild); return; } else { GeneralUtils.sendImage("https://flarebot.stream/img/trap.jpg", "trap.jpg", event.getAuthor()); Constants.logEG("It's a trap", cmd, guild.getGuild(), event.getAuthor()); return; } } if (guild.hasBetaAccess()) { if ((guild.getSettings().getChannelBlacklist().contains(event.getChannel().getIdLong()) || guild.getSettings().getUserBlacklist().contains(event.getAuthor().getIdLong())) && !guild.getPermissions().hasPermission(event.getMember(), stream.flarebot.flarebot.permissions.Permission.BLACKLIST_BYPASS)) return; } if (guild.isBlocked() && System.currentTimeMillis() > guild.getUnBlockTime() && guild.getUnBlockTime() != -1) guild.revokeBlock(); handleSpamDetection(event, guild); if (guild.isBlocked() && !(cmd.getType() == CommandType.SECRET)) return; if (handleMissingPermission(cmd, event)) return; if (!guild.hasBetaAccess() && cmd.isBetaTesterCommand()) { if (flareBot.isTestBot()) LOGGER.error("Guild " + event.getGuild().getId() + " tried to use the beta command '" + cmd.getCommand() + "'!"); return; } if (FlareBot.UPDATING.get()) { event.getChannel().sendMessage("**Currently updating!**").queue(); return; } if (flareBot.getManager().isCommandDisabled(cmd.getCommand())) { MessageUtils.sendErrorMessage(flareBot.getManager().getDisabledCommandReason(cmd.getCommand()), event.getChannel(), event.getAuthor()); return; } // Internal stuff if (event.getGuild().getId().equals(Constants.OFFICIAL_GUILD) && !handleOfficialGuildStuff(event, cmd)) return; dispatchCommand(cmd, args, event, guild); } private boolean handleOfficialGuildStuff(GuildMessageReceivedEvent event, Command command) { Guild guild = event.getGuild(); GuildWrapper wrapper = FlareBotManager.instance().getGuild(guild.getId()); if (event.getChannel().getIdLong() == 226785954537406464L && !event.getMember().hasPermission(Permission.MESSAGE_MANAGE)) { event.getChannel().sendMessage("Heyo " + event.getAuthor().getAsMention() + " please use me in <#226786507065786380>!").queue(); return false; } return true; } private boolean handleMissingPermission(Command cmd, GuildMessageReceivedEvent e) { if (cmd.getDiscordPermission() != null) { if (!cmd.getDiscordPermission().isEmpty()) if (e.getMember().getPermissions().containsAll(cmd.getDiscordPermission())) return false; } if (cmd.getPermission() != null) { if (!cmd.getPermissions(e.getChannel()).hasPermission(e.getMember(), cmd.getPermission())) { MessageUtils.sendAutoDeletedMessage(MessageUtils.getEmbed(e.getAuthor()).setColor(Color.red) .setDescription("You are missing the permission ``" + cmd .getPermission() + "`` which is required for use of this command!").build(), 5000, e.getChannel()); delete(e.getMessage()); return true; } } return !cmd.getPermissions(e.getChannel()).hasPermission( e.getMember(), stream.flarebot.flarebot.permissions.Permission.getPermission(cmd.getType()) ) && cmd.getPermission() == null && cmd.getType() != CommandType.SECRET; } private void delete(Message message) { if (message.getTextChannel().getGuild().getSelfMember() .getPermissions(message.getTextChannel()).contains(Permission.MESSAGE_MANAGE)) message.delete().queue(); } private String getGuildId(GenericGuildMessageEvent e) { return e.getChannel().getGuild() != null ? e.getChannel().getGuild().getId() : null; } private void handleSpamDetection(GuildMessageReceivedEvent event, GuildWrapper guild) { if (spamMap.containsKey(event.getGuild().getId())) { int messages = spamMap.get(event.getGuild().getId()); double allowed = Math.floor(Math.sqrt(GuildUtils.getGuildUserCount(event.getGuild()) / 2.5)); allowed = allowed == 0 ? 1 : allowed; if (messages > allowed) { if (!guild.isBlocked()) { MessageUtils.sendErrorMessage("We detected command spam in this guild. No commands will be able to " + "be run in this guild for a little bit.", event.getChannel()); guild.addBlocked("Command spam", System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(5)); Metrics.blocksGivenOut.labels(guild.getGuildId()).inc(); } } else { spamMap.put(event.getGuild().getId(), messages + 1); } } else { spamMap.put(event.getGuild().getId(), 1); } } private void dispatchCommand(Command cmd, String[] args, GuildMessageReceivedEvent event, GuildWrapper guild) { COMMAND_POOL.submit(() -> { LOGGER.info( "Dispatching command '" + cmd.getCommand() + "' " + Arrays .toString(args) + " in " + event.getChannel() + "! Sender: " + event.getAuthor().getName() + '#' + event.getAuthor().getDiscriminator()); // We're sending a lot of commands... Let's change the way this works soon :D /*ApiRequester.requestAsync(ApiRoute.DISPATCH_COMMAND, new JSONObject().put("command", cmd.getCommand()) .put("guildId", guild.getGuildId()));*/ commandCounter.incrementAndGet(); try { Histogram.Timer executionTimer = Metrics.commandExecutionTime.labels(cmd.getClass().getSimpleName()).startTimer(); cmd.onCommand(event.getAuthor(), guild, event.getChannel(), event.getMessage(), args, event .getMember()); executionTimer.observeDuration(); Metrics.commandsExecuted.labels(cmd.getClass().getSimpleName()).inc(); MessageEmbed.Field field = null; if (args.length > 0) { String s = MessageUtils.getMessage(args, 0).replaceAll("`", "'"); if (s.length() > 1000) s = s.substring(0, 1000) + "..."; field = new MessageEmbed.Field("Args", "`" + s + "`", false); } ModlogHandler.getInstance().postToModlog(guild, ModlogEvent.FLAREBOT_COMMAND, event.getAuthor(), new MessageEmbed.Field("Channel", event.getChannel().getName() + " (" + event.getChannel().getIdLong() + ")", true), new MessageEmbed.Field("Command", cmd.getCommand(), true), field); } catch (Exception ex) { Metrics.commandExceptions.labels(ex.getClass().getSimpleName()).inc(); MessageUtils.sendException("**There was an internal error trying to execute your command**", ex, event .getChannel()); LOGGER.error("Exception in guild " + event.getGuild().getId() + "!\n" + '\'' + cmd.getCommand() + "' " + Arrays.toString(args) + " in " + event.getChannel() + "! Sender: " + event.getAuthor().getName() + '#' + event.getAuthor().getDiscriminator(), ex); } if ((guild.hasBetaAccess() && cmd.deleteMessage() && guild.getSettings().shouldDeleteCommands()) || cmd.deleteMessage()) { delete(event.getMessage()); removedByMe.add(event.getMessageIdLong()); } }); } public int getCommandCount() { return commandCounter.get(); } @Override public void onGenericEvent(Event e) { shardEventTime.put(e.getJDA().getShardInfo() == null ? 0 : e.getJDA().getShardInfo().getShardId(), System.currentTimeMillis()); } public Map<Integer, Long> getShardEventTime() { return this.shardEventTime; } public Map<String, Integer> getSpamMap() { return spamMap; } public List<Long> getRemovedByMeList() { return removedByMe; } public Map<Long, Double> getMaxButtonClicksPerSec() { return maxButtonClicksPerSec; } public Map<Long, List<Double>> getButtonClicksPerSec() { return buttonClicksPerSec; } }
src/main/java/stream/flarebot/flarebot/Events.java
package stream.flarebot.flarebot; import io.prometheus.client.Histogram; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.OnlineStatus; import net.dv8tion.jda.core.Permission; import net.dv8tion.jda.core.entities.*; import net.dv8tion.jda.core.events.DisconnectEvent; import net.dv8tion.jda.core.events.Event; import net.dv8tion.jda.core.events.ReadyEvent; import net.dv8tion.jda.core.events.StatusChangeEvent; import net.dv8tion.jda.core.events.guild.GuildJoinEvent; import net.dv8tion.jda.core.events.guild.GuildLeaveEvent; import net.dv8tion.jda.core.events.guild.member.GuildMemberJoinEvent; import net.dv8tion.jda.core.events.guild.voice.GuildVoiceJoinEvent; import net.dv8tion.jda.core.events.guild.voice.GuildVoiceLeaveEvent; import net.dv8tion.jda.core.events.guild.voice.GuildVoiceMoveEvent; import net.dv8tion.jda.core.events.message.guild.GenericGuildMessageEvent; import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.core.events.message.react.MessageReactionAddEvent; import net.dv8tion.jda.core.events.role.RoleDeleteEvent; import net.dv8tion.jda.core.events.user.UserOnlineStatusUpdateEvent; import net.dv8tion.jda.core.hooks.ListenerAdapter; import okhttp3.Request; import okhttp3.RequestBody; import org.json.JSONObject; import org.slf4j.Logger; import stream.flarebot.flarebot.commands.Command; import stream.flarebot.flarebot.commands.CommandType; import stream.flarebot.flarebot.commands.music.SkipCommand; import stream.flarebot.flarebot.commands.secret.update.UpdateCommand; import stream.flarebot.flarebot.database.RedisController; import stream.flarebot.flarebot.metrics.Metrics; import stream.flarebot.flarebot.mod.modlog.ModlogEvent; import stream.flarebot.flarebot.mod.modlog.ModlogHandler; import stream.flarebot.flarebot.objects.GuildWrapper; import stream.flarebot.flarebot.objects.PlayerCache; import stream.flarebot.flarebot.objects.Welcome; import stream.flarebot.flarebot.util.Constants; import stream.flarebot.flarebot.util.MessageUtils; import stream.flarebot.flarebot.util.WebUtils; import stream.flarebot.flarebot.util.buttons.ButtonUtil; import stream.flarebot.flarebot.util.errorhandling.Markers; import stream.flarebot.flarebot.util.general.GeneralUtils; import stream.flarebot.flarebot.util.general.GuildUtils; import stream.flarebot.flarebot.util.general.VariableUtils; import stream.flarebot.flarebot.util.objects.ButtonGroup; import stream.flarebot.flarebot.util.votes.VoteUtil; import java.awt.Color; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; import java.util.stream.Collectors; public class Events extends ListenerAdapter { public static final ThreadGroup COMMAND_THREADS = new ThreadGroup("Command Threads"); private static final ExecutorService COMMAND_POOL = Executors.newFixedThreadPool(4, r -> new Thread(COMMAND_THREADS, r, "Command Pool-" + COMMAND_THREADS.activeCount())); private static final List<Long> removedByMe = new ArrayList<>(); private final Logger LOGGER = FlareBot.getLog(this.getClass()); private final Pattern multiSpace = Pattern.compile(" {2,}"); private FlareBot flareBot; private Map<String, Integer> spamMap = new ConcurrentHashMap<>(); private final Map<Integer, Long> shardEventTime = new HashMap<>(); private final AtomicInteger commandCounter = new AtomicInteger(0); private Map<Long, Double> maxButtonClicksPerSec = new HashMap<>(); private Map<Long, List<Double>> buttonClicksPerSec = new HashMap<>(); Events(FlareBot bot) { this.flareBot = bot; } @Override public void onMessageReactionAdd(MessageReactionAddEvent event) { if (!event.getGuild().getSelfMember().hasPermission(event.getTextChannel(), Permission.MESSAGE_READ)) return; if (event.getUser().isBot()) return; if (ButtonUtil.isButtonMessage(event.getMessageId())) { for (ButtonGroup.Button button : ButtonUtil.getButtonGroup(event.getMessageId()).getButtons()) { if ((event.getReactionEmote() != null && event.getReactionEmote().isEmote() && event.getReactionEmote().getIdLong() == button.getEmoteId()) || (button.getUnicode() != null && event.getReactionEmote().getName().equals(button.getUnicode()))) { event.getChannel().getMessageById(event.getMessageId()).queue(message -> { for (MessageReaction reaction : message.getReactions()) { if (reaction.getReactionEmote().equals(event.getReactionEmote())) { reaction.removeReaction(event.getUser()).queue(); } } }); button.onClick(ButtonUtil.getButtonGroup(event.getMessageId()).getOwner(), event.getUser()); String emote = event.getReactionEmote() != null ? event.getReactionEmote().getName() + "(" + event.getReactionEmote().getId() + ")" : button.getUnicode(); Metrics.buttonsPressed.labels(emote, ButtonUtil.getButtonGroup(event.getMessageId()).getName()).inc(); if (!event.getGuild().getSelfMember().hasPermission(Permission.MESSAGE_MANAGE)) { return; } return; } } } if (!FlareBotManager.instance().getGuild(event.getGuild().getId()).getBetaAccess()) return; if (!event.getReactionEmote().getName().equals("\uD83D\uDCCC")) return; // Check if it's a :pushpin: event.getChannel().getMessageById(event.getMessageId()).queue(message -> { MessageReaction reaction = message.getReactions().stream().filter(r -> r.getReactionEmote().getName() .equals(event.getReactionEmote().getName())).findFirst().orElse(null); if (reaction != null) { if (reaction.getCount() == 5) { message.pin().queue((aVoid) -> event.getChannel().getHistory().retrievePast(1).complete().get(0) .delete().queue()); } } }); } @Override public void onReady(ReadyEvent event) { if (FlareBot.instance().isReady()) FlareBot.instance().run(); } @Override public void onGuildMemberJoin(GuildMemberJoinEvent event) { if (event.getMember().getUser().isBot() || event.getMember().getUser().isFake()) return; PlayerCache cache = flareBot.getPlayerCache(event.getMember().getUser().getId()); cache.setLastSeen(LocalDateTime.now()); GuildWrapper wrapper = FlareBotManager.instance().getGuild(event.getGuild().getId()); if (wrapper == null) return; if (wrapper.isBlocked()) return; if (flareBot.getManager().getGuild(event.getGuild().getId()).getWelcome() != null) { Welcome welcome = wrapper.getWelcome(); if ((welcome.getChannelId() != null && Getters.getChannelById(welcome.getChannelId()) != null) || welcome.isDmEnabled()) { if (welcome.getChannelId() != null && Getters.getChannelById(welcome.getChannelId()) != null && welcome.isGuildEnabled()) { TextChannel channel = Getters.getChannelById(welcome.getChannelId()); if (channel == null || !channel.canTalk()) { welcome.setGuildEnabled(false); MessageUtils.sendPM(event.getGuild().getOwner().getUser(), "Cannot send welcome messages in " + (channel == null ? welcome.getChannelId() : channel.getAsMention()) + " due to this, welcomes have been disabled!"); return; } if (welcome.isGuildEnabled()) { String guildMsg = VariableUtils.parseVariables(welcome.getRandomGuildMessage(), wrapper, null, event.getUser()); // Deprecated values guildMsg = guildMsg .replace("%user%", event.getMember().getUser().getName()) .replace("%guild%", event.getGuild().getName()) .replace("%mention%", event.getMember().getUser().getAsMention()); channel.sendMessage(guildMsg).queue(); if (guildMsg.contains("%user%") || guildMsg.contains("%guild%") || guildMsg.contains("%mention%")) { MessageUtils.sendPM(event.getGuild().getOwner().getUser(), "Your guild welcome message contains deprecated variables! " + "Please check the docs at the link below for a list of all the " + "variables you can use!\n" + "https://docs.flarebot.stream/variables"); } } } if (welcome.isDmEnabled()) { if (event.getMember().getUser().isBot()) return; // We can't DM other bots. String dmMsg = VariableUtils.parseVariables(welcome.getRandomDmMessage(), wrapper, null, event.getUser()); // Deprecated values dmMsg = dmMsg .replace("%user%", event.getMember().getUser().getName()) .replace("%guild%", event.getGuild().getName()) .replace("%mention%", event.getMember().getUser().getAsMention()); MessageUtils.sendPM(event.getMember().getUser(), dmMsg); if (dmMsg.contains("%user%") || dmMsg.contains("%guild%") || dmMsg.contains("%mention%")) { MessageUtils.sendPM(event.getGuild().getOwner().getUser(), "Your DM welcome message contains deprecated variables! " + "Please check the docs at the link below for a list of all the " + "variables you can use!\n" + "https://docs.flarebot.stream/variables"); } } } else welcome.setGuildEnabled(false); } if (event.getMember().getUser().isBot()) return; if (!wrapper.getAutoAssignRoles().isEmpty()) { Set<String> autoAssignRoles = wrapper.getAutoAssignRoles(); List<Role> roles = new ArrayList<>(); for (String s : autoAssignRoles) { Role role = event.getGuild().getRoleById(s); if (role != null) { roles.add(role); } else autoAssignRoles.remove(s); } try { event.getGuild().getController().addRolesToMember(event.getMember(), roles).queue((n) -> { }, e1 -> handle(e1, event, roles)); StringBuilder sb = new StringBuilder("```\n"); for (Role role : roles) { sb.append(role.getName()).append(" (").append(role.getId()).append(")\n"); } sb.append("```"); ModlogHandler.getInstance().postToModlog(wrapper, ModlogEvent.FLAREBOT_AUTOASSIGN_ROLE, event.getUser(), new MessageEmbed.Field("Roles", sb.toString(), false)); } catch (Exception e1) { handle(e1, event, roles); } } } private void handle(Throwable e1, GuildMemberJoinEvent event, List<Role> roles) { if (!e1.getMessage().startsWith("Can't modify a role with higher")) { MessageUtils.sendPM(event.getGuild().getOwner().getUser(), "**Could not auto assign a role!**\n" + e1.getMessage()); return; } MessageUtils.sendPM(event.getGuild().getOwner().getUser(), "**Hello!\nI am here to tell you that I could not give the role(s) ```\n" + roles.stream().map(Role::getName).collect(Collectors.joining("\n")) + "\n``` to one of your new users!\n" + "Please move one of the following roles so they are higher up than any of the above: \n```" + event.getGuild().getSelfMember().getRoles().stream() .map(Role::getName) .collect(Collectors.joining("\n")) + "``` in your server's role tab!**"); } @Override public void onGuildJoin(GuildJoinEvent event) { if (event.getJDA().getStatus() == JDA.Status.CONNECTED && event.getGuild().getSelfMember().getJoinDate().plusMinutes(2).isAfter(OffsetDateTime.now())) { Constants.getGuildLogChannel().sendMessage(new EmbedBuilder() .setColor(new Color(96, 230, 144)) .setThumbnail(event.getGuild().getIconUrl()) .setFooter(event.getGuild().getId(), event.getGuild().getIconUrl()) .setAuthor(event.getGuild().getName(), null, event.getGuild().getIconUrl()) .setTimestamp(event.getGuild().getSelfMember().getJoinDate()) .setDescription("Guild Created: `" + event.getGuild().getName() + "` :smile: :heart:\n" + "Guild Owner: " + event.getGuild().getOwner().getUser().getName() + "\nGuild Members: " + event.getGuild().getMembers().size()).build()).queue(); } } @Override public void onGuildLeave(GuildLeaveEvent event) { Constants.getGuildLogChannel().sendMessage(new EmbedBuilder() .setColor(new Color(244, 23, 23)) .setThumbnail(event.getGuild().getIconUrl()) .setFooter(event.getGuild().getId(), event.getGuild().getIconUrl()) .setTimestamp(OffsetDateTime.now()) .setAuthor(event.getGuild().getName(), null, event.getGuild().getIconUrl()) .setDescription("Guild Deleted: `" + event.getGuild().getName() + "` L :broken_heart:\n" + "Guild Owner: " + (event.getGuild().getOwner() != null ? event.getGuild().getOwner().getUser().getName() : "Non-existent, they had to much L")).build()).queue(); } @Override public void onGuildVoiceJoin(GuildVoiceJoinEvent event) { if (event.getMember().getUser().equals(event.getJDA().getSelfUser()) && flareBot.getMusicManager() .hasPlayer(event.getGuild().getId())) { flareBot.getMusicManager().getPlayer(event.getGuild().getId()).setPaused(false); } if (event.getMember().getUser().equals(event.getJDA().getSelfUser())) return; if (event.getGuild().getSelfMember().getVoiceState().getChannel() == null) return; if (VoteUtil.contains(SkipCommand.getSkipUUID(), event.getGuild()) && event.getChannelJoined().getIdLong() == event.getGuild().getSelfMember().getVoiceState().getChannel().getIdLong()) { VoteUtil.getVoteGroup(SkipCommand.getSkipUUID(), event.getGuild()).addAllowedUser(event.getMember().getUser()); } } @Override public void onGuildVoiceLeave(GuildVoiceLeaveEvent event) { if (event.getMember().getUser().getIdLong() == event.getJDA().getSelfUser().getIdLong()) { if (flareBot.getMusicManager().hasPlayer(event.getGuild().getId())) { flareBot.getMusicManager().getPlayer(event.getGuild().getId()).setPaused(true); } if (Getters.getActiveVoiceChannels() == 0 && FlareBot.NOVOICE_UPDATING.get()) { Constants.getImportantLogChannel() .sendMessage("I am now updating, there are no voice channels active!").queue(); UpdateCommand.update(true, null); } } else { handleVoiceConnectivity(event.getChannelLeft()); } if (event.getMember().getUser().equals(event.getJDA().getSelfUser())) return; if (VoteUtil.contains(SkipCommand.getSkipUUID(), event.getGuild()) && event.getChannelLeft().getIdLong() == event.getGuild().getSelfMember().getVoiceState().getChannel().getIdLong()) { VoteUtil.getVoteGroup(SkipCommand.getSkipUUID(), event.getGuild()).remoreAllowedUser(event.getMember().getUser()); } } private void handleVoiceConnectivity(VoiceChannel channel) { if (channel.getMembers().contains(channel.getGuild().getSelfMember()) && (channel.getMembers().size() < 2 || channel.getMembers() .stream().filter(m -> m.getUser().isBot()).count() == channel.getMembers().size())) { channel.getGuild().getAudioManager().closeAudioConnection(); } } @Override public void onGuildVoiceMove(GuildVoiceMoveEvent event) { handleVoiceConnectivity(event.getChannelJoined()); } @Override public void onGuildMessageReceived(GuildMessageReceivedEvent event) { PlayerCache cache = flareBot.getPlayerCache(event.getAuthor().getId()); cache.setLastMessage(LocalDateTime.from(event.getMessage().getCreationTime())); cache.setLastSeen(LocalDateTime.now()); cache.setLastSpokeGuild(event.getGuild().getId()); if (event.getAuthor().isBot()) return; String message = multiSpace.matcher(event.getMessage().getContentRaw()).replaceAll(" "); if (message.startsWith("" + FlareBotManager.instance().getGuild(getGuildId(event)).getPrefix())) { List<Permission> perms = event.getChannel().getGuild().getSelfMember().getPermissions(event.getChannel()); if (!perms.contains(Permission.ADMINISTRATOR)) { if (!perms.contains(Permission.MESSAGE_WRITE)) { return; } if (!perms.contains(Permission.MESSAGE_EMBED_LINKS)) { event.getChannel().sendMessage("Hey! I can't be used here." + "\nI do not have the `Embed Links` permission! Please go to your permissions and give me Embed Links." + "\nThanks :D").queue(); return; } } String command = message.substring(1); String[] args = new String[0]; if (message.contains(" ")) { command = command.substring(0, message.indexOf(" ") - 1); args = message.substring(message.indexOf(" ") + 1).split(" "); } Command cmd = FlareBot.getCommandManager().getCommand(command, event.getAuthor()); if (cmd != null) handleCommand(event, cmd, args); } else { if (FlareBotManager.instance().getGuild(getGuildId(event)).getPrefix() != Constants.COMMAND_CHAR && (message.startsWith("_prefix")) || message.startsWith(event.getGuild().getSelfMember().getAsMention())) { event.getChannel().sendMessage(MessageUtils.getEmbed(event.getAuthor()) .setDescription("The server prefix is `" + FlareBotManager .instance().getGuild(getGuildId(event)).getPrefix() + "`") .build()).queue(); } if (!message.isEmpty()) { RedisController.set(event.getMessageId(), GeneralUtils.getRedisMessageJson(event.getMessage()), "nx", "ex", 86400); } } } @Override public void onUserOnlineStatusUpdate(UserOnlineStatusUpdateEvent event) { if (event.getPreviousOnlineStatus() == OnlineStatus.OFFLINE) { flareBot.getPlayerCache(event.getUser().getId()).setLastSeen(LocalDateTime.now()); } } @Override public void onStatusChange(StatusChangeEvent event) { if (FlareBot.EXITING.get()) return; String statusHook = FlareBot.getStatusHook(); if (statusHook == null) return; Request.Builder request = new Request.Builder().url(statusHook); RequestBody body = RequestBody.create(WebUtils.APPLICATION_JSON, new JSONObject() .put("content", String.format("onStatusChange: %s -> %s SHARD: %d", event.getOldStatus(), event.getStatus(), event.getJDA().getShardInfo() != null ? event.getJDA().getShardInfo().getShardId() : null)).toString()); WebUtils.postAsync(request.post(body)); } @Override public void onDisconnect(DisconnectEvent event) { if (event.isClosedByServer()) LOGGER.error(Markers.NO_ANNOUNCE, String.format("---- DISCONNECT [SERVER] CODE: [%d] %s%n", event.getServiceCloseFrame() .getCloseCode(), event .getCloseCode())); else LOGGER.error(Markers.NO_ANNOUNCE, String.format("---- DISCONNECT [CLIENT] CODE: [%d] %s%n", event.getClientCloseFrame() .getCloseCode(), event .getClientCloseFrame().getCloseReason())); } @Override public void onRoleDelete(RoleDeleteEvent event) { if (FlareBotManager.instance().getGuild(event.getGuild().getId()) == null) return; if (FlareBotManager.instance().getGuild(event.getGuild().getId()).getSelfAssignRoles().contains(event.getRole().getId())) { FlareBotManager.instance().getGuild(event.getGuild().getId()).getSelfAssignRoles().remove(event.getRole().getId()); } } private void handleCommand(GuildMessageReceivedEvent event, Command cmd, String[] args) { Metrics.commandsReceived.labels(cmd.getClass().getSimpleName()).inc(); GuildWrapper guild = flareBot.getManager().getGuild(event.getGuild().getId()); if (cmd.getType().isInternal()) { if (GeneralUtils.canRunInternalCommand(cmd.getType(), event.getAuthor())) { dispatchCommand(cmd, args, event, guild); return; } else { GeneralUtils.sendImage("https://flarebot.stream/img/trap.jpg", "trap.jpg", event.getAuthor()); Constants.logEG("It's a trap", cmd, guild.getGuild(), event.getAuthor()); return; } } if (guild.hasBetaAccess()) { if ((guild.getSettings().getChannelBlacklist().contains(event.getChannel().getIdLong()) || guild.getSettings().getUserBlacklist().contains(event.getAuthor().getIdLong())) && !guild.getPermissions().hasPermission(event.getMember(), stream.flarebot.flarebot.permissions.Permission.BLACKLIST_BYPASS)) return; } if (guild.isBlocked() && System.currentTimeMillis() > guild.getUnBlockTime() && guild.getUnBlockTime() != -1) guild.revokeBlock(); handleSpamDetection(event, guild); if (guild.isBlocked() && !(cmd.getType() == CommandType.SECRET)) return; if (handleMissingPermission(cmd, event)) return; if (!guild.hasBetaAccess() && cmd.isBetaTesterCommand()) { if (flareBot.isTestBot()) LOGGER.error("Guild " + event.getGuild().getId() + " tried to use the beta command '" + cmd.getCommand() + "'!"); return; } if (FlareBot.UPDATING.get()) { event.getChannel().sendMessage("**Currently updating!**").queue(); return; } if (flareBot.getManager().isCommandDisabled(cmd.getCommand())) { MessageUtils.sendErrorMessage(flareBot.getManager().getDisabledCommandReason(cmd.getCommand()), event.getChannel(), event.getAuthor()); return; } // Internal stuff if (event.getGuild().getId().equals(Constants.OFFICIAL_GUILD) && !handleOfficialGuildStuff(event, cmd)) return; dispatchCommand(cmd, args, event, guild); } private boolean handleOfficialGuildStuff(GuildMessageReceivedEvent event, Command command) { Guild guild = event.getGuild(); GuildWrapper wrapper = FlareBotManager.instance().getGuild(guild.getId()); if (event.getChannel().getIdLong() == 226785954537406464L && !event.getMember().hasPermission(Permission.MESSAGE_MANAGE)) { event.getChannel().sendMessage("Heyo " + event.getAuthor().getAsMention() + " please use me in <#226786507065786380>!").queue(); return false; } return true; } private boolean handleMissingPermission(Command cmd, GuildMessageReceivedEvent e) { if (cmd.getDiscordPermission() != null) { if (!cmd.getDiscordPermission().isEmpty()) if (e.getMember().getPermissions().containsAll(cmd.getDiscordPermission())) return false; } if (cmd.getPermission() != null) { if (!cmd.getPermissions(e.getChannel()).hasPermission(e.getMember(), cmd.getPermission())) { MessageUtils.sendAutoDeletedMessage(MessageUtils.getEmbed(e.getAuthor()).setColor(Color.red) .setDescription("You are missing the permission ``" + cmd .getPermission() + "`` which is required for use of this command!").build(), 5000, e.getChannel()); delete(e.getMessage()); return true; } } return !cmd.getPermissions(e.getChannel()).hasPermission( e.getMember(), stream.flarebot.flarebot.permissions.Permission.getPermission(cmd.getType()) ) && cmd.getPermission() == null && cmd.getType() != CommandType.SECRET; } private void delete(Message message) { if (message.getTextChannel().getGuild().getSelfMember() .getPermissions(message.getTextChannel()).contains(Permission.MESSAGE_MANAGE)) message.delete().queue(); } private String getGuildId(GenericGuildMessageEvent e) { return e.getChannel().getGuild() != null ? e.getChannel().getGuild().getId() : null; } private void handleSpamDetection(GuildMessageReceivedEvent event, GuildWrapper guild) { if (spamMap.containsKey(event.getGuild().getId())) { int messages = spamMap.get(event.getGuild().getId()); double allowed = Math.floor(Math.sqrt(GuildUtils.getGuildUserCount(event.getGuild()) / 2.5)); allowed = allowed == 0 ? 1 : allowed; if (messages > allowed) { if (!guild.isBlocked()) { MessageUtils.sendErrorMessage("We detected command spam in this guild. No commands will be able to " + "be run in this guild for a little bit.", event.getChannel()); guild.addBlocked("Command spam", System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(5)); Metrics.blocksGivenOut.labels(guild.getGuildId()).inc(); } } else { spamMap.put(event.getGuild().getId(), messages + 1); } } else { spamMap.put(event.getGuild().getId(), 1); } } private void dispatchCommand(Command cmd, String[] args, GuildMessageReceivedEvent event, GuildWrapper guild) { COMMAND_POOL.submit(() -> { LOGGER.info( "Dispatching command '" + cmd.getCommand() + "' " + Arrays .toString(args) + " in " + event.getChannel() + "! Sender: " + event.getAuthor().getName() + '#' + event.getAuthor().getDiscriminator()); // We're sending a lot of commands... Let's change the way this works soon :D /*ApiRequester.requestAsync(ApiRoute.DISPATCH_COMMAND, new JSONObject().put("command", cmd.getCommand()) .put("guildId", guild.getGuildId()));*/ commandCounter.incrementAndGet(); try { Histogram.Timer executionTimer = Metrics.commandExecutionTime.labels(cmd.getClass().getSimpleName()).startTimer(); cmd.onCommand(event.getAuthor(), guild, event.getChannel(), event.getMessage(), args, event .getMember()); executionTimer.observeDuration(); Metrics.commandsExecuted.labels(cmd.getClass().getSimpleName()).inc(); MessageEmbed.Field field = null; if (args.length > 0) { String s = MessageUtils.getMessage(args, 0).replaceAll("`", "'"); if (s.length() > 1000) s = s.substring(0, 1000) + "..."; field = new MessageEmbed.Field("Args", "`" + s + "`", false); } ModlogHandler.getInstance().postToModlog(guild, ModlogEvent.FLAREBOT_COMMAND, event.getAuthor(), new MessageEmbed.Field("Channel", event.getChannel().getName() + " (" + event.getChannel().getIdLong() + ")", true), new MessageEmbed.Field("Command", cmd.getCommand(), true), field); } catch (Exception ex) { Metrics.commandExceptions.labels(ex.getClass().getSimpleName()).inc(); MessageUtils.sendException("**There was an internal error trying to execute your command**", ex, event .getChannel()); LOGGER.error("Exception in guild " + event.getGuild().getId() + "!\n" + '\'' + cmd.getCommand() + "' " + Arrays.toString(args) + " in " + event.getChannel() + "! Sender: " + event.getAuthor().getName() + '#' + event.getAuthor().getDiscriminator(), ex); } if ((guild.hasBetaAccess() && cmd.deleteMessage() && guild.getSettings().shouldDeleteCommands()) || cmd.deleteMessage()) { delete(event.getMessage()); removedByMe.add(event.getMessageIdLong()); } }); } public int getCommandCount() { return commandCounter.get(); } @Override public void onGenericEvent(Event e) { shardEventTime.put(e.getJDA().getShardInfo() == null ? 0 : e.getJDA().getShardInfo().getShardId(), System.currentTimeMillis()); } public Map<Integer, Long> getShardEventTime() { return this.shardEventTime; } public Map<String, Integer> getSpamMap() { return spamMap; } public List<Long> getRemovedByMeList() { return removedByMe; } public Map<Long, Double> getMaxButtonClicksPerSec() { return maxButtonClicksPerSec; } public Map<Long, List<Double>> getButtonClicksPerSec() { return buttonClicksPerSec; } }
Catch this
src/main/java/stream/flarebot/flarebot/Events.java
Catch this
Java
mit
b3ba63615a5d03066c4bff6939b9dfa4b2bbf5cb
0
Axellience/vue-gwt,Axellience/vue-gwt,Axellience/vue-gwt,Axellience/vue-gwt
package com.axellience.vuegwt.processors.component.template.parser; import com.axellience.vuegwt.core.annotations.component.Prop; import com.axellience.vuegwt.processors.component.template.parser.context.TemplateParserContext; import com.axellience.vuegwt.processors.component.template.parser.context.localcomponents.LocalComponent; import com.axellience.vuegwt.processors.component.template.parser.context.localcomponents.LocalComponentProp; import com.axellience.vuegwt.processors.component.template.parser.jericho.TemplateParserLoggerProvider; import com.axellience.vuegwt.processors.component.template.parser.result.TemplateExpression; import com.axellience.vuegwt.processors.component.template.parser.result.TemplateParserResult; import com.axellience.vuegwt.processors.component.template.parser.variable.LocalVariableInfo; import com.axellience.vuegwt.processors.component.template.parser.variable.VariableInfo; import com.github.javaparser.JavaParser; import com.github.javaparser.ParseProblemException; import com.github.javaparser.ast.expr.BinaryExpr; import com.github.javaparser.ast.expr.CastExpr; import com.github.javaparser.ast.expr.Expression; import com.github.javaparser.ast.expr.MethodCallExpr; import com.github.javaparser.ast.expr.NameExpr; import com.github.javaparser.ast.nodeTypes.NodeWithType; import com.github.javaparser.ast.type.Type; import com.squareup.javapoet.TypeName; import jsinterop.base.Any; import net.htmlparser.jericho.Attribute; import net.htmlparser.jericho.Attributes; import net.htmlparser.jericho.CharacterReference; import net.htmlparser.jericho.Config; import net.htmlparser.jericho.Element; import net.htmlparser.jericho.OutputDocument; import net.htmlparser.jericho.Segment; import net.htmlparser.jericho.Source; import net.htmlparser.jericho.Tag; import javax.annotation.processing.Messager; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static com.axellience.vuegwt.processors.utils.GeneratorsNameUtil.propNameToAttributeName; import static com.axellience.vuegwt.processors.utils.GeneratorsUtil.stringTypeToTypeName; /** * Parse an HTML Vue GWT template. * <br> * This parser find all the Java expression and process them. It will throw explicit exceptions * if a variable cannot be find in the context. * It also automatically decide of the Java type of a given expression depending on the context * where it is used. * @author Adrien Baron */ public class TemplateParser { private static Pattern VUE_ATTR_PATTERN = Pattern.compile("^(v-|:|@).*"); private static Pattern VUE_MUSTACHE_PATTERN = Pattern.compile("\\{\\{.*?}}"); private TemplateParserContext context; private TemplateParserLogger logger; private TemplateParserResult result; private Attribute currentAttribute; private LocalComponentProp currentProp; private TypeName currentExpressionReturnType; private OutputDocument outputDocument; /** * Parse a given HTML template and return the a result object containing the expressions * and a transformed HTML. * @param htmlTemplate The HTML template to process, as a String * @param context Context of the Component we are currently processing * @param messager Used to report errors in template during Annotation Processing * @return A {@link TemplateParserResult} containing the processed template and expressions */ public TemplateParserResult parseHtmlTemplate(String htmlTemplate, TemplateParserContext context, Messager messager) { this.context = context; this.logger = new TemplateParserLogger(context, messager); initJerichoConfig(this.logger); Source source = new Source(htmlTemplate); outputDocument = new OutputDocument(source); result = new TemplateParserResult(); processImports(source); source.getChildElements().forEach(this::processElement); result.setProcessedTemplate(outputDocument.toString()); return result; } private void initJerichoConfig(TemplateParserLogger logger) { // Allow as many invalid character in attributes as possible Attributes.setDefaultMaxErrorCount(Integer.MAX_VALUE); // Allow any element to be self closing Config.IsHTMLEmptyElementTagRecognised = true; // Use our own logger Config.LoggerProvider = new TemplateParserLoggerProvider(logger); } /** * Add java imports in the template to the context. * @param doc The document to process */ private void processImports(Source doc) { doc .getAllElements() .stream() .filter(element -> "vue-gwt:import".equalsIgnoreCase(element.getName())) .peek(importElement -> { String classAttributeValue = importElement.getAttributeValue("class"); if (classAttributeValue != null) context.addImport(classAttributeValue); }) .forEach(outputDocument::remove); } /** * Recursive method that will process the whole template DOM tree. * @param element Current element being processed */ private void processElement(Element element) { context.setCurrentElement(element); currentProp = null; currentAttribute = null; Attributes attributes = element.getAttributes(); Attribute vForAttribute = attributes != null ? attributes.get("v-for") : null; if (vForAttribute != null) { // Add a context layer for our v-for context.addContextLayer(); // Process the v-for expression, and update our attribute String processedVForValue = processVForValue(vForAttribute.getValue()); outputDocument.replace(vForAttribute.getValueSegment(), processedVForValue); } // Process the element if (attributes != null) processElementAttributes(element); // Process text segments StreamSupport .stream(((Iterable<Segment>) element::getNodeIterator).spliterator(), false) .filter(segment -> !(segment instanceof Tag) && !(segment instanceof CharacterReference)) .filter(segment -> { for (Element child : element.getChildElements()) if (child.encloses(segment)) return false; return true; }) .forEach(this::processTextNode); // Recurse downwards element.getChildElements(). forEach(this::processElement); // After downward recursion, pop the context layer if (vForAttribute != null) context.popContextLayer(); } /** * Process text node to check for {{ }} vue expressions. * @param textSegment Current segment being processed */ private void processTextNode(Segment textSegment) { String elementText = textSegment.toString(); Matcher matcher = VUE_MUSTACHE_PATTERN.matcher(elementText); int lastEnd = 0; StringBuilder newText = new StringBuilder(); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); if (start > 0) newText.append(elementText.substring(lastEnd, start)); currentExpressionReturnType = TypeName.get(String.class); String expressionString = elementText.substring(start + 2, end - 2).trim(); String processedExpression = processExpression(expressionString); newText.append("{{ ").append(processedExpression).append(" }}"); lastEnd = end; } if (lastEnd > 0) { newText.append(elementText.substring(lastEnd)); outputDocument.replace(textSegment, newText.toString()); } } /** * Process an {@link Element} and check for vue attributes. * @param element Current element being processed */ private void processElementAttributes(Element element) { Optional<LocalComponent> localComponent = getLocalComponentForElement(element); // Iterate on element attributes Set<LocalComponentProp> foundProps = new HashSet<>(); for (Attribute attribute : element.getAttributes()) { if ("v-for".equals(attribute.getKey()) || "v-model".equals(attribute.getKey())) continue; Optional<LocalComponentProp> optionalProp = localComponent.flatMap(lc -> lc.getPropForAttribute(attribute.getName())); optionalProp.ifPresent(foundProps::add); if (!VUE_ATTR_PATTERN.matcher(attribute.getKey()).matches()) { optionalProp.ifPresent(this::validateStringPropBinding); continue; } currentAttribute = attribute; currentProp = optionalProp.orElse(null); currentExpressionReturnType = getExpressionReturnTypeForAttribute(attribute); String processedExpression = processExpression(attribute.getValue()); if (attribute.getValueSegment() != null) outputDocument.replace(attribute.getValueSegment(), processedExpression); } localComponent.ifPresent(lc -> validateRequiredProps(lc, foundProps)); } /** * Return the {@link LocalComponent} definition for a given DOM {@link Element} * @param element Current element being processed * @return An Optional {@link LocalComponent} */ private Optional<LocalComponent> getLocalComponentForElement(Element element) { String componentName = element.getAttributes().getValue("is"); if (componentName == null) componentName = element.getStartTag().getName(); return context.getLocalComponent(componentName); } /** * Validate that a {@link Prop} bounded with string binding is of type String * @param localComponentProp The prop to check */ private void validateStringPropBinding(LocalComponentProp localComponentProp) { if (localComponentProp.getType().toString().equals(String.class.getCanonicalName())) return; logger.error("Passing a String to a non String Prop: \"" + localComponentProp.getPropName() + "\". " + "If you want to pass a boolean or an int you should use v-bind. " + "For example: v-bind:my-prop=\"12\" (or using the short syntax, :my-prop=\"12\") instead of my-prop=\"12\"."); } /** * Validate that all the required properties of a local components are present on a the * HTML {@link Element} that represents it. * @param localComponent The {@link LocalComponent} we want to check * @param foundProps The props we found on the HTML {@link Element} during processing */ private void validateRequiredProps(LocalComponent localComponent, Set<LocalComponentProp> foundProps) { String missingRequiredProps = localComponent .getRequiredProps() .stream() .filter(prop -> !foundProps.contains(prop)) .map(prop -> "\"" + propNameToAttributeName(prop.getPropName()) + "\"") .collect(Collectors.joining(",")); if (!missingRequiredProps.isEmpty()) { logger.error("Missing required property: " + missingRequiredProps + " on child component \"" + localComponent.getComponentTagName() + "\""); } } /** * Guess the type of the expression based on where it is used. * The guessed type can be overridden by adding a Cast to the desired type at the * beginning of the expression. * @param attribute The attribute the expression is in * @return */ private TypeName getExpressionReturnTypeForAttribute(Attribute attribute) { String attributeName = attribute.getKey().toLowerCase(); if (attributeName.indexOf("@") == 0 || attributeName.indexOf("v-on:") == 0) return TypeName.VOID; if ("v-if".equals(attributeName) || "v-show".equals(attributeName)) return TypeName.BOOLEAN; if (currentProp != null) return currentProp.getType(); return TypeName.get(Any.class); } /** * Process a v-for value. * It will register the loop variables as a local variable in the context stack. * @param vForValue The value of the v-for attribute * @return A processed v-for value, should be placed in the HTML in place of the original * v-for value */ private String processVForValue(String vForValue) { VForDefinition vForDef = new VForDefinition(vForValue, context, logger); // Set return of the "in" expression currentExpressionReturnType = vForDef.getInExpressionType(); String inExpression = this.processExpression(vForDef.getInExpression()); // And return the newly built definition return vForDef.getVariableDefinition() + " in " + inExpression; } /** * Process a given template expression * @param expressionString Should be either empty or a valid Java expression * @return The processed expression */ private String processExpression(String expressionString) { expressionString = expressionString == null ? "" : expressionString.trim(); if (expressionString.isEmpty()) { if (isAttributeBinding(currentAttribute)) { logger.error( "Empty expression in template property binding. If you want to pass an empty string then simply don't use binding: my-attribute=\"\"", currentAttribute.toString()); } else if (isEventBinding(currentAttribute)) { logger.error("Empty expression in template event binding.", currentAttribute.toString()); } else { return ""; } } if (expressionString.startsWith("{")) logger.error( "Object literal syntax are not supported yet in Vue GWT, please use map(e(\"key1\", myValue), e(\"key2\", myValue2 > 5)...) instead. The object returned by map() is a regular Javascript Object (JsObject) with the given key/values.", expressionString); if (expressionString.startsWith("[")) logger.error( "Array literal syntax are not supported yet in Vue GWT, please use array(myValue, myValue2 > 5...) instead. The object returned by array() is a regular Javascript Array (JsArray) with the given values.", expressionString); if (shouldSkipExpressionProcessing(expressionString)) return expressionString; return processJavaExpression(expressionString).toTemplateString(); } /** * In some cases we want to skip expression processing for optimization. * This is when we are sure the expression is valid and there is no need to create a Java method * for it. * @param expressionString The expression to asses * @return true if we can skip the expression */ private boolean shouldSkipExpressionProcessing(String expressionString) { // We don't skip if it's a component prop as we want Java validation // We don't optimize String expression, as we want GWT to convert Java values // to String for us (Enums, wrapped primitives...) return currentProp == null && !String.class .getCanonicalName() .equals(currentExpressionReturnType.toString()) && isSimpleVueJsExpression( expressionString); } private boolean isAttributeBinding(Attribute attribute) { String attributeName = attribute.getKey().toLowerCase(); return attributeName.startsWith(":") || attributeName.startsWith("v-bind:"); } private boolean isEventBinding(Attribute attribute) { String attributeName = attribute.getKey().toLowerCase(); return attributeName.startsWith("@") || attributeName.startsWith("v-on:"); } /** * In some case the expression is already a valid Vue.js expression that will work without * any processing. In this case we just leave it in place. * This avoid creating Computed properties/methods for simple expressions. * @param expressionString The expression to check * @return true if it's already a valid Vue.js expression, false otherwise */ private boolean isSimpleVueJsExpression(String expressionString) { String methodName = expressionString; if (expressionString.endsWith("()")) methodName = expressionString.substring(0, expressionString.length() - 2); // Just a method name/simple method call with no parameters if (context.hasMethod(methodName)) return true; // Just a variable return context.findVariable(expressionString) != null; } /** * Process the given string as a Java expression. * @param expressionString A valid Java expression * @return A processed expression, should be placed in the HTML in place of the original * expression */ private TemplateExpression processJavaExpression(String expressionString) { Expression expression; try { expression = JavaParser.parseExpression(expressionString); } catch (ParseProblemException parseException) { logger.error("Couldn't parse Expression, make sure it is valid Java.", expressionString); throw parseException; } resolveTypesUsingImports(expression); resolveStaticMethodsUsingImports(expression); checkMethodNames(expression); // Find the parameters used by the expression List<VariableInfo> expressionParameters = new LinkedList<>(); findExpressionParameters(expression, expressionParameters); // If there is a cast first, we use this as the type of our expression if (currentProp == null) expression = getTypeFromCast(expression); // Update the expression as it might have been changed expressionString = expression.toString(); // Add the resulting expression to our result return result.addExpression(expressionString, currentExpressionReturnType, currentProp == null, expressionParameters); } /** * Get the type of an expression from the cast at the beginning. * (int) 12 -> 12 of type int * (int) 15 + 5 -> 15 + 5 of type int * (float) (12 + 3) -> 12 + 3 of type float * ((int) 12) + 3 -> ((int) 12) + 3 of type Any * ((JsArray) myArray).getAt(0) -> ((JsArray) myArray).getAt(0) of type Any * @param expression The expression to process * @return The modified expression (where cast has been removed if necessary) */ private Expression getTypeFromCast(Expression expression) { if (expression instanceof BinaryExpr) { Expression mostLeft = getLeftmostExpression(expression); if (mostLeft instanceof CastExpr) { CastExpr castExpr = (CastExpr) mostLeft; currentExpressionReturnType = stringTypeToTypeName(castExpr.getType().toString()); BinaryExpr parent = (BinaryExpr) mostLeft.getParentNode().get(); parent.setLeft(castExpr.getExpression()); } } else if (expression instanceof CastExpr) { CastExpr castExpr = (CastExpr) expression; currentExpressionReturnType = stringTypeToTypeName(castExpr.getType().toString()); expression = castExpr.getExpression(); } return expression; } private Expression getLeftmostExpression(Expression expression) { if (expression instanceof BinaryExpr) return getLeftmostExpression(((BinaryExpr) expression).getLeft()); return expression; } /** * Resolve all the types in the expression. * This will replace the Class with the full qualified name using the template imports. * @param expression A Java expression from the Template */ private void resolveTypesUsingImports(Expression expression) { if (expression instanceof NodeWithType) { NodeWithType nodeWithType = ((NodeWithType) expression); nodeWithType.setType(getQualifiedName(nodeWithType.getType())); } // Recurse downward in the expression expression .getChildNodes() .stream() .filter(Expression.class::isInstance) .map(Expression.class::cast) .forEach(this::resolveTypesUsingImports); } /** * Resolve static method calls using static imports * @param expression The expression to resolve */ private void resolveStaticMethodsUsingImports(Expression expression) { if (expression instanceof MethodCallExpr) { MethodCallExpr methodCall = ((MethodCallExpr) expression); String methodName = methodCall.getName().getIdentifier(); if (!methodCall.getScope().isPresent() && context.hasStaticMethod(methodName)) { methodCall.setName(context.getFullyQualifiedNameForMethodName(methodName)); } } // Recurse downward in the expression expression .getChildNodes() .stream() .filter(Expression.class::isInstance) .map(Expression.class::cast) .forEach(this::resolveStaticMethodsUsingImports); } /** * Check the expression for component method calls. * This will check that the methods used in the template exist in the Component. * It throws an exception if we use a method that is not declared in our Component. * This will not check for the type or number of parameters, we leave that to the Java Compiler. * @param expression The expression to check */ private void checkMethodNames(Expression expression) { if (expression instanceof MethodCallExpr) { MethodCallExpr methodCall = ((MethodCallExpr) expression); if (!methodCall.getScope().isPresent()) { String methodName = methodCall.getName().getIdentifier(); if (!context.hasMethod(methodName) && !context.hasStaticMethod(methodName)) { logger.error("Couldn't find the method \"" + methodName + "\" in the Component. " + "Make sure it is not private or try rerunning your Annotation processor.", expression.toString()); } } } for (com.github.javaparser.ast.Node node : expression.getChildNodes()) { if (!(node instanceof Expression)) continue; Expression childExpr = (Expression) node; checkMethodNames(childExpr); } } /** * Find all the parameters this expression depends on. * This is either the local variables (from a v-for loop) or the $event variable. * @param expression An expression from the Template * @param parameters The parameters this expression depends on */ private void findExpressionParameters(Expression expression, List<VariableInfo> parameters) { if (expression instanceof NameExpr) { NameExpr nameExpr = ((NameExpr) expression); if ("$event".equals(nameExpr.getNameAsString())) processEventParameter(expression, nameExpr, parameters); else processNameExpression(expression, nameExpr, parameters); } expression .getChildNodes() .stream() .filter(Expression.class::isInstance) .map(Expression.class::cast) .forEach(exp -> findExpressionParameters(exp, parameters)); } /** * Process the $event variable passed on v-on. This variable must have a valid cast in front. * @param expression The currently processed expression * @param nameExpr The variable we are processing * @param parameters The parameters this expression depends on */ private void processEventParameter(Expression expression, NameExpr nameExpr, List<VariableInfo> parameters) { if (nameExpr.getParentNode().isPresent() && nameExpr .getParentNode() .get() instanceof CastExpr) { CastExpr castExpr = (CastExpr) nameExpr.getParentNode().get(); parameters.add(new VariableInfo(castExpr.getType().toString(), "$event")); } else { logger.error( "\"$event\" should always be casted to it's intended type. Example: @click=\"doSomething((NativeEvent) $event)\".", expression.toString()); } } /** * Process a name expression to determine if it exists in the context. * If it does, and it's a local variable (from a v-for) we add it to our parameters * @param expression The currently processed expression * @param nameExpr The variable we are processing * @param parameters The parameters this expression depends on */ private void processNameExpression(Expression expression, NameExpr nameExpr, List<VariableInfo> parameters) { String name = nameExpr.getNameAsString(); if (context.hasImport(name)) { // This is a direct Class reference, we just replace with the fully qualified name nameExpr.setName(context.getFullyQualifiedNameForClassName(name)); return; } VariableInfo variableInfo = context.findVariable(name); if (variableInfo == null) { logger.error("Couldn't find variable/method \"" + name + "\" in the Component. Make sure you didn't forget the @JsProperty/@JsMethod annotation.", expression.toString()); } if (variableInfo instanceof LocalVariableInfo) { parameters.add(variableInfo); } } private String getQualifiedName(Type type) { return context.getFullyQualifiedNameForClassName(type.toString()); } }
processors/src/main/java/com/axellience/vuegwt/processors/component/template/parser/TemplateParser.java
package com.axellience.vuegwt.processors.component.template.parser; import com.axellience.vuegwt.core.annotations.component.Prop; import com.axellience.vuegwt.processors.component.template.parser.context.TemplateParserContext; import com.axellience.vuegwt.processors.component.template.parser.context.localcomponents.LocalComponent; import com.axellience.vuegwt.processors.component.template.parser.context.localcomponents.LocalComponentProp; import com.axellience.vuegwt.processors.component.template.parser.jericho.TemplateParserLoggerProvider; import com.axellience.vuegwt.processors.component.template.parser.result.TemplateExpression; import com.axellience.vuegwt.processors.component.template.parser.result.TemplateParserResult; import com.axellience.vuegwt.processors.component.template.parser.variable.LocalVariableInfo; import com.axellience.vuegwt.processors.component.template.parser.variable.VariableInfo; import com.github.javaparser.JavaParser; import com.github.javaparser.ParseProblemException; import com.github.javaparser.ast.expr.BinaryExpr; import com.github.javaparser.ast.expr.CastExpr; import com.github.javaparser.ast.expr.Expression; import com.github.javaparser.ast.expr.MethodCallExpr; import com.github.javaparser.ast.expr.NameExpr; import com.github.javaparser.ast.nodeTypes.NodeWithType; import com.github.javaparser.ast.type.Type; import com.squareup.javapoet.TypeName; import jsinterop.base.Any; import net.htmlparser.jericho.Attribute; import net.htmlparser.jericho.Attributes; import net.htmlparser.jericho.CharacterReference; import net.htmlparser.jericho.Config; import net.htmlparser.jericho.Element; import net.htmlparser.jericho.OutputDocument; import net.htmlparser.jericho.Segment; import net.htmlparser.jericho.Source; import net.htmlparser.jericho.Tag; import javax.annotation.processing.Messager; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static com.axellience.vuegwt.processors.utils.GeneratorsNameUtil.propNameToAttributeName; import static com.axellience.vuegwt.processors.utils.GeneratorsUtil.stringTypeToTypeName; /** * Parse an HTML Vue GWT template. * <br> * This parser find all the Java expression and process them. It will throw explicit exceptions * if a variable cannot be find in the context. * It also automatically decide of the Java type of a given expression depending on the context * where it is used. * @author Adrien Baron */ public class TemplateParser { private static Pattern VUE_ATTR_PATTERN = Pattern.compile("^(v-|:|@).*"); private static Pattern VUE_MUSTACHE_PATTERN = Pattern.compile("\\{\\{.*?}}"); private TemplateParserContext context; private TemplateParserLogger logger; private TemplateParserResult result; private Attribute currentAttribute; private LocalComponentProp currentProp; private TypeName currentExpressionReturnType; private OutputDocument outputDocument; /** * Parse a given HTML template and return the a result object containing the expressions * and a transformed HTML. * @param htmlTemplate The HTML template to process, as a String * @param context Context of the Component we are currently processing * @param messager Used to report errors in template during Annotation Processing * @return A {@link TemplateParserResult} containing the processed template and expressions */ public TemplateParserResult parseHtmlTemplate(String htmlTemplate, TemplateParserContext context, Messager messager) { this.context = context; this.logger = new TemplateParserLogger(context, messager); initJerichoConfig(this.logger); Source source = new Source(htmlTemplate); outputDocument = new OutputDocument(source); result = new TemplateParserResult(); processImports(source); source.getChildElements().forEach(this::processElement); result.setProcessedTemplate(outputDocument.toString()); return result; } private void initJerichoConfig(TemplateParserLogger logger) { // Allow as many invalid character in attributes as possible Attributes.setDefaultMaxErrorCount(Integer.MAX_VALUE); // Allow any element to be self closing Config.IsHTMLEmptyElementTagRecognised = true; // Use our own logger Config.LoggerProvider = new TemplateParserLoggerProvider(logger); } /** * Add java imports in the template to the context. * @param doc The document to process */ private void processImports(Source doc) { doc .getAllElements() .stream() .filter(element -> "vue-gwt:import".equalsIgnoreCase(element.getName())) .peek(importElement -> { String classAttributeValue = importElement.getAttributeValue("class"); if (classAttributeValue != null) context.addImport(classAttributeValue); }) .forEach(outputDocument::remove); } /** * Recursive method that will process the whole template DOM tree. * @param element Current element being processed */ private void processElement(Element element) { context.setCurrentElement(element); currentProp = null; currentAttribute = null; Attributes attributes = element.getAttributes(); Attribute vForAttribute = attributes != null ? attributes.get("v-for") : null; if (vForAttribute != null) { // Add a context layer for our v-for context.addContextLayer(); // Process the v-for expression, and update our attribute String processedVForValue = processVForValue(vForAttribute.getValue()); outputDocument.replace(vForAttribute.getValueSegment(), processedVForValue); } // Process the element if (attributes != null) processElementAttributes(element); // Process text segments StreamSupport .stream(((Iterable<Segment>) element::getNodeIterator).spliterator(), false) .filter(segment -> !(segment instanceof Tag) && !(segment instanceof CharacterReference)) .filter(segment -> { for (Element child : element.getChildElements()) if (child.encloses(segment)) return false; return true; }) .forEach(this::processTextNode); // Recurse downwards element.getChildElements(). forEach(this::processElement); // After downward recursion, pop the context layer if (vForAttribute != null) context.popContextLayer(); } /** * Process text node to check for {{ }} vue expressions. * @param textSegment Current segment being processed */ private void processTextNode(Segment textSegment) { String elementText = textSegment.toString(); Matcher matcher = VUE_MUSTACHE_PATTERN.matcher(elementText); int lastEnd = 0; StringBuilder newText = new StringBuilder(); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); if (start > 0) newText.append(elementText.substring(lastEnd, start)); currentExpressionReturnType = TypeName.get(String.class); String expressionString = elementText.substring(start + 2, end - 2).trim(); String processedExpression = processExpression(expressionString); newText.append("{{ ").append(processedExpression).append(" }}"); lastEnd = end; } if (lastEnd > 0) { newText.append(elementText.substring(lastEnd)); outputDocument.replace(textSegment, newText.toString()); } } /** * Process an {@link Element} and check for vue attributes. * @param element Current element being processed */ private void processElementAttributes(Element element) { Optional<LocalComponent> localComponent = getLocalComponentForElement(element); // Iterate on element attributes Set<LocalComponentProp> foundProps = new HashSet<>(); for (Attribute attribute : element.getAttributes()) { if ("v-for".equals(attribute.getKey()) || "v-model".equals(attribute.getKey())) continue; Optional<LocalComponentProp> optionalProp = localComponent.flatMap(lc -> lc.getPropForAttribute(attribute.getName())); optionalProp.ifPresent(foundProps::add); if (!VUE_ATTR_PATTERN.matcher(attribute.getKey()).matches()) { optionalProp.ifPresent(this::validateStringPropBinding); continue; } currentAttribute = attribute; currentProp = optionalProp.orElse(null); currentExpressionReturnType = getExpressionReturnTypeForAttribute(attribute); String processedExpression = processExpression(attribute.getValue()); if (attribute.getValueSegment() != null) outputDocument.replace(attribute.getValueSegment(), processedExpression); } localComponent.ifPresent(lc -> validateRequiredProps(lc, foundProps)); } /** * Return the {@link LocalComponent} definition for a given DOM {@link Element} * @param element Current element being processed * @return An Optional {@link LocalComponent} */ private Optional<LocalComponent> getLocalComponentForElement(Element element) { String componentName = element.getAttributes().getValue("is"); if (componentName == null) componentName = element.getStartTag().getName(); return context.getLocalComponent(componentName); } /** * Validate that a {@link Prop} bounded with string binding is of type String * @param localComponentProp The prop to check */ private void validateStringPropBinding(LocalComponentProp localComponentProp) { if (localComponentProp.getType().toString().equals(String.class.getCanonicalName())) return; logger.error("Passing a String to a non String Prop: \"" + localComponentProp.getPropName() + "\". " + "If you want to pass a boolean or an int you should use v-bind. " + "For example: v-bind:my-prop=\"12\" (or using the short syntax, :my-prop=\"12\") instead of my-prop=\"12\"."); } /** * Validate that all the required properties of a local components are present on a the * HTML {@link Element} that represents it. * @param localComponent The {@link LocalComponent} we want to check * @param foundProps The props we found on the HTML {@link Element} during processing */ private void validateRequiredProps(LocalComponent localComponent, Set<LocalComponentProp> foundProps) { String missingRequiredProps = localComponent .getRequiredProps() .stream() .filter(prop -> !foundProps.contains(prop)) .map(prop -> "\"" + propNameToAttributeName(prop.getPropName()) + "\"") .collect(Collectors.joining(",")); if (!missingRequiredProps.isEmpty()) { logger.error("Missing required property: " + missingRequiredProps + " on child component \"" + localComponent.getComponentTagName() + "\""); } } /** * Guess the type of the expression based on where it is used. * The guessed type can be overridden by adding a Cast to the desired type at the * beginning of the expression. * @param attribute The attribute the expression is in * @return */ private TypeName getExpressionReturnTypeForAttribute(Attribute attribute) { String attributeName = attribute.getKey().toLowerCase(); if (attributeName.indexOf("@") == 0 || attributeName.indexOf("v-on:") == 0) return TypeName.VOID; if ("v-if".equals(attributeName) || "v-show".equals(attributeName)) return TypeName.BOOLEAN; if (currentProp != null) return currentProp.getType(); return TypeName.get(Any.class); } /** * Process a v-for value. * It will register the loop variables as a local variable in the context stack. * @param vForValue The value of the v-for attribute * @return A processed v-for value, should be placed in the HTML in place of the original * v-for value */ private String processVForValue(String vForValue) { VForDefinition vForDef = new VForDefinition(vForValue, context, logger); // Set return of the "in" expression currentExpressionReturnType = vForDef.getInExpressionType(); String inExpression = this.processExpression(vForDef.getInExpression()); // And return the newly built definition return vForDef.getVariableDefinition() + " in " + inExpression; } /** * Process a given template expression * @param expressionString Should be either empty or a valid Java expression * @return The processed expression */ private String processExpression(String expressionString) { expressionString = expressionString == null ? "" : expressionString.trim(); if (expressionString.isEmpty()) { if (isAttributeBinding(currentAttribute)) { logger.error( "Empty expression in template property binding. If you want to pass an empty string then simply don't use binding: my-attribute=\"\"", currentAttribute.toString()); } else if (isEventBinding(currentAttribute)) { logger.error("Empty expression in template event binding.", currentAttribute.toString()); } else { return ""; } } if (expressionString.startsWith("{")) logger.error( "Object literal syntax are not supported yet in Vue GWT, please use map(e(\"key1\", myValue), e(\"key2\", myValue2 > 5)...) instead. The object returned by map() is a regular Javascript Object (JsObject) with the given key/values.", expressionString); if (expressionString.startsWith("[")) logger.error( "Array literal syntax are not supported yet in Vue GWT, please use array(myValue, myValue2 > 5...) instead. The object returned by array() is a regular Javascript Array (JsArray) with the given values.", expressionString); if (shouldSkipExpressionProcessing(expressionString)) return expressionString; return processJavaExpression(expressionString).toTemplateString(); } /** * In some cases we want to skip expression processing for optimization. * This is when we are sure the expression is valid and there is no need to create a Java method * for it. * @param expressionString The expression to asses * @return true if we can skip the expression */ private boolean shouldSkipExpressionProcessing(String expressionString) { // We don't skip if it's a component prop as we want Java validation // We don't optimize String expression, as we want GWT to convert Java values // to String for us (Enums, wrapped primitives...) return currentProp == null && !String.class .getCanonicalName() .equals(currentExpressionReturnType.toString()) && isSimpleVueJsExpression( expressionString); } private boolean isAttributeBinding(Attribute attribute) { String attributeName = attribute.getKey().toLowerCase(); return attributeName.startsWith(":") || attributeName.startsWith("v-bind:"); } private boolean isEventBinding(Attribute attribute) { String attributeName = attribute.getKey().toLowerCase(); return attributeName.startsWith("@") || attributeName.startsWith("v-on:"); } /** * In some case the expression is already a valid Vue.js expression that will work without * any processing. In this case we just leave it in place. * This avoid creating Computed properties/methods for simple expressions. * @param expressionString The expression to check * @return true if it's already a valid Vue.js expression, false otherwise */ private boolean isSimpleVueJsExpression(String expressionString) { String methodName = expressionString; if (expressionString.endsWith("()")) methodName = expressionString.substring(0, expressionString.length() - 2); // Just a method name/simple method call with no parameters if (context.hasMethod(methodName)) return true; // Just a variable return context.findVariable(expressionString) != null; } /** * Process the given string as a Java expression. * @param expressionString A valid Java expression * @return A processed expression, should be placed in the HTML in place of the original * expression */ private TemplateExpression processJavaExpression(String expressionString) { Expression expression; try { expression = JavaParser.parseExpression(expressionString); } catch (ParseProblemException parseException) { logger.error("Couldn't parse Expression, make sure it is valid Java.", expressionString); throw parseException; } resolveTypesUsingImports(expression); resolveStaticMethodsUsingImports(expression); checkMethodNames(expression); // Find the parameters used by the expression List<VariableInfo> expressionParameters = new LinkedList<>(); findExpressionParameters(expression, expressionParameters); // If there is a cast first, we use this as the type of our expression if (currentProp == null) expression = getTypeFromCast(expression); // Update the expression as it might have been changed expressionString = expression.toString(); // Add the resulting expression to our result return result.addExpression(expressionString, currentExpressionReturnType, currentProp == null, expressionParameters); } /** * Get the type of an expression from the cast at the beginning. * (int) 12 -> 12 of type int * (int) 15 + 5 -> 15 + 5 of type int * (float) (12 + 3) -> 12 + 3 of type float * ((int) 12) + 3 -> ((int) 12) + 3 of type Any * ((JsArray) myArray).getAt(0) -> ((JsArray) myArray).getAt(0) of type Any * @param expression The expression to process * @return The modified expression (where cast has been removed if necessary) */ private Expression getTypeFromCast(Expression expression) { if (expression instanceof BinaryExpr) { Expression mostLeft = getLeftmostExpression(expression); if (mostLeft instanceof CastExpr) { CastExpr castExpr = (CastExpr) mostLeft; currentExpressionReturnType = stringTypeToTypeName(castExpr.getType().toString()); BinaryExpr parent = (BinaryExpr) mostLeft.getParentNode().get(); parent.setLeft(castExpr.getExpression()); } } else if (expression instanceof CastExpr) { CastExpr castExpr = (CastExpr) expression; currentExpressionReturnType = stringTypeToTypeName(castExpr.getType().toString()); expression = castExpr.getExpression(); } return expression; } private Expression getLeftmostExpression(Expression expression) { if (expression instanceof BinaryExpr) return getLeftmostExpression(((BinaryExpr) expression).getLeft()); return expression; } /** * Resolve all the types in the expression. * This will replace the Class with the full qualified name using the template imports. * @param expression A Java expression from the Template */ private void resolveTypesUsingImports(Expression expression) { if (expression instanceof NodeWithType) { NodeWithType nodeWithType = ((NodeWithType) expression); nodeWithType.setType(getQualifiedName(nodeWithType.getType())); } // Recurse downward in the expression expression .getChildNodes() .stream() .filter(Expression.class::isInstance) .map(Expression.class::cast) .forEach(this::resolveTypesUsingImports); } /** * Resolve static method calls using static imports * @param expression The expression to resolve */ private void resolveStaticMethodsUsingImports(Expression expression) { if (expression instanceof MethodCallExpr) { MethodCallExpr methodCall = ((MethodCallExpr) expression); String methodName = methodCall.getName().getIdentifier(); if (!methodCall.getScope().isPresent() && context.hasStaticMethod(methodName)) { methodCall.setName(context.getFullyQualifiedNameForMethodName(methodName)); } } // Recurse downward in the expression expression .getChildNodes() .stream() .filter(Expression.class::isInstance) .map(Expression.class::cast) .forEach(this::resolveStaticMethodsUsingImports); } /** * Check the expression for component method calls. * This will check that the methods used in the template exist in the Component. * It throws an exception if we use a method that is not declared in our Component. * This will not check for the type or number of parameters, we leave that to the Java Compiler. * @param expression The expression to check */ private void checkMethodNames(Expression expression) { if (expression instanceof MethodCallExpr) { MethodCallExpr methodCall = ((MethodCallExpr) expression); if (!methodCall.getScope().isPresent()) { String methodName = methodCall.getName().getIdentifier(); if (!context.hasMethod(methodName) && !context.hasStaticMethod(methodName)) { logger.error("Couldn't find the method \"" + methodName + "\" in the Component. " + "Make sure it is not private or try rerunning your Annotation processor.", expression.toString()); } } } for (com.github.javaparser.ast.Node node : expression.getChildNodes()) { if (!(node instanceof Expression)) continue; Expression childExpr = (Expression) node; checkMethodNames(childExpr); } } /** * Find all the parameters this expression depends on. * This is either the local variables (from a v-for loop) or the $event variable. * @param expression An expression from the Template * @param parameters The parameters this expression depends on */ private void findExpressionParameters(Expression expression, List<VariableInfo> parameters) { if (expression instanceof NameExpr) { NameExpr nameExpr = ((NameExpr) expression); if ("$event".equals(nameExpr.getNameAsString())) processEventParameter(expression, nameExpr, parameters); else processNameExpression(expression, nameExpr, parameters); } expression .getChildNodes() .stream() .filter(Expression.class::isInstance) .map(Expression.class::cast) .forEach(exp -> findExpressionParameters(exp, parameters)); } /** * Process the $event variable passed on v-on. This variable must have a valid cast in front. * @param expression The currently processed expression * @param nameExpr The variable we are processing * @param parameters The parameters this expression depends on */ private void processEventParameter(Expression expression, NameExpr nameExpr, List<VariableInfo> parameters) { if (nameExpr.getParentNode().isPresent() && nameExpr .getParentNode() .get() instanceof CastExpr) { CastExpr castExpr = (CastExpr) nameExpr.getParentNode().get(); parameters.add(new VariableInfo(castExpr.getType().toString(), "$event")); } else { logger.error( "\"$event\" should always be casted to it's intended type. Example: @click=\"doSomething((NativeEvent) $event)\".", expression.toString()); } } /** * Process a name expression to determine if it exists in the context. * If it does, and it's a local variable (from a v-for) we add it to our parameters * @param expression The currently processed expression * @param nameExpr The variable we are processing * @param parameters The parameters this expression depends on */ private void processNameExpression(Expression expression, NameExpr nameExpr, List<VariableInfo> parameters) { String name = nameExpr.getNameAsString(); if (context.hasImport(name)) { // This is a direct Class reference, we just replace with the fully qualified name nameExpr.setName(context.getFullyQualifiedNameForClassName(name)); return; } VariableInfo variableInfo = context.findVariable(name); if (variableInfo == null) { logger.error("Couldn't find variable/method \"" + name + "\" in the Component. Make sure you didn't forget the @JsProperty/@JsMethod annotation or try rerunning your Annotation processor.", expression.toString()); } if (variableInfo instanceof LocalVariableInfo) { parameters.add(variableInfo); } } private String getQualifiedName(Type type) { return context.getFullyQualifiedNameForClassName(type.toString()); } }
Improve error message when not finding variable on template
processors/src/main/java/com/axellience/vuegwt/processors/component/template/parser/TemplateParser.java
Improve error message when not finding variable on template
Java
mit
4a75a382a8c733d5855460d766e6f806b5016514
0
codeka/wwmmo,jife94/wwmmo,jife94/wwmmo,lafiter/wwmmo,NoMasp/wwmmo,NoMasp/wwmmo,lafiter/wwmmo,codeka/wwmmo,NoMasp/wwmmo,codeka/wwmmo,lafiter/wwmmo,NoMasp/wwmmo,codeka/wwmmo,lafiter/wwmmo,jife94/wwmmo,codeka/wwmmo,lafiter/wwmmo,codeka/wwmmo,NoMasp/wwmmo,jife94/wwmmo,jife94/wwmmo
package au.com.codeka.warworlds.server.ctrl; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.joda.time.DateTime; import au.com.codeka.common.model.BaseAllianceMember; import au.com.codeka.common.model.BaseAllianceRequest; import au.com.codeka.common.protobuf.Messages; import au.com.codeka.warworlds.server.RequestException; import au.com.codeka.warworlds.server.data.SqlStmt; import au.com.codeka.warworlds.server.data.Transaction; import au.com.codeka.warworlds.server.model.Alliance; import au.com.codeka.warworlds.server.model.AllianceMember; import au.com.codeka.warworlds.server.model.AllianceRequest; import au.com.codeka.warworlds.server.model.AllianceRequestVote; import au.com.codeka.warworlds.server.model.Empire; public class AllianceController { private DataBase db; public AllianceController() { db = new DataBase(); } public AllianceController(Transaction trans) { db = new DataBase(trans); } public BaseDataBase getDB() { return db; } public List<Alliance> getAlliances() throws RequestException { try { return db.getAlliances(); } catch (Exception e) { throw new RequestException(e); } } public Alliance getAlliance(int allianceID) throws RequestException { try { return db.getAlliance(allianceID); } catch (Exception e) { throw new RequestException(e); } } public List<AllianceRequest> getRequests(int allianceID) throws RequestException { try { return db.getRequests(allianceID); } catch (Exception e) { throw new RequestException(e); } } public void leaveAlliance(int empireID, int allianceID) throws RequestException { try { db.leaveAlliance(empireID, allianceID); } catch (Exception e) { throw new RequestException(e); } } public int addRequest(AllianceRequest request) throws RequestException { try { int requestID = db.addRequest(request); request.setID(requestID); // there's an implicit vote when you create a request (some requests require zero // votes, which means it passes straight away) Alliance alliance = db.getAlliance(request.getAllianceID()); AllianceRequestProcessor processor = AllianceRequestProcessor.get(alliance, request); processor.onVote(this); return requestID; } catch (Exception e) { throw new RequestException(e); } } public void vote(AllianceRequestVote vote) throws RequestException { try { Alliance alliance = db.getAlliance(vote.getAllianceID()); // normalize the number of votes they get by their rank in the alliance for (BaseAllianceMember member : alliance.getMembers()) { if (Integer.parseInt(member.getEmpireKey()) == vote.getEmpireID()) { int numVotes = member.getRank().getNumVotes(); if (vote.getVotes() < 0) { numVotes *= -1; } vote.setVotes(numVotes); break; } } db.vote(vote); // depending on the kind of request this is, check whether this is enough votes to // complete the voting or not AllianceRequest request = db.getRequest(vote.getAllianceRequestID()); AllianceRequestProcessor processor = AllianceRequestProcessor.get(alliance, request); processor.onVote(this); } catch(Exception e) { throw new RequestException(e); } } public void createAlliance(Alliance alliance, Empire ownerEmpire) throws RequestException { Messages.CashAuditRecord.Builder audit_record_pb = Messages.CashAuditRecord.newBuilder() .setEmpireId(ownerEmpire.getID()) .setAllianceName(alliance.getName()); if (!new EmpireController().withdrawCash(ownerEmpire.getID(), 250000, audit_record_pb)) { throw new RequestException(400, Messages.GenericError.ErrorCode.InsufficientCash, "Insufficient cash to create a new alliance."); } try { db.createAlliance(alliance, ownerEmpire.getID()); } catch (Exception e) { throw new RequestException(e); } } private static class DataBase extends BaseDataBase { public DataBase() { super(); } public DataBase(Transaction trans) { super(trans); } public List<Alliance> getAlliances() throws Exception { String sql = "SELECT alliances.*," + " (SELECT COUNT(*) FROM empires WHERE empires.alliance_id = alliances.id) AS num_empires" + " FROM alliances" + " ORDER BY name DESC"; try (SqlStmt stmt = prepare(sql)) { ResultSet rs = stmt.select(); ArrayList<Alliance> alliances = new ArrayList<Alliance>(); while (rs.next()) { alliances.add(new Alliance(null, rs)); } return alliances; } } public Alliance getAlliance(int allianceID) throws Exception { Alliance alliance = null; String sql = "SELECT *, 0 AS num_empires FROM alliances WHERE id = ?"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, allianceID); ResultSet rs = stmt.select(); if (rs.next()) { alliance = new Alliance(null, rs); } } if (alliance == null) { throw new RequestException(404); } sql = "SELECT id, alliance_id, alliance_rank FROM empires WHERE alliance_id = ?"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, allianceID); ResultSet rs = stmt.select(); while (rs.next()) { AllianceMember member = new AllianceMember(rs); alliance.getMembers().add(member); } } return alliance; } public void createAlliance(Alliance alliance, int creatorEmpireID) throws Exception { String sql = "INSERT INTO alliances (name, creator_empire_id, created_date, bank_balance) VALUES (?, ?, ?, 0)"; try (SqlStmt stmt = prepare(sql, Statement.RETURN_GENERATED_KEYS)) { stmt.setString(1, alliance.getName()); stmt.setInt(2, creatorEmpireID); stmt.setDateTime(3, DateTime.now()); stmt.update(); alliance.setID(stmt.getAutoGeneratedID()); } sql = "UPDATE empires SET alliance_id = ? WHERE id = ?"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, alliance.getID()); stmt.setInt(2, creatorEmpireID); stmt.update(); } } public int addRequest(AllianceRequest request) throws Exception { // if you make another request while you've still got one pending, the new request // will overwrite the old one. String sql = "DELETE FROM alliance_requests" + " WHERE request_empire_id = ?" + " AND alliance_id = ?" + " AND request_type = ?" + " AND state = " + BaseAllianceRequest.RequestState.PENDING.getNumber(); try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, request.getRequestEmpireID()); stmt.setInt(2, request.getAllianceID()); stmt.setInt(3, request.getRequestType().getNumber()); stmt.update(); } sql = "INSERT INTO alliance_requests (" + "alliance_id, request_empire_id, request_date, request_type, message, state," + " votes, target_empire_id, amount) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; try (SqlStmt stmt = prepare(sql, Statement.RETURN_GENERATED_KEYS)) { stmt.setInt(1, request.getAllianceID()); stmt.setInt(2, request.getRequestEmpireID()); stmt.setDateTime(3, DateTime.now()); stmt.setInt(4, request.getRequestType().getNumber()); stmt.setString(5, request.getMessage()); stmt.setInt(6, BaseAllianceRequest.RequestState.PENDING.getNumber()); stmt.setInt(7, 0); if (request.getTargetEmpireID() != null) { stmt.setInt(8, request.getTargetEmpireID()); } else { stmt.setNull(8); } if (request.getAmount() != null) { stmt.setDouble(9, request.getAmount()); } else { stmt.setNull(9); } stmt.update(); return stmt.getAutoGeneratedID(); } } public void leaveAlliance(int empireID, int allianceID) throws Exception { String sql = "UPDATE empires SET alliance_id = NULL WHERE id = ? AND alliance_id = ?"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, empireID); stmt.setInt(2, allianceID); stmt.update(); } } public List<AllianceRequest> getRequests(int allianceID) throws Exception { String sql = "SELECT * FROM alliance_requests WHERE alliance_id = ? ORDER BY request_date DESC"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, allianceID); ResultSet rs = stmt.select(); ArrayList<AllianceRequest> joinRequests = new ArrayList<AllianceRequest>(); while (rs.next()) { joinRequests.add(new AllianceRequest(rs)); } return joinRequests; } } public AllianceRequest getRequest(int allianceRequestID) throws Exception { String sql = "SELECT * FROM alliance_requests WHERE id = ?"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, allianceRequestID); ResultSet rs = stmt.select(); if (rs.next()) { return new AllianceRequest(rs); } } throw new RequestException(404, "No such alliance request found!"); } public void vote(AllianceRequestVote vote) throws Exception { // if they're already voted for this request, then update the existing vote String sql = "SELECT id FROM alliance_request_votes " + "WHERE alliance_request_id = ? AND empire_id = ?"; Integer id = null; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, vote.getAllianceRequestID()); stmt.setInt(2, vote.getEmpireID()); id = stmt.selectFirstValue(Integer.class); } if (id != null) { sql = "UPDATE alliance_request_votes SET votes = ? WHERE id = ?"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, vote.getVotes()); stmt.setInt(2, (int) id); stmt.update(); } } else { sql = "INSERT INTO alliance_request_votes (alliance_id, alliance_request_id," + " empire_id, votes, date) VALUES (?, ?, ?, ?, NOW())"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, vote.getAllianceID()); stmt.setInt(2, vote.getAllianceRequestID()); stmt.setInt(3, vote.getEmpireID()); stmt.setInt(4, vote.getVotes()); stmt.update(); } } // update the alliance_requests table so it has an accurate vote count for this request sql = "UPDATE alliance_requests SET votes = (" + "SELECT SUM(votes) FROM alliance_request_votes WHERE alliance_request_id = alliance_requests.id" + ") WHERE id = ?"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, vote.getAllianceRequestID()); stmt.update(); } } } }
server/src/au/com/codeka/warworlds/server/ctrl/AllianceController.java
package au.com.codeka.warworlds.server.ctrl; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.joda.time.DateTime; import au.com.codeka.common.model.BaseAllianceMember; import au.com.codeka.common.model.BaseAllianceRequest; import au.com.codeka.common.protobuf.Messages; import au.com.codeka.warworlds.server.RequestException; import au.com.codeka.warworlds.server.data.SqlStmt; import au.com.codeka.warworlds.server.data.Transaction; import au.com.codeka.warworlds.server.model.Alliance; import au.com.codeka.warworlds.server.model.AllianceMember; import au.com.codeka.warworlds.server.model.AllianceRequest; import au.com.codeka.warworlds.server.model.AllianceRequestVote; import au.com.codeka.warworlds.server.model.Empire; public class AllianceController { private DataBase db; public AllianceController() { db = new DataBase(); } public AllianceController(Transaction trans) { db = new DataBase(trans); } public BaseDataBase getDB() { return db; } public List<Alliance> getAlliances() throws RequestException { try { return db.getAlliances(); } catch (Exception e) { throw new RequestException(e); } } public Alliance getAlliance(int allianceID) throws RequestException { try { return db.getAlliance(allianceID); } catch (Exception e) { throw new RequestException(e); } } public List<AllianceRequest> getRequests(int allianceID) throws RequestException { try { return db.getRequests(allianceID); } catch (Exception e) { throw new RequestException(e); } } public void leaveAlliance(int empireID, int allianceID) throws RequestException { try { db.leaveAlliance(empireID, allianceID); } catch (Exception e) { throw new RequestException(e); } } public int addRequest(AllianceRequest request) throws RequestException { try { int requestID = db.addRequest(request); request.setID(requestID); // there's an implicit vote when you create a request (some requests require zero // votes, which means it passes straight away) Alliance alliance = db.getAlliance(request.getAllianceID()); AllianceRequestProcessor processor = AllianceRequestProcessor.get(alliance, request); processor.onVote(this); return requestID; } catch (Exception e) { throw new RequestException(e); } } public void vote(AllianceRequestVote vote) throws RequestException { try { Alliance alliance = db.getAlliance(vote.getAllianceID()); // normalize the number of votes they get by their rank in the alliance for (BaseAllianceMember member : alliance.getMembers()) { if (Integer.parseInt(member.getEmpireKey()) == vote.getEmpireID()) { int numVotes = member.getRank().getNumVotes(); if (vote.getVotes() < 0) { numVotes *= -1; } vote.setVotes(numVotes); break; } } db.vote(vote); // depending on the kind of request this is, check whether this is enough votes to // complete the voting or not AllianceRequest request = db.getRequest(vote.getAllianceRequestID()); AllianceRequestProcessor processor = AllianceRequestProcessor.get(alliance, request); processor.onVote(this); } catch(Exception e) { throw new RequestException(e); } } public void createAlliance(Alliance alliance, Empire ownerEmpire) throws RequestException { Messages.CashAuditRecord.Builder audit_record_pb = Messages.CashAuditRecord.newBuilder() .setEmpireId(ownerEmpire.getID()) .setAllianceName(alliance.getName()); if (!new EmpireController().withdrawCash(ownerEmpire.getID(), 250000, audit_record_pb)) { throw new RequestException(400, Messages.GenericError.ErrorCode.InsufficientCash, "Insufficient cash to create a new alliance."); } try { db.createAlliance(alliance, ownerEmpire.getID()); } catch (Exception e) { throw new RequestException(e); } } private static class DataBase extends BaseDataBase { public DataBase() { super(); } public DataBase(Transaction trans) { super(trans); } public List<Alliance> getAlliances() throws Exception { String sql = "SELECT alliances.*," + " (SELECT COUNT(*) FROM empires WHERE empires.alliance_id = alliances.id) AS num_empires" + " FROM alliances" + " ORDER BY name DESC"; try (SqlStmt stmt = prepare(sql)) { ResultSet rs = stmt.select(); ArrayList<Alliance> alliances = new ArrayList<Alliance>(); while (rs.next()) { alliances.add(new Alliance(null, rs)); } return alliances; } } public Alliance getAlliance(int allianceID) throws Exception { Alliance alliance = null; String sql = "SELECT *, 0 AS num_empires FROM alliances WHERE id = ?"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, allianceID); ResultSet rs = stmt.select(); if (rs.next()) { alliance = new Alliance(null, rs); } } if (alliance == null) { throw new RequestException(404); } sql = "SELECT id, alliance_id, alliance_rank FROM empires WHERE alliance_id = ?"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, allianceID); ResultSet rs = stmt.select(); while (rs.next()) { AllianceMember member = new AllianceMember(rs); alliance.getMembers().add(member); } } return alliance; } public void createAlliance(Alliance alliance, int creatorEmpireID) throws Exception { String sql = "INSERT INTO alliances (name, creator_empire_id, created_date) VALUES (?, ?, ?)"; try (SqlStmt stmt = prepare(sql, Statement.RETURN_GENERATED_KEYS)) { stmt.setString(1, alliance.getName()); stmt.setInt(2, creatorEmpireID); stmt.setDateTime(3, DateTime.now()); stmt.update(); alliance.setID(stmt.getAutoGeneratedID()); } sql = "UPDATE empires SET alliance_id = ? WHERE id = ?"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, alliance.getID()); stmt.setInt(2, creatorEmpireID); stmt.update(); } } public int addRequest(AllianceRequest request) throws Exception { // if you make another request while you've still got one pending, the new request // will overwrite the old one. String sql = "DELETE FROM alliance_requests" + " WHERE request_empire_id = ?" + " AND alliance_id = ?" + " AND request_type = ?" + " AND state = " + BaseAllianceRequest.RequestState.PENDING.getNumber(); try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, request.getRequestEmpireID()); stmt.setInt(2, request.getAllianceID()); stmt.setInt(3, request.getRequestType().getNumber()); stmt.update(); } sql = "INSERT INTO alliance_requests (" + "alliance_id, request_empire_id, request_date, request_type, message, state," + " votes, target_empire_id, amount) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; try (SqlStmt stmt = prepare(sql, Statement.RETURN_GENERATED_KEYS)) { stmt.setInt(1, request.getAllianceID()); stmt.setInt(2, request.getRequestEmpireID()); stmt.setDateTime(3, DateTime.now()); stmt.setInt(4, request.getRequestType().getNumber()); stmt.setString(5, request.getMessage()); stmt.setInt(6, BaseAllianceRequest.RequestState.PENDING.getNumber()); stmt.setInt(7, 0); if (request.getTargetEmpireID() != null) { stmt.setInt(8, request.getTargetEmpireID()); } else { stmt.setNull(8); } if (request.getAmount() != null) { stmt.setDouble(9, request.getAmount()); } else { stmt.setNull(9); } stmt.update(); return stmt.getAutoGeneratedID(); } } public void leaveAlliance(int empireID, int allianceID) throws Exception { String sql = "UPDATE empires SET alliance_id = NULL WHERE id = ? AND alliance_id = ?"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, empireID); stmt.setInt(2, allianceID); stmt.update(); } } public List<AllianceRequest> getRequests(int allianceID) throws Exception { String sql = "SELECT * FROM alliance_requests WHERE alliance_id = ? ORDER BY request_date DESC"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, allianceID); ResultSet rs = stmt.select(); ArrayList<AllianceRequest> joinRequests = new ArrayList<AllianceRequest>(); while (rs.next()) { joinRequests.add(new AllianceRequest(rs)); } return joinRequests; } } public AllianceRequest getRequest(int allianceRequestID) throws Exception { String sql = "SELECT * FROM alliance_requests WHERE id = ?"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, allianceRequestID); ResultSet rs = stmt.select(); if (rs.next()) { return new AllianceRequest(rs); } } throw new RequestException(404, "No such alliance request found!"); } public void vote(AllianceRequestVote vote) throws Exception { // if they're already voted for this request, then update the existing vote String sql = "SELECT id FROM alliance_request_votes " + "WHERE alliance_request_id = ? AND empire_id = ?"; Integer id = null; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, vote.getAllianceRequestID()); stmt.setInt(2, vote.getEmpireID()); id = stmt.selectFirstValue(Integer.class); } if (id != null) { sql = "UPDATE alliance_request_votes SET votes = ? WHERE id = ?"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, vote.getVotes()); stmt.setInt(2, (int) id); stmt.update(); } } else { sql = "INSERT INTO alliance_request_votes (alliance_id, alliance_request_id," + " empire_id, votes, date) VALUES (?, ?, ?, ?, NOW())"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, vote.getAllianceID()); stmt.setInt(2, vote.getAllianceRequestID()); stmt.setInt(3, vote.getEmpireID()); stmt.setInt(4, vote.getVotes()); stmt.update(); } } // update the alliance_requests table so it has an accurate vote count for this request sql = "UPDATE alliance_requests SET votes = (" + "SELECT SUM(votes) FROM alliance_request_votes WHERE alliance_request_id = alliance_requests.id" + ") WHERE id = ?"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, vote.getAllianceRequestID()); stmt.update(); } } } }
Fixed bug when creating alliance.
server/src/au/com/codeka/warworlds/server/ctrl/AllianceController.java
Fixed bug when creating alliance.
Java
mit
eb26b3c45db6d6a7d55e430244ac63ed0920e4be
0
Reline/realm-expandable-recycler-view,bignerdranch/expandable-recycler-view,Syhids/expandable-recycler-view,bignerdranch/expandable-recycler-view
package com.bignerdranch.expandablerecyclerview.Adapter; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import com.bignerdranch.expandablerecyclerview.Listener.ExpandCollapseListener; import com.bignerdranch.expandablerecyclerview.Listener.ParentItemExpandCollapseListener; import com.bignerdranch.expandablerecyclerview.Model.ParentObject; import com.bignerdranch.expandablerecyclerview.Model.ParentWrapper; import com.bignerdranch.expandablerecyclerview.ViewHolder.ChildViewHolder; import com.bignerdranch.expandablerecyclerview.ViewHolder.ParentViewHolder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * The Base class for an Expandable RecyclerView Adapter * * Provides the base for a user to implement binding custom views to a Parent ViewHolder and a * Child ViewHolder * * @author Ryan Brooks * @version 1.0 * @since 5/27/2015 */ public abstract class ExpandableRecyclerAdapter<PVH extends ParentViewHolder, CVH extends ChildViewHolder> extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements ParentItemExpandCollapseListener { private static final String STABLE_ID_MAP = "ExpandableRecyclerAdapter.StableIdMap"; private static final int TYPE_PARENT = 0; private static final int TYPE_CHILD = 1; protected Context mContext; protected List<? extends ParentObject> mParentItemList; private List<Object> mHelperItemList; private HashMap<Long, Boolean> mStableIdMap; private ExpandCollapseListener mExpandCollapseListener; private List<RecyclerView> mAttachedRecyclerViewPool; /** * Public constructor for the base ExpandableRecyclerView. * * @param context * @param parentItemList List of all parent objects that make up the recyclerview */ public ExpandableRecyclerAdapter(Context context, @NonNull List<? extends ParentObject> parentItemList) { super(); mContext = context; mParentItemList = parentItemList; mHelperItemList = ExpandableRecyclerAdapterHelper.generateHelperItemList(parentItemList); mStableIdMap = generateStableIdMapFromList(mHelperItemList); mAttachedRecyclerViewPool = new ArrayList<>(); } /** * Override of RecyclerView's default onCreateViewHolder. * * This implementation determines if the item is a child or a parent view and will then call * the respective onCreateViewHolder method that the user must implement in their custom * implementation. * * @param viewGroup * @param viewType * @return the ViewHolder that corresponds to the item at the position. */ @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { if (viewType == TYPE_PARENT) { PVH pvh = onCreateParentViewHolder(viewGroup); pvh.setParentItemExpandCollapseListener(this); return pvh; } else if (viewType == TYPE_CHILD) { return onCreateChildViewHolder(viewGroup); } else { throw new IllegalStateException("Incorrect ViewType found"); } } /** * Override of RecyclerView's default onBindViewHolder * * This implementation determines first if the ViewHolder is a ParentViewHolder or a * ChildViewHolder. The respective onBindViewHolders for ParentObjects and ChildObject are then * called. * * If the item is a ParentObject, sets the entire row to trigger expansion if instructed to * * @param holder * @param position * @throws IllegalStateException if the item in the list is neither a ParentObject or ChildObject */ @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { Object helperItem = getHelperItem(position); if (helperItem instanceof ParentWrapper) { PVH parentViewHolder = (PVH) holder; if (parentViewHolder.shouldItemViewClickToggleExpansion()) { parentViewHolder.setMainItemClickToExpand(); } ParentWrapper parentWrapper = (ParentWrapper) helperItem; parentViewHolder.setExpanded(parentWrapper.isExpanded()); onBindParentViewHolder(parentViewHolder, position, parentWrapper.getParentObject()); } else if (helperItem == null) { throw new IllegalStateException("Incorrect ViewHolder found"); } else { onBindChildViewHolder((CVH) holder, position, helperItem); } } /** * Creates the Parent ViewHolder. Called from onCreateViewHolder when the item is a ParenObject. * * @param parentViewGroup * @return ParentViewHolder that the user must create and inflate. */ public abstract PVH onCreateParentViewHolder(ViewGroup parentViewGroup); /** * Creates the Child ViewHolder. Called from onCreateViewHolder when the item is a ChildObject. * * @param childViewGroup * @return ChildViewHolder that the user must create and inflate. */ public abstract CVH onCreateChildViewHolder(ViewGroup childViewGroup); /** * Binds the data to the ParentViewHolder. Called from onBindViewHolder when the item is a * ParentObject * * @param parentViewHolder * @param position */ public abstract void onBindParentViewHolder(PVH parentViewHolder, int position, Object parentObject); /** * Binds the data to the ChildViewHolder. Called from onBindViewHolder when the item is a * ChildObject * * @param childViewHolder * @param position */ public abstract void onBindChildViewHolder(CVH childViewHolder, int position, Object childObject); /** * Returns the size of the list that contains Parent and Child objects * * @return integer value of the size of the Parent/Child list */ @Override public int getItemCount() { return mHelperItemList.size(); } /** * Returns the type of view that the item at the given position is. * * @param position * @return TYPE_PARENT (0) for ParentObjects and TYPE_CHILD (1) for ChildObjects * @throws IllegalStateException if the item at the given position in the list is null */ @Override public int getItemViewType(int position) { Object helperItem = getHelperItem(position); if (helperItem instanceof ParentWrapper) { return TYPE_PARENT; } else if (helperItem == null) { throw new IllegalStateException("Null object added"); } else { return TYPE_CHILD; } } @Override public void onParentItemExpanded(int position) { Object helperItem = getHelperItem(position); if (helperItem instanceof ParentWrapper) { expandHelperItem((ParentWrapper) helperItem, position, false); } } @Override public void onParentItemCollapsed(int position) { Object helperItem = getHelperItem(position); if (helperItem instanceof ParentWrapper) { collapseHelperItem((ParentWrapper) helperItem, position, false); } } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); mAttachedRecyclerViewPool.add(recyclerView); } @Override public void onDetachedFromRecyclerView(RecyclerView recyclerView) { super.onDetachedFromRecyclerView(recyclerView); mAttachedRecyclerViewPool.remove(recyclerView); } public void addExpandCollapseListener(ExpandCollapseListener expandCollapseListener) { mExpandCollapseListener = expandCollapseListener; } /** * Expands the parent with the specified index in the list of parents. * * @param parentIndex The index of the parent to expand */ public void expandParent(int parentIndex) { int parentWrapperIndex = getParentWrapperIndex(parentIndex); Object helperItem = getHelperItem(parentWrapperIndex); ParentWrapper parentWrapper; if (helperItem instanceof ParentWrapper) { parentWrapper = (ParentWrapper) helperItem; } else { return; } expandViews(parentWrapper, parentWrapperIndex); } /** * Expands the parent associated with a specified {@link ParentObject} in * the list of parents. * * @param parentObject The {@code ParentObject} of the parent to expand */ public void expandParent(ParentObject parentObject) { ParentWrapper parentWrapper = getParentWrapper(parentObject); int parentWrapperIndex = mHelperItemList.indexOf(parentWrapper); if (parentWrapperIndex == -1) { return; } expandViews(parentWrapper, parentWrapperIndex); } /** * Expands all parents in the list. */ public void expandAllParents() { for (ParentObject parentObject : mParentItemList) { expandParent(parentObject); } } /** * Collapses the parent with the specified index in the list of parents. * * @param parentIndex The index of the parent to expand */ public void collapseParent(int parentIndex) { int parentWrapperIndex = getParentWrapperIndex(parentIndex); Object helperItem = getHelperItem(parentWrapperIndex); ParentWrapper parentWrapper; if (helperItem instanceof ParentWrapper) { parentWrapper = (ParentWrapper) helperItem; } else { return; } collapseViews(parentWrapper, parentWrapperIndex); } /** * Collapses the parent associated with a specified {@link ParentObject} in * the list of parents. * * @param parentObject The {@code ParentObject} of the parent to collapse */ public void collapseParent(ParentObject parentObject) { ParentWrapper parentWrapper = getParentWrapper(parentObject); int parentWrapperIndex = mHelperItemList.indexOf(parentWrapper); if (parentWrapperIndex == -1) { return; } collapseViews(parentWrapper, parentWrapperIndex); } /** * Collapses all parents in the list. */ public void collapseAllParents() { for (ParentObject parentObject : mParentItemList) { collapseParent(parentObject); } } /** * Calls through to the {@link ParentViewHolder} to expand views for each * {@link RecyclerView} a specified parent is a child of. These calls to * the {@code ParentViewHolder} are made so that animations can be * triggered at the {@link android.support.v7.widget.RecyclerView.ViewHolder} * level. * * @param parentIndex The inject of the parent to expand */ private void expandViews(ParentWrapper parentWrapper, int parentIndex) { for (RecyclerView recyclerView : mAttachedRecyclerViewPool) { RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(parentIndex); if (viewHolder != null && !((ParentViewHolder) viewHolder).isExpanded()) { ((ParentViewHolder) viewHolder).setExpanded(true); ((ParentViewHolder) viewHolder).onExpansionToggled(false); } expandHelperItem(parentWrapper, parentIndex, true); } } /** * Calls through to the {@link ParentViewHolder} to collapse views for each * {@link RecyclerView} a specified parent is a child of. These calls to * the {@code ParentViewHolder} are made so that animations can be * triggered at the {@link android.support.v7.widget.RecyclerView.ViewHolder} * level. * * @param parentIndex The inject of the parent to collapse */ private void collapseViews(ParentWrapper parentWrapper, int parentIndex) { for (RecyclerView recyclerView : mAttachedRecyclerViewPool) { RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(parentIndex); if (viewHolder != null && ((ParentViewHolder) viewHolder).isExpanded()) { ((ParentViewHolder) viewHolder).setExpanded(false); ((ParentViewHolder) viewHolder).onExpansionToggled(true); } collapseHelperItem(parentWrapper, parentIndex, true); } } /** * Expands a specified parent item. Calls through to the {@link ExpandCollapseListener} * and adds children of the specified parent to the total list of items. * * @param parentWrapper The {@link ParentWrapper} of the parent to expand * @param parentIndex The index of the parent to expand * @param expansionTriggeredProgrammatically {@value false} if expansion was triggered by a * click event, {@value false} otherwise. */ private void expandHelperItem(ParentWrapper parentWrapper, int parentIndex, boolean expansionTriggeredProgrammatically) { if (!parentWrapper.isExpanded()) { parentWrapper.setExpanded(true); if (expansionTriggeredProgrammatically && mExpandCollapseListener != null) { int expandedCountBeforePosition = getExpandedItemCount(parentIndex); mExpandCollapseListener.onRecyclerViewItemExpanded(parentIndex - expandedCountBeforePosition); } mStableIdMap.put(parentWrapper.getStableId(), true); List<Object> childObjectList = parentWrapper.getParentObject().getChildObjectList(); if (childObjectList != null) { int numChildObjects = childObjectList.size(); for (int i = 0; i < numChildObjects; i++) { mHelperItemList.add(parentIndex + i + 1, childObjectList.get(i)); notifyItemInserted(parentIndex + i + 1); } } } } /** * Collapses a specified parent item. Calls through to the {@link ExpandCollapseListener} * and adds children of the specified parent to the total list of items. * * @param parentWrapper The {@link ParentWrapper} of the parent to collapse * @param parentIndex The index of the parent to collapse * @param collapseTriggeredProgrammatically {@value false} if expansion was triggered by a * click event, {@value false} otherwise. */ private void collapseHelperItem(ParentWrapper parentWrapper, int parentIndex, boolean collapseTriggeredProgrammatically) { if (parentWrapper.isExpanded()) { parentWrapper.setExpanded(false); if (collapseTriggeredProgrammatically && mExpandCollapseListener != null) { int expandedCountBeforePosition = getExpandedItemCount(parentIndex); mExpandCollapseListener.onRecyclerViewItemCollapsed(parentIndex - expandedCountBeforePosition); } mStableIdMap.put(parentWrapper.getStableId(), false); List<Object> childObjectList = parentWrapper.getParentObject().getChildObjectList(); if (childObjectList != null) { for (int i = childObjectList.size() - 1; i >= 0; i--) { mHelperItemList.remove(parentIndex + i + 1); notifyItemRemoved(parentIndex + i + 1); } } } } /** * Method to get the number of expanded children before the specified position. * * @param position * @return number of expanded children before the specified position */ private int getExpandedItemCount(int position) { if (position == 0) { return 0; } int expandedCount = 0; for (int i = 0; i < position; i++) { Object object = getHelperItem(i); if (!(object instanceof ParentWrapper)) { expandedCount++; } } return expandedCount; } /** * Generates a HashMap for storing expanded state when activity is rotated or onResume() is called. * * @param itemList * @return HashMap containing the Object's stable id along with a boolean indicating its expanded * state */ private HashMap<Long, Boolean> generateStableIdMapFromList(List<Object> itemList) { HashMap<Long, Boolean> parentObjectHashMap = new HashMap<>(); for (int i = 0; i < itemList.size(); i++) { if (itemList.get(i) != null) { Object helperItem = getHelperItem(i); if (helperItem instanceof ParentWrapper) { ParentWrapper parentWrapper = (ParentWrapper) helperItem; parentObjectHashMap.put(parentWrapper.getStableId(), parentWrapper.isExpanded()); } } } return parentObjectHashMap; } /** * Should be called from onSaveInstanceState of Activity that holds the RecyclerView. This will * make sure to add the generated HashMap as an extra to the bundle to be used in * OnRestoreInstanceState(). * * @param savedInstanceStateBundle * @return the Bundle passed in with the Id HashMap added if applicable */ public Bundle onSaveInstanceState(Bundle savedInstanceStateBundle) { savedInstanceStateBundle.putSerializable(STABLE_ID_MAP, mStableIdMap); return savedInstanceStateBundle; } /** * Should be called from onRestoreInstanceState of Activity that contains the ExpandingRecyclerView. * This will fetch the HashMap that was saved in onSaveInstanceState() and use it to restore * the expanded states before the rotation or onSaveInstanceState was called. * * @param savedInstanceStateBundle */ public void onRestoreInstanceState(Bundle savedInstanceStateBundle) { if (savedInstanceStateBundle == null) { return; } if (!savedInstanceStateBundle.containsKey(STABLE_ID_MAP)) { return; } mStableIdMap = (HashMap<Long, Boolean>) savedInstanceStateBundle.getSerializable(STABLE_ID_MAP); int i = 0; while (i < mHelperItemList.size()) { Object helperItem = getHelperItem(i); if (helperItem instanceof ParentWrapper) { ParentWrapper parentWrapper = (ParentWrapper) helperItem; if (mStableIdMap.containsKey(parentWrapper.getStableId())) { parentWrapper.setExpanded(mStableIdMap.get(parentWrapper.getStableId())); if (parentWrapper.isExpanded() && !parentWrapper.getParentObject().isInitiallyExpanded()) { List<Object> childObjectList = parentWrapper.getParentObject().getChildObjectList(); if (childObjectList != null) { for (int j = 0; j < childObjectList.size(); j++) { i++; mHelperItemList.add(i, childObjectList.get(j)); } } } else if (!parentWrapper.isExpanded() && parentWrapper.getParentObject().isInitiallyExpanded()) { List<Object> childObjectList = parentWrapper.getParentObject().getChildObjectList(); for (int j = 0; j < childObjectList.size(); j++) { mHelperItemList.remove(i + 1); } } } else { parentWrapper.setExpanded(false); } } i++; } notifyDataSetChanged(); } private Object getHelperItem(int position) { return mHelperItemList.get(position); } /** * Gets the index of a {@link ParentWrapper} within the helper item list * based on the index of the {@code ParentWrapper}. * * @param parentIndex The index of the parent in the list of parent items * @return The index of the parent in the list of all views in the adapter */ private int getParentWrapperIndex(int parentIndex) { int parentWrapperIndex = -1; int parentCount = 0; int numHelperItems = mHelperItemList.size(); for (int i = 0; i < numHelperItems; i++) { if (mHelperItemList.get(i) instanceof ParentWrapper) { parentCount++; if (parentCount > parentIndex) { parentWrapperIndex = i; break; } } } return parentWrapperIndex; } /** * Gets the {@link ParentWrapper} for a specified {@link ParentObject} from * the list of parents. * * @param parentObject A {@code ParentObject} in the list of parents * @return If the parent exists on the list, returns its {@code ParentWrapper}. * Otherwise, returns {@value null}. */ private ParentWrapper getParentWrapper(ParentObject parentObject) { ParentWrapper parentWrapper = null; int numHelperItems = mHelperItemList.size(); for (int i = 0; i < numHelperItems; i++) { Object helperItem = mHelperItemList.get(i); if (helperItem instanceof ParentWrapper) { if (((ParentWrapper) helperItem).getParentObject().equals(parentObject)) { parentWrapper = (ParentWrapper) helperItem; break; } } } return parentWrapper; } }
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/Adapter/ExpandableRecyclerAdapter.java
package com.bignerdranch.expandablerecyclerview.Adapter; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import com.bignerdranch.expandablerecyclerview.Listener.ExpandCollapseListener; import com.bignerdranch.expandablerecyclerview.Listener.ParentItemExpandCollapseListener; import com.bignerdranch.expandablerecyclerview.Model.ParentObject; import com.bignerdranch.expandablerecyclerview.Model.ParentWrapper; import com.bignerdranch.expandablerecyclerview.ViewHolder.ChildViewHolder; import com.bignerdranch.expandablerecyclerview.ViewHolder.ParentViewHolder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * The Base class for an Expandable RecyclerView Adapter * * Provides the base for a user to implement binding custom views to a Parent ViewHolder and a * Child ViewHolder * * @author Ryan Brooks * @version 1.0 * @since 5/27/2015 */ public abstract class ExpandableRecyclerAdapter<PVH extends ParentViewHolder, CVH extends ChildViewHolder> extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements ParentItemExpandCollapseListener { private static final String STABLE_ID_MAP = "ExpandableRecyclerAdapter.StableIdMap"; private static final int TYPE_PARENT = 0; private static final int TYPE_CHILD = 1; protected Context mContext; protected List<? extends ParentObject> mParentItemList; private List<Object> mHelperItemList; private HashMap<Long, Boolean> mStableIdMap; private ExpandCollapseListener mExpandCollapseListener; private List<RecyclerView> mAttachedRecyclerViewPool; /** * Public constructor for the base ExpandableRecyclerView. * * @param context * @param parentItemList List of all parent objects that make up the recyclerview */ public ExpandableRecyclerAdapter(Context context, @NonNull List<? extends ParentObject> parentItemList) { super(); mContext = context; mParentItemList = parentItemList; mHelperItemList = ExpandableRecyclerAdapterHelper.generateHelperItemList(parentItemList); mStableIdMap = generateStableIdMapFromList(mHelperItemList); mAttachedRecyclerViewPool = new ArrayList<>(); } /** * Override of RecyclerView's default onCreateViewHolder. * * This implementation determines if the item is a child or a parent view and will then call * the respective onCreateViewHolder method that the user must implement in their custom * implementation. * * @param viewGroup * @param viewType * @return the ViewHolder that corresponds to the item at the position. */ @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { if (viewType == TYPE_PARENT) { PVH pvh = onCreateParentViewHolder(viewGroup); pvh.setParentItemExpandCollapseListener(this); return pvh; } else if (viewType == TYPE_CHILD) { return onCreateChildViewHolder(viewGroup); } else { throw new IllegalStateException("Incorrect ViewType found"); } } /** * Override of RecyclerView's default onBindViewHolder * * This implementation determines first if the ViewHolder is a ParentViewHolder or a * ChildViewHolder. The respective onBindViewHolders for ParentObjects and ChildObject are then * called. * * If the item is a ParentObject, sets the entire row to trigger expansion if instructed to * * @param holder * @param position * @throws IllegalStateException if the item in the list is neither a ParentObject or ChildObject */ @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { Object helperItem = getHelperItem(position); if (helperItem instanceof ParentWrapper) { PVH parentViewHolder = (PVH) holder; if (parentViewHolder.shouldItemViewClickToggleExpansion()) { parentViewHolder.setMainItemClickToExpand(); } ParentWrapper parentWrapper = (ParentWrapper) helperItem; parentViewHolder.setExpanded(parentWrapper.isExpanded()); onBindParentViewHolder(parentViewHolder, position, parentWrapper.getParentObject()); } else if (helperItem == null) { throw new IllegalStateException("Incorrect ViewHolder found"); } else { onBindChildViewHolder((CVH) holder, position, helperItem); } } /** * Creates the Parent ViewHolder. Called from onCreateViewHolder when the item is a ParenObject. * * @param parentViewGroup * @return ParentViewHolder that the user must create and inflate. */ public abstract PVH onCreateParentViewHolder(ViewGroup parentViewGroup); /** * Creates the Child ViewHolder. Called from onCreateViewHolder when the item is a ChildObject. * * @param childViewGroup * @return ChildViewHolder that the user must create and inflate. */ public abstract CVH onCreateChildViewHolder(ViewGroup childViewGroup); /** * Binds the data to the ParentViewHolder. Called from onBindViewHolder when the item is a * ParentObject * * @param parentViewHolder * @param position */ public abstract void onBindParentViewHolder(PVH parentViewHolder, int position, Object parentObject); /** * Binds the data to the ChildViewHolder. Called from onBindViewHolder when the item is a * ChildObject * * @param childViewHolder * @param position */ public abstract void onBindChildViewHolder(CVH childViewHolder, int position, Object childObject); /** * Returns the size of the list that contains Parent and Child objects * * @return integer value of the size of the Parent/Child list */ @Override public int getItemCount() { return mHelperItemList.size(); } /** * Returns the type of view that the item at the given position is. * * @param position * @return TYPE_PARENT (0) for ParentObjects and TYPE_CHILD (1) for ChildObjects * @throws IllegalStateException if the item at the given position in the list is null */ @Override public int getItemViewType(int position) { Object helperItem = getHelperItem(position); if (helperItem instanceof ParentWrapper) { return TYPE_PARENT; } else if (helperItem == null) { throw new IllegalStateException("Null object added"); } else { return TYPE_CHILD; } } @Override public void onParentItemExpanded(int position) { Object helperItem = getHelperItem(position); if (helperItem instanceof ParentWrapper) { expandHelperItem((ParentWrapper) helperItem, position, false); } } @Override public void onParentItemCollapsed(int position) { Object helperItem = getHelperItem(position); if (helperItem instanceof ParentWrapper) { collapseHelperItem((ParentWrapper) helperItem, position, false); } } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); mAttachedRecyclerViewPool.add(recyclerView); } @Override public void onDetachedFromRecyclerView(RecyclerView recyclerView) { super.onDetachedFromRecyclerView(recyclerView); mAttachedRecyclerViewPool.remove(recyclerView); } public void addExpandCollapseListener(ExpandCollapseListener expandCollapseListener) { mExpandCollapseListener = expandCollapseListener; } /** * Expands the parent with the specified index in the list of parents. * * @param parentIndex The index of the parent to expand */ public void expandParent(int parentIndex) { int parentWrapperIndex = getParentWrapperIndex(parentIndex); Object helperItem = getHelperItem(parentWrapperIndex); ParentWrapper parentWrapper; if (helperItem instanceof ParentWrapper) { parentWrapper = (ParentWrapper) helperItem; } else { return; } expandViews(parentWrapper, parentWrapperIndex); } /** * Expands the parent associated with a specified {@link ParentObject} in * the list of parents. * * @param parentObject The {@code ParentObject} of the parent to expand */ public void expandParent(ParentObject parentObject) { ParentWrapper parentWrapper = getParentWrapper(parentObject); int parentWrapperIndex = mHelperItemList.indexOf(parentWrapper); if (parentWrapperIndex == -1) { return; } expandViews(parentWrapper, parentWrapperIndex); } /** * Expands all parents in the list. */ public void expandAllParents() { for (ParentObject parentObject : mParentItemList) { expandParent(parentObject); } } /** * Collapses the parent with the specified index in the list of parents. * * @param parentIndex The index of the parent to expand */ public void collapseParent(int parentIndex) { int parentWrapperIndex = getParentWrapperIndex(parentIndex); Object helperItem = getHelperItem(parentWrapperIndex); ParentWrapper parentWrapper; if (helperItem instanceof ParentWrapper) { parentWrapper = (ParentWrapper) helperItem; } else { return; } collapseViews(parentWrapper, parentWrapperIndex); } /** * Collapses the parent associated with a specified {@link ParentObject} in * the list of parents. * * @param parentObject The {@code ParentObject} of the parent to collapse */ public void collapseParent(ParentObject parentObject) { ParentWrapper parentWrapper = getParentWrapper(parentObject); int parentWrapperIndex = mHelperItemList.indexOf(parentWrapper); if (parentWrapperIndex == -1) { return; } collapseViews(parentWrapper, parentWrapperIndex); } /** * Collapses all parents in the list. */ public void collapseAllParents() { for (ParentObject parentObject : mParentItemList) { collapseParent(parentObject); } } /** * Calls through to the {@link ParentViewHolder} to expand views for each * {@link RecyclerView} a specified parent is a child of. These calls to * the {@code ParentViewHolder} are made so that animations can be * triggered at the {@link android.support.v7.widget.RecyclerView.ViewHolder} * level. * * @param parentIndex The inject of the parent to expand */ private void expandViews(ParentWrapper parentWrapper, int parentIndex) { for (RecyclerView recyclerView : mAttachedRecyclerViewPool) { RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(parentIndex); if (viewHolder != null && !((ParentViewHolder) viewHolder).isExpanded()) { ((ParentViewHolder) viewHolder).setExpanded(true); ((ParentViewHolder) viewHolder).onExpansionToggled(false); } expandHelperItem(parentWrapper, parentIndex, true); } } /** * Calls through to the {@link ParentViewHolder} to collapse views for each * {@link RecyclerView} a specified parent is a child of. These calls to * the {@code ParentViewHolder} are made so that animations can be * triggered at the {@link android.support.v7.widget.RecyclerView.ViewHolder} * level. * * @param parentIndex The inject of the parent to collapse */ private void collapseViews(ParentWrapper parentWrapper, int parentIndex) { for (RecyclerView recyclerView : mAttachedRecyclerViewPool) { RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(parentIndex); if (viewHolder != null && ((ParentViewHolder) viewHolder).isExpanded()) { ((ParentViewHolder) viewHolder).setExpanded(false); ((ParentViewHolder) viewHolder).onExpansionToggled(true); } collapseHelperItem(parentWrapper, parentIndex, true); } } /** * Expands a specified parent item. Calls through to the {@link ExpandCollapseListener} * and adds children of the specified parent to the total list of items. * * @param parentWrapper The {@link ParentWrapper} of the parent to expand * @param parentIndex The index of the parent to expand * @param expansionTriggeredProgrammatically {@value false} if expansion was triggered by a * click event, {@value false} otherwise. */ private void expandHelperItem(ParentWrapper parentWrapper, int parentIndex, boolean expansionTriggeredProgrammatically) { if (!parentWrapper.isExpanded()) { parentWrapper.setExpanded(true); if (expansionTriggeredProgrammatically && mExpandCollapseListener != null) { int expandedCountBeforePosition = getExpandedItemCount(parentIndex); mExpandCollapseListener.onRecyclerViewItemExpanded(parentIndex - expandedCountBeforePosition); } mStableIdMap.put(parentWrapper.getStableId(), true); List<Object> childObjectList = parentWrapper.getParentObject().getChildObjectList(); if (childObjectList != null) { int numChildObjects = childObjectList.size(); for (int i = 0; i < numChildObjects; i++) { mHelperItemList.add(parentIndex + i + 1, childObjectList.get(i)); notifyItemInserted(parentIndex + i + 1); } } } } /** * Collapses a specified parent item. Calls through to the {@link ExpandCollapseListener} * and adds children of the specified parent to the total list of items. * * @param parentWrapper The {@link ParentWrapper} of the parent to collapse * @param parentIndex The index of the parent to collapse * @param collapseTriggeredProgrammatically {@value false} if expansion was triggered by a * click event, {@value false} otherwise. */ private void collapseHelperItem(ParentWrapper parentWrapper, int parentIndex, boolean collapseTriggeredProgrammatically) { if (parentWrapper.isExpanded()) { parentWrapper.setExpanded(false); if (collapseTriggeredProgrammatically && mExpandCollapseListener != null) { int expandedCountBeforePosition = getExpandedItemCount(parentIndex); mExpandCollapseListener.onRecyclerViewItemCollapsed(parentIndex - expandedCountBeforePosition); } mStableIdMap.put(parentWrapper.getStableId(), false); List<Object> childObjectList = parentWrapper.getParentObject().getChildObjectList(); if (childObjectList != null) { for (int i = childObjectList.size() - 1; i >= 0; i--) { mHelperItemList.remove(parentIndex + i + 1); notifyItemRemoved(parentIndex + i + 1); } } } } /** * Method to get the number of expanded children before the specified position. * * @param position * @return number of expanded children before the specified position */ private int getExpandedItemCount(int position) { if (position == 0) { return 0; } int expandedCount = 0; for (int i = 0; i < position; i++) { Object object = getHelperItem(i); if (!(object instanceof ParentWrapper)) { expandedCount++; } } return expandedCount; } /** * Generates a HashMap for storing expanded state when activity is rotated or onResume() is called. * * @param itemList * @return HashMap containing the Object's stable id along with a boolean indicating its expanded * state */ private HashMap<Long, Boolean> generateStableIdMapFromList(List<Object> itemList) { HashMap<Long, Boolean> parentObjectHashMap = new HashMap<>(); for (int i = 0; i < itemList.size(); i++) { if (itemList.get(i) != null) { Object helperItem = getHelperItem(i); if (helperItem instanceof ParentWrapper) { ParentWrapper parentWrapper = (ParentWrapper) helperItem; parentObjectHashMap.put(parentWrapper.getStableId(), parentWrapper.isExpanded()); } } } return parentObjectHashMap; } /** * Should be called from onSaveInstanceState of Activity that holds the RecyclerView. This will * make sure to add the generated HashMap as an extra to the bundle to be used in * OnRestoreInstanceState(). * * @param savedInstanceStateBundle * @return the Bundle passed in with the Id HashMap added if applicable */ public Bundle onSaveInstanceState(Bundle savedInstanceStateBundle) { savedInstanceStateBundle.putSerializable(STABLE_ID_MAP, mStableIdMap); return savedInstanceStateBundle; } /** * Should be called from onRestoreInstanceState of Activity that contains the ExpandingRecyclerView. * This will fetch the HashMap that was saved in onSaveInstanceState() and use it to restore * the expanded states before the rotation or onSaveInstanceState was called. * * @param savedInstanceStateBundle */ public void onRestoreInstanceState(Bundle savedInstanceStateBundle) { if (savedInstanceStateBundle == null) { return; } if (!savedInstanceStateBundle.containsKey(STABLE_ID_MAP)) { return; } mStableIdMap = (HashMap<Long, Boolean>) savedInstanceStateBundle.getSerializable(STABLE_ID_MAP); int i = 0; while (i < mHelperItemList.size()) { Object helperItem = getHelperItem(i); if (helperItem instanceof ParentWrapper) { ParentWrapper parentWrapper = (ParentWrapper) helperItem; if (mStableIdMap.containsKey(parentWrapper.getStableId())) { parentWrapper.setExpanded(mStableIdMap.get(parentWrapper.getStableId())); if (parentWrapper.isExpanded() && !parentWrapper.getParentObject().isInitiallyExpanded()) { List<Object> childObjectList = parentWrapper.getParentObject().getChildObjectList(); if (childObjectList != null) { for (int j = 0; j < childObjectList.size(); j++) { i++; mHelperItemList.add(i, childObjectList.get(j)); } } } else if (!parentWrapper.isExpanded() && parentWrapper.getParentObject().isInitiallyExpanded()) { List<Object> childObjectList = parentWrapper.getParentObject().getChildObjectList(); for (int j = 0; j < childObjectList.size(); j++) { mHelperItemList.remove(i + 1); } } } else { parentWrapper.setExpanded(false); } } i++; } notifyDataSetChanged(); } private Object getHelperItem(int position) { return mHelperItemList.get(position); } /** * Gets the index of a {@link ParentWrapper} within the helper item list * based on the index of the {@code ParentWrapper}. * * @param parentIndex The index of the parent in the list of parent items * @return The index of the parent in the list of all views in the adapter */ private int getParentWrapperIndex(int parentIndex) { int parentWrapperIndex = -1; int parentCount = 0; int numHelperItems = mHelperItemList.size(); for (int i = 0; i < numHelperItems; i++) { if (mHelperItemList.get(i) instanceof ParentWrapper) { parentCount++; if (parentCount > parentIndex) { parentWrapperIndex = i; break; } } } return parentWrapperIndex; } /** * Gets the {@link ParentWrapper} for a specified {@link ParentObject} from * the list of parents. * * @param parentObject A {@code ParentObject} in the list of parents * @return If the parent exists on the list, returns its {@code ParentWrapper}. * Otherwise, returns {@value null}. */ private ParentWrapper getParentWrapper(ParentObject parentObject) { ParentWrapper parentWrapper = null; int numHelperItems = mHelperItemList.size(); for (int i = 0; i < numHelperItems; i++) { Object helperItem = mHelperItemList.get(i); if (helperItem instanceof ParentWrapper) { if (((ParentWrapper) helperItem).getParentObject().equals(parentObject)) { parentWrapper = (ParentWrapper) helperItem; } } } return parentWrapper; } }
Broke out of loop when ParentWrapper found
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/Adapter/ExpandableRecyclerAdapter.java
Broke out of loop when ParentWrapper found
Java
mit
e9fa1b704b5923dcb2e5e7f40d94a3eaafbdedcc
0
HoboOthello/HoboOthello
package de.htw_berlin.HoboOthello.core; /** * Created by laura on 17.11.16. */ public class Board { public static final int STANDARD_BOARD_SIZE_EIGHT = 8; public static final int SMALL_BOARD_SIZE_SIX = 6; public static final int LARGE_BOARD_SIZE_TEN = 10; private Field[][] fields; /** * Constructor of Board which declares and constructs an two dimensional array of fields * Small size of Board is 6 x 6 * Standard size of Board is 8 x 8 * Large size of Board is 10 x 10 * Calls a method to fill the field with default values */ public Board(int i) { switch (i){ case 6: fields = new Field[SMALL_BOARD_SIZE_SIX][SMALL_BOARD_SIZE_SIX]; fields = fillWithDefaultValues(fields); break; case 8: fields = new Field[STANDARD_BOARD_SIZE_EIGHT][STANDARD_BOARD_SIZE_EIGHT]; fields = fillWithDefaultValues(fields); break; case 10: fields = new Field[LARGE_BOARD_SIZE_TEN][LARGE_BOARD_SIZE_TEN]; fields = fillWithDefaultValues(fields); break; default: System.out.println("Invalid size for a HoboOthello Board"); //todo : decide if case 8 becomes default } } /** * Method which fills fields with default values. * Default value of a field is: * empty = true * white = false * black = false * <p> * @param fields fields which are being filled * @return fields with default values (true, false, false) */ private Field[][] fillWithDefaultValues(Field[][] fields) { for (int i = 0; i < fields.length; i++) { for (int j = 0; j < fields.length; j++) { fields[i][j] = new Field(true, false, false); } } return fields; } }
src/main/java/de/htw_berlin/HoboOthello/core/Board.java
package de.htw_berlin.HoboOthello.core; /** * Created by laura on 17.11.16. */ public class Board { public static final int STANDARD_BOARD_SIZE_EIGHT = 8; public static final int SMALL_BOARD_SIZE_SIX = 6; public static final int LARGE_BOARD_SIZE_TEN = 10; private Field[][] fields; /** * Constructor of Board which declares and constructs an two dimensional array of fields * Standard size of Board is 8 x 8 * Calls a method to fill with default values */ public Board(int i) { while(true) { if (i == 6) { fields = new Field[SMALL_BOARD_SIZE_SIX][SMALL_BOARD_SIZE_SIX]; fields = fillWithDefaultValues(fields); } if (i == 8) { fields = new Field[STANDARD_BOARD_SIZE_EIGHT][STANDARD_BOARD_SIZE_EIGHT]; fields = fillWithDefaultValues(fields); } if (i == 10) { fields = new Field[LARGE_BOARD_SIZE_TEN][LARGE_BOARD_SIZE_TEN]; fields = fillWithDefaultValues(fields); } else { System.out.println("Invalid size for a HoboOthello Board"); } } } /** * Method which fills fields with default values. * Default value is: * empty = true * white = false * black = false * <p> * @param fields fields which are being filled * @return fields with default values (true, false, false) */ private Field[][] fillWithDefaultValues(Field[][] fields) { for (int i = 0; i < fields.length; i++) { for (int j = 0; j < fields.length; j++) { fields[i][j] = new Field(true, false, false); } } return fields; } }
changed the board constructor to a switch case. default could be changed to 8x8 if we decide to do so
src/main/java/de/htw_berlin/HoboOthello/core/Board.java
changed the board constructor to a switch case. default could be changed to 8x8 if we decide to do so
Java
epl-1.0
6c1a203c486dfc683b765847990a9d0c2c061a4a
0
SiriusLab/ModelDebugging,SiriusLab/SiriusAnimator,SiriusLab/ModelDebugging,SiriusLab/ModelDebugging,SiriusLab/SiriusAnimator,SiriusLab/SiriusAnimator
package fr.inria.diverse.trace.gemoc.traceaddon; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.xtext.naming.DefaultDeclarativeQualifiedNameProvider; import org.eclipse.xtext.naming.QualifiedName; import org.gemoc.xdsmlframework.api.core.IDisposable; import fr.inria.diverse.trace.api.IStep; import fr.inria.diverse.trace.api.IStep.StepEvent; import fr.inria.diverse.trace.api.ITraceManager; import fr.inria.diverse.trace.api.IValueTrace; import fr.inria.diverse.trace.gemoc.api.ISimpleTimeLineNotifier; public class WrapperSimpleTimeLine extends AbstractSequentialTimelineProvider implements IDisposable, ISimpleTimeLineNotifier { protected ITraceManager traceManager; private List<IValueTrace> cache; private final DefaultDeclarativeQualifiedNameProvider nameprovider = new DefaultDeclarativeQualifiedNameProvider(); protected List<IValueTrace> getAllValueTraces() { if (cache == null) this.cache = traceManager.getAllValueTraces(); return cache; } @Override public void setTraceManager(ITraceManager m) { this.traceManager = m; } /** * Constructor. * * @param simpleProvider * The provider of the xDSML. * @param engine * The engine used for the execution. */ public WrapperSimpleTimeLine(ITraceManager manager) { this.traceManager = manager; } public WrapperSimpleTimeLine() { } /** * WARNING: notifyEndChanged is WRONG, since it asks an index and requires a length! */ @Override public void notifyTimeLine() { if (traceManager != null) { notifyEndChanged(0, traceManager.getTraceSize()); notifyIsSelectedChanged(0, 0, 0, true); } } @Override public int getNumberOfBranches() { if (traceManager == null) { return 1; } return 1 + traceManager.getNumberOfValueTraces(); } @Override public int getStart(int branch) { return 0; } @Override public int getEnd(int branch) { if (traceManager == null) { return 0; } if (branch == 0) return traceManager.getTraceSize(); else return getAllValueTraces().get(branch - 1).getSize(); } @Override public String getTextAt(int branch, int index, int possibleStep) { if (branch == 0) { return traceManager.getDescriptionOfExecutionState(index); } else { String result = ""; try { result += traceManager.getContainedValue(getAllValueTraces().get(branch - 1).getValue(index)); } catch (IllegalStateException e) { e.printStackTrace(); result = traceManager.getDescriptionOfValue(getAllValueTraces().get(branch - 1).getValue(index)); } return result; } } /* * (non-Javadoc) * @see fr.obeo.timeline.view.ITimelineProvider#getTextAt(int) * Used to get the label of the dynamic information timelines. */ @Override public String getTextAt(int branch) { if (branch == 0) { return "All execution states (" + traceManager.getTraceSize() + ")"; } else { IValueTrace trace = getAllValueTraces().get(branch - 1); EObject value = trace.getValue(0); if (value == null) { return ""; } EObject container = value.eContainer(); List<String> attributes = container.eClass().getEAllReferences().stream() .filter(r->r.getName().endsWith("Sequence")) .map(r->r.getName().substring(0,r.getName().length()-8)) .collect(Collectors.toList()); String attributeName = ""; if (!attributes.isEmpty()) { attributeName = attributes.stream().filter(s->value.getClass().getName().contains("_"+s+"_")).collect(Collectors.toList()).get(0); } Optional<EReference> originalObject = container.eClass().getEAllReferences().stream().filter(r->r.getName().equals("originalObject")).findFirst(); if (originalObject.isPresent()) { Object o = container.eGet(originalObject.get()); if (o instanceof EObject) { EObject eObject = (EObject) o; QualifiedName qname = nameprovider.getFullyQualifiedName(eObject); if(qname == null) { return attributeName + " (" + eObject.toString() + ")"; } else { return attributeName + " (" + qname.toString() + " :" + eObject.eClass().getName() + ")"; } } } return attributeName; } } @Override public int getNumberOfPossibleStepsAt(int branch, int index) { return 1; } @Override public String getTextAt(int branch, int index) { return "DISABLED"; } @Override /* * (non-Javadoc) Asks whether the bubble at "index" is yellow or blue. Well not really, but in our case yes. -1 * means yellow, 0 means blue. * * @see fr.obeo.timeline.view.ITimelineProvider#getSelectedPossibleStep(int, int) */ public int getSelectedPossibleStep(int branch, int index) { if (branch == 0) { if (traceManager.getTraceSize() - 1 == index) return -1; else return 0; } else { IValueTrace trace = getAllValueTraces().get(branch - 1); if (trace.getSize() - 1 == index) return -1; else return 0; } } @Override public Object getAt(int branch, int index, int possibleStep) { return getAt(branch, index); } @Override public Object getAt(int branch, int index) { if (branch == 0) { if (traceManager.getTraceSize() > index) { return traceManager.getExecutionState(index); } } else { if (getAllValueTraces().size() > index) { return getAllValueTraces().get(branch - 1).getValue(index); } } return null; } @Override public int[][] getFollowings(int branch, int index, int possibleStep) { return new int[0][0]; } @Override public int[][] getPrecedings(int branch, int index, int possibleStep) { return new int[0][0]; } @Override public void dispose() { } @Override public List<StateWrapper> getStatesOrValues(int line, int startStateIndex, int endStateIndex) { List<StateWrapper> result = new ArrayList<>(); startStateIndex = Math.max(0, startStateIndex); endStateIndex = Math.min(traceManager.getTraceSize(), endStateIndex); if (line == 0) { for (int i=startStateIndex;i<endStateIndex;i++) { result.add(new StateWrapper(traceManager.getExecutionState(i), i, i, i)); } } else if (line-1<getAllValueTraces().size()) { // Getting the trace we want to gather values from IValueTrace valueTrace = getAllValueTraces().get(line - 1); // Initializing the index of the current value int valueStartIndex = -1; for (int i=startStateIndex;i<endStateIndex;i++) { // We get the starting index of the current value in the value trace. int startIndex = valueTrace.getActiveValueStartingState(i); if (startIndex != valueStartIndex) { // If it points to a new value if (valueStartIndex != -1) { // If we have a current value result.add(new StateWrapper(valueTrace.getActiveValue(valueStartIndex), valueStartIndex, valueTrace.getActiveValueIndex(valueStartIndex), i - 1)); } valueStartIndex = startIndex; } } // If the last value does not end before the endStateIndex parameter, // we iterate until we find the actual end of the value. if (valueStartIndex != -1) { int i = endStateIndex; int endIndex = traceManager.getTraceSize() - 1; while (i < traceManager.getTraceSize()) { int startIndex = valueTrace.getActiveValueStartingState(i); if (startIndex != valueStartIndex) { endIndex = i - 1; break; } i++; } result.add(new StateWrapper(valueTrace.getActiveValue(valueStartIndex), valueStartIndex, valueTrace.getActiveValueIndex(valueStartIndex), endIndex)); } } return result; } @Override public List<StepEvent> getStepEventsForState(int stateIndex) { if (stateIndex > -1 && stateIndex < traceManager.getTraceSize()) { return traceManager.getEventsForState(stateIndex); } else { return new ArrayList<>(); } } @Override public Map<IStep,List<IStep>> getStepsForStates(int startingState, int endingState) { return traceManager.getStepsForStates(startingState, endingState); } @Override public int getCurrentBranch() { // TODO Auto-generated method stub return -1; } @Override public int getCurrentChoice() { // TODO Auto-generated method stub return -1; } @Override public int getCurrentPossibleStep() { // TODO Auto-generated method stub return -1; } }
trace/generator/plugins/fr.inria.diverse.trace.gemoc/src/fr/inria/diverse/trace/gemoc/traceaddon/WrapperSimpleTimeLine.java
package fr.inria.diverse.trace.gemoc.traceaddon; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.xtext.naming.DefaultDeclarativeQualifiedNameProvider; import org.eclipse.xtext.naming.QualifiedName; import org.gemoc.xdsmlframework.api.core.IDisposable; import fr.inria.diverse.trace.api.IStep; import fr.inria.diverse.trace.api.IStep.StepEvent; import fr.inria.diverse.trace.api.ITraceManager; import fr.inria.diverse.trace.api.IValueTrace; import fr.inria.diverse.trace.gemoc.api.ISimpleTimeLineNotifier; public class WrapperSimpleTimeLine extends AbstractSequentialTimelineProvider implements IDisposable, ISimpleTimeLineNotifier { protected ITraceManager traceManager; private List<IValueTrace> cache; private final DefaultDeclarativeQualifiedNameProvider nameprovider = new DefaultDeclarativeQualifiedNameProvider(); protected List<IValueTrace> getAllValueTraces() { if (cache == null) this.cache = traceManager.getAllValueTraces(); return cache; } @Override public void setTraceManager(ITraceManager m) { this.traceManager = m; } /** * Constructor. * * @param simpleProvider * The provider of the xDSML. * @param engine * The engine used for the execution. */ public WrapperSimpleTimeLine(ITraceManager manager) { this.traceManager = manager; } public WrapperSimpleTimeLine() { } /** * WARNING: notifyEndChanged is WRONG, since it asks an index and requires a length! */ @Override public void notifyTimeLine() { if (traceManager != null) { notifyEndChanged(0, traceManager.getTraceSize()); notifyIsSelectedChanged(0, 0, 0, true); } } @Override public int getNumberOfBranches() { if (traceManager == null) { return 1; } return 1 + traceManager.getNumberOfValueTraces(); } @Override public int getStart(int branch) { return 0; } @Override public int getEnd(int branch) { if (traceManager == null) { return 0; } if (branch == 0) return traceManager.getTraceSize(); else return getAllValueTraces().get(branch - 1).getSize(); } @Override public String getTextAt(int branch, int index, int possibleStep) { if (branch == 0) { return traceManager.getDescriptionOfExecutionState(index); } else { String result = ""; try { result += traceManager.getContainedValue(getAllValueTraces().get(branch - 1).getValue(index)); } catch (IllegalStateException e) { e.printStackTrace(); result = traceManager.getDescriptionOfValue(getAllValueTraces().get(branch - 1).getValue(index)); } return result; } } /* * (non-Javadoc) * @see fr.obeo.timeline.view.ITimelineProvider#getTextAt(int) * Used to get the label of the dynamic information timelines. */ @Override public String getTextAt(int branch) { if (branch == 0) { return "All execution states (" + traceManager.getTraceSize() + ")"; } else { IValueTrace trace = getAllValueTraces().get(branch - 1); EObject value = trace.getValue(0); if (value == null) { return ""; } EObject container = value.eContainer(); List<String> attributes = container.eClass().getEAllReferences().stream() .filter(r->r.getName().endsWith("Sequence")) .map(r->r.getName().substring(0,r.getName().length()-8)) .collect(Collectors.toList()); String attributeName = ""; if (!attributes.isEmpty()) { attributeName = attributes.stream().filter(s->value.getClass().getName().contains("_"+s+"_")).collect(Collectors.toList()).get(0); } Optional<EReference> originalObject = container.eClass().getEAllReferences().stream().filter(r->r.getName().equals("originalObject")).findFirst(); if (originalObject.isPresent()) { Object o = container.eGet(originalObject.get()); if (o instanceof EObject) { EObject eObject = (EObject) o; QualifiedName qname = nameprovider.getFullyQualifiedName(eObject); if(qname == null) { return attributeName + " (" + eObject.toString() + ")"; } else { return attributeName + " (" + qname.toString() + " :" + eObject.eClass().getName() + ")"; } } } return attributeName; } } @Override public int getNumberOfPossibleStepsAt(int branch, int index) { return 1; } @Override public String getTextAt(int branch, int index) { return "DISABLED"; } @Override /* * (non-Javadoc) Asks whether the bubble at "index" is yellow or blue. Well not really, but in our case yes. -1 * means yellow, 0 means blue. * * @see fr.obeo.timeline.view.ITimelineProvider#getSelectedPossibleStep(int, int) */ public int getSelectedPossibleStep(int branch, int index) { if (branch == 0) { if (traceManager.getTraceSize() - 1 == index) return -1; else return 0; } else { IValueTrace trace = getAllValueTraces().get(branch - 1); if (trace.getSize() - 1 == index) return -1; else return 0; } } @Override public Object getAt(int branch, int index, int possibleStep) { return getAt(branch, index); } @Override public Object getAt(int branch, int index) { if (branch == 0) { if (traceManager.getTraceSize() > index) { return traceManager.getExecutionState(index); } } else { if (getAllValueTraces().size() > index) { return getAllValueTraces().get(branch - 1).getValue(index); } } return null; } @Override public int[][] getFollowings(int branch, int index, int possibleStep) { return new int[0][0]; } @Override public int[][] getPrecedings(int branch, int index, int possibleStep) { return new int[0][0]; } @Override public void dispose() { } @Override public List<StateWrapper> getStatesOrValues(int line, int startStateIndex, int endStateIndex) { List<StateWrapper> result = new ArrayList<>(); startStateIndex = Math.max(0, startStateIndex); endStateIndex = Math.min(traceManager.getTraceSize(), endStateIndex); if (line == 0) { for (int i=startStateIndex;i<endStateIndex;i++) { result.add(new StateWrapper(traceManager.getExecutionState(i), i, i, i)); } } else if (line-1<getAllValueTraces().size()) { // Getting the trace we want to gather values from IValueTrace valueTrace = getAllValueTraces().get(line - 1); // Initializing the index of the current value int valueStartIndex = -1; for (int i=startStateIndex;i<endStateIndex;i++) { // We get the starting index of the current value in the value trace. int startIndex = valueTrace.getActiveValueStartingState(i); if (startIndex != valueStartIndex) { // If it points to a new value if (valueStartIndex != -1) { // If we have a current value result.add(new StateWrapper(valueTrace.getActiveValue(valueStartIndex), valueStartIndex, valueTrace.getActiveValueIndex(valueStartIndex), i - 1)); } valueStartIndex = startIndex; } } // If the last value does not end before the endStateIndex parameter, // we iterate until we find the actual end of the value. if (valueStartIndex != -1) { int i = endStateIndex; int endIndex = traceManager.getTraceSize() - 1; while (i < traceManager.getTraceSize()) { int startIndex = valueTrace.getActiveValueStartingState(i); if (startIndex != valueStartIndex) { endIndex = i - 1; break; } i++; } result.add(new StateWrapper(valueTrace.getActiveValue(valueStartIndex), valueStartIndex, valueTrace.getActiveValueIndex(valueStartIndex), endIndex)); } } return result; } @Override public List<StepEvent> getStepEventsForState(int stateIndex) { if (stateIndex > -1 && stateIndex < traceManager.getTraceSize()) { return traceManager.getEventsForState(stateIndex); } else { return new ArrayList<>(); } } @Override public Map<IStep,List<IStep>> getStepsForStates(int startingState, int endingState) { return traceManager.getStepsForStates(startingState, endingState); } }
Added current branch/choice/possible step informations to ITimelineProvider.
trace/generator/plugins/fr.inria.diverse.trace.gemoc/src/fr/inria/diverse/trace/gemoc/traceaddon/WrapperSimpleTimeLine.java
Added current branch/choice/possible step informations to ITimelineProvider.
Java
agpl-3.0
06919bc3262b35343351db39840561d69f91f8b9
0
UniversityOfHawaiiORS/kc,ColostateResearchServices/kc,jwillia/kc-old1,jwillia/kc-old1,mukadder/kc,jwillia/kc-old1,ColostateResearchServices/kc,iu-uits-es/kc,kuali/kc,geothomasp/kcmit,geothomasp/kcmit,geothomasp/kcmit,mukadder/kc,iu-uits-es/kc,kuali/kc,UniversityOfHawaiiORS/kc,geothomasp/kcmit,geothomasp/kcmit,mukadder/kc,kuali/kc,UniversityOfHawaiiORS/kc,jwillia/kc-old1,ColostateResearchServices/kc,iu-uits-es/kc
/* * Copyright 2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.proposaldevelopment.web.struts.action; import static java.util.Collections.sort; import static org.kuali.kra.infrastructure.KraServiceLocator.getService; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.kuali.core.bo.PersistableBusinessObject; import org.kuali.core.service.KualiConfigurationService; import org.kuali.core.service.KualiRuleService; import org.kuali.core.util.GlobalVariables; import org.kuali.kra.bo.Rolodex; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.KraServiceLocator; import org.kuali.kra.proposaldevelopment.bo.PropScienceKeyword; import org.kuali.kra.proposaldevelopment.bo.ProposalLocation; import org.kuali.kra.proposaldevelopment.bo.ProposalPersonComparator; import org.kuali.kra.proposaldevelopment.bo.ScienceKeyword; import org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument; import org.kuali.kra.proposaldevelopment.rule.event.AddProposalLocationEvent; import org.kuali.kra.proposaldevelopment.service.ProposalDevelopmentService; import org.kuali.kra.proposaldevelopment.web.struts.form.ProposalDevelopmentForm; import org.kuali.kra.service.SponsorService; import org.kuali.rice.KNSServiceLocator; public class ProposalDevelopmentProposalAction extends ProposalDevelopmentAction { private static final Log LOG = LogFactory.getLog(ProposalDevelopmentProposalAction.class); @Override public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setKeywordsPanelFlag(request); ProposalDevelopmentDocument proposalDevelopmentDocument = ((ProposalDevelopmentForm) form).getProposalDevelopmentDocument(); KraServiceLocator.getService(ProposalDevelopmentService.class).initializeUnitOrganzationLocation( proposalDevelopmentDocument); return super.save(mapping, form, request, response); } @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward actionForward = super.execute(mapping, form, request, response); setKeywordsPanelFlag(request); ProposalDevelopmentDocument proposalDevelopmentDocument = ((ProposalDevelopmentForm) form).getProposalDevelopmentDocument(); if (proposalDevelopmentDocument.getOrganizationId() != null && proposalDevelopmentDocument.getProposalLocations().size() == 0 && StringUtils.isNotBlank(request.getParameter("methodToCall")) && request.getParameter("methodToCall").toString().equals("refresh") && StringUtils.isNotBlank(request.getParameter("refreshCaller")) && request.getParameter("refreshCaller").toString().equals("kualiLookupable") && StringUtils.isNotBlank(request.getParameter("document.organizationId"))) { // populate 1st location. Not sure yet ProposalLocation propLocation = new ProposalLocation(); propLocation.setLocation(proposalDevelopmentDocument.getOrganization().getOrganizationName()); propLocation.setLocationSequenceNumber(proposalDevelopmentDocument .getDocumentNextValue(Constants.PROPOSAL_LOCATION_SEQUENCE_NUMBER)); proposalDevelopmentDocument.getProposalLocations().add(propLocation); } // populate the Prime Sponsor Name if we have the code // this is necessary since the name is only on the form not the document // and it is only populated by a lookup or through AJAX/DWR String primeSponsorCode = proposalDevelopmentDocument.getPrimeSponsorCode(); if (StringUtils.isNotEmpty(primeSponsorCode)) { String primeSponsorName = (KraServiceLocator.getService(SponsorService.class).getSponsorName(primeSponsorCode)); if (StringUtils.isEmpty(primeSponsorName)) { primeSponsorName = "not found"; } ((ProposalDevelopmentForm) form).setPrimeSponsorName(primeSponsorName); } else { // TODO: why do we have to do this? ((ProposalDevelopmentForm) form).setPrimeSponsorName(null); } if (proposalDevelopmentDocument.getProposalPersons().size() > 0) sort(proposalDevelopmentDocument.getProposalPersons(), new ProposalPersonComparator()); if (proposalDevelopmentDocument.getInvestigators().size() > 0) sort(proposalDevelopmentDocument.getInvestigators(), new ProposalPersonComparator()); return actionForward; } /** * * This method sets the flag for keyword display panel - display keyword panel if parameter is set to true * * @param request */ private void setKeywordsPanelFlag(HttpServletRequest request) { String keywordPanelDisplay = KraServiceLocator.getService(KualiConfigurationService.class).getParameterValue( Constants.PARAMETER_MODULE_PROPOSAL_DEVELOPMENT, Constants.PARAMETER_COMPONENT_DOCUMENT, Constants.KEYWORD_PANEL_DISPLAY); request.getSession().setAttribute(Constants.KEYWORD_PANEL_DISPLAY, keywordPanelDisplay); } /** * * Add new location to proposal document and reset newProplocation from form. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward addLocation(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ProposalDevelopmentForm proposalDevelopmentForm = (ProposalDevelopmentForm) form; ProposalLocation newProposalLocation = proposalDevelopmentForm.getNewPropLocation(); if (getKualiRuleService().applyRules( new AddProposalLocationEvent(Constants.EMPTY_STRING, proposalDevelopmentForm.getProposalDevelopmentDocument(), newProposalLocation))) { newProposalLocation.setLocationSequenceNumber(proposalDevelopmentForm.getProposalDevelopmentDocument() .getDocumentNextValue(Constants.PROPOSAL_LOCATION_SEQUENCE_NUMBER)); proposalDevelopmentForm.getProposalDevelopmentDocument().getProposalLocations().add(newProposalLocation); proposalDevelopmentForm.setNewPropLocation(new ProposalLocation()); } return mapping.findForward("basic"); } /** * * Delete one location/site from proposal document * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward deleteLocation(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ProposalDevelopmentForm proposalDevelopmentForm = (ProposalDevelopmentForm) form; proposalDevelopmentForm.getProposalDevelopmentDocument().getProposalLocations().remove(getLineToDelete(request)); return mapping.findForward("basic"); } /** * * Clear the address from the site/location selected. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward clearAddress(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ProposalDevelopmentForm proposalDevelopmentForm = (ProposalDevelopmentForm) form; int index = getSelectedLine(request); proposalDevelopmentForm.getProposalDevelopmentDocument().getProposalLocations().get(index).setRolodexId(new Integer(0)); proposalDevelopmentForm.getProposalDevelopmentDocument().getProposalLocations().get(index).setRolodex(new Rolodex()); return mapping.findForward("basic"); } private boolean isDuplicateKeyword(String newScienceKeywordCode, List<PropScienceKeyword> keywords) { for (Iterator iter = keywords.iterator(); iter.hasNext();) { PropScienceKeyword propScienceKeyword = (PropScienceKeyword) iter.next(); String scienceKeywordCode = propScienceKeyword.getScienceKeywordCode(); if (scienceKeywordCode.equalsIgnoreCase(newScienceKeywordCode)) { // duplicate keyword return true; } } return false; } public ActionForward selectAllScienceKeyword(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ProposalDevelopmentForm proposalDevelopmentForm = (ProposalDevelopmentForm) form; ProposalDevelopmentDocument proposalDevelopmentDocument = proposalDevelopmentForm.getProposalDevelopmentDocument(); List<PropScienceKeyword> keywords = proposalDevelopmentDocument.getPropScienceKeywords(); for (Iterator iter = keywords.iterator(); iter.hasNext();) { PropScienceKeyword propScienceKeyword = (PropScienceKeyword) iter.next(); propScienceKeyword.setSelectKeyword(true); } return mapping.findForward("basic"); } public ActionForward deleteSelectedScienceKeyword(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ProposalDevelopmentForm proposalDevelopmentForm = (ProposalDevelopmentForm) form; ProposalDevelopmentDocument proposalDevelopmentDocument = proposalDevelopmentForm.getProposalDevelopmentDocument(); List<PropScienceKeyword> keywords = proposalDevelopmentDocument.getPropScienceKeywords(); List<PropScienceKeyword> newKeywords = new ArrayList<PropScienceKeyword>(); for (Iterator iter = keywords.iterator(); iter.hasNext();) { PropScienceKeyword propScienceKeyword = (PropScienceKeyword) iter.next(); if (!propScienceKeyword.getSelectKeyword()) { newKeywords.add(propScienceKeyword); } } proposalDevelopmentDocument.setPropScienceKeywords(newKeywords); return mapping.findForward("basic"); } @Override public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { super.refresh(mapping, form, request, response); ProposalDevelopmentForm proposalDevelopmentForm = (ProposalDevelopmentForm) form; ProposalDevelopmentDocument proposalDevelopmentDocument = proposalDevelopmentForm.getProposalDevelopmentDocument(); if(proposalDevelopmentDocument!=null && proposalDevelopmentDocument.getPerformingOrganizationId()!=null && proposalDevelopmentDocument.getOwnedByUnit()!=null && proposalDevelopmentDocument.getOwnedByUnit().getOrganizationId()!=null && ((StringUtils.equalsIgnoreCase(proposalDevelopmentDocument.getPerformingOrganizationId(), proposalDevelopmentDocument.getOwnedByUnit().getOrganizationId())) ||(StringUtils.equalsIgnoreCase(proposalDevelopmentDocument.getPerformingOrganizationId().trim(), "")))){ proposalDevelopmentDocument.setPerformingOrganizationId(proposalDevelopmentDocument.getOrganizationId()); } proposalDevelopmentDocument.refreshReferenceObject("organization"); proposalDevelopmentDocument.refreshReferenceObject("performingOrganization"); for(ProposalLocation proposalLocation: proposalDevelopmentDocument.getProposalLocations()){ proposalLocation.refreshReferenceObject("rolodex"); } // check to see if we are coming back from a lookup if (Constants.MULTIPLE_VALUE.equals(proposalDevelopmentForm.getRefreshCaller())) { // Multivalue lookup. Note that the multivalue keyword lookup results are returned persisted to avoid using session. // Since URLs have a max length of 2000 chars, field conversions can not be done. String lookupResultsSequenceNumber = proposalDevelopmentForm.getLookupResultsSequenceNumber(); if (StringUtils.isNotBlank(lookupResultsSequenceNumber)) { Class lookupResultsBOClass = Class.forName(proposalDevelopmentForm.getLookupResultsBOClassName()); Collection<PersistableBusinessObject> rawValues = KNSServiceLocator.getLookupResultsService() .retrieveSelectedResultBOs(lookupResultsSequenceNumber, lookupResultsBOClass, GlobalVariables.getUserSession().getUniversalUser().getPersonUniversalIdentifier()); if (lookupResultsBOClass.isAssignableFrom(ScienceKeyword.class)) { for (Iterator iter = rawValues.iterator(); iter.hasNext();) { ScienceKeyword scienceKeyword = (ScienceKeyword) iter.next(); PropScienceKeyword propScienceKeyword = new PropScienceKeyword(proposalDevelopmentDocument .getProposalNumber(), scienceKeyword); // ignore / drop duplicates if (!isDuplicateKeyword(propScienceKeyword.getScienceKeywordCode(), proposalDevelopmentDocument .getPropScienceKeywords())) { proposalDevelopmentDocument.addPropScienceKeyword(propScienceKeyword); } } } } } return mapping.findForward("basic"); } private KualiRuleService getKualiRuleService() { return getService(KualiRuleService.class); } }
src/main/java/org/kuali/kra/proposaldevelopment/web/struts/action/ProposalDevelopmentProposalAction.java
/* * Copyright 2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.proposaldevelopment.web.struts.action; import static java.util.Collections.sort; import static org.kuali.kra.infrastructure.KraServiceLocator.getService; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.kuali.core.bo.PersistableBusinessObject; import org.kuali.core.service.KualiConfigurationService; import org.kuali.core.service.KualiRuleService; import org.kuali.core.util.GlobalVariables; import org.kuali.kra.bo.Rolodex; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.KraServiceLocator; import org.kuali.kra.proposaldevelopment.bo.PropScienceKeyword; import org.kuali.kra.proposaldevelopment.bo.ProposalLocation; import org.kuali.kra.proposaldevelopment.bo.ProposalPersonComparator; import org.kuali.kra.proposaldevelopment.bo.ScienceKeyword; import org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument; import org.kuali.kra.proposaldevelopment.rule.event.AddProposalLocationEvent; import org.kuali.kra.proposaldevelopment.service.ProposalDevelopmentService; import org.kuali.kra.proposaldevelopment.web.struts.form.ProposalDevelopmentForm; import org.kuali.kra.service.SponsorService; import org.kuali.rice.KNSServiceLocator; public class ProposalDevelopmentProposalAction extends ProposalDevelopmentAction { private static final Log LOG = LogFactory.getLog(ProposalDevelopmentProposalAction.class); @Override public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setKeywordsPanelFlag(request); ProposalDevelopmentDocument proposalDevelopmentDocument = ((ProposalDevelopmentForm) form).getProposalDevelopmentDocument(); KraServiceLocator.getService(ProposalDevelopmentService.class).initializeUnitOrganzationLocation( proposalDevelopmentDocument); return super.save(mapping, form, request, response); } @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward actionForward = super.execute(mapping, form, request, response); setKeywordsPanelFlag(request); ProposalDevelopmentDocument proposalDevelopmentDocument = ((ProposalDevelopmentForm) form).getProposalDevelopmentDocument(); if (proposalDevelopmentDocument.getOrganizationId() != null && proposalDevelopmentDocument.getProposalLocations().size() == 0 && StringUtils.isNotBlank(request.getParameter("methodToCall")) && request.getParameter("methodToCall").toString().equals("refresh") && StringUtils.isNotBlank(request.getParameter("refreshCaller")) && request.getParameter("refreshCaller").toString().equals("kualiLookupable") && StringUtils.isNotBlank(request.getParameter("document.organizationId"))) { // populate 1st location. Not sure yet ProposalLocation propLocation = new ProposalLocation(); propLocation.setLocation(proposalDevelopmentDocument.getOrganization().getOrganizationName()); propLocation.setLocationSequenceNumber(proposalDevelopmentDocument .getDocumentNextValue(Constants.PROPOSAL_LOCATION_SEQUENCE_NUMBER)); proposalDevelopmentDocument.getProposalLocations().add(propLocation); } // populate the Prime Sponsor Name if we have the code // this is necessary since the name is only on the form not the document // and it is only populated by a lookup or through AJAX/DWR String primeSponsorCode = proposalDevelopmentDocument.getPrimeSponsorCode(); if (StringUtils.isNotEmpty(primeSponsorCode)) { String primeSponsorName = (KraServiceLocator.getService(SponsorService.class).getSponsorName(primeSponsorCode)); if (StringUtils.isEmpty(primeSponsorName)) { primeSponsorName = "not found"; } ((ProposalDevelopmentForm) form).setPrimeSponsorName(primeSponsorName); } else { // TODO: why do we have to do this? ((ProposalDevelopmentForm) form).setPrimeSponsorName(null); } if (proposalDevelopmentDocument.getProposalPersons().size() > 0) sort(proposalDevelopmentDocument.getProposalPersons(), new ProposalPersonComparator()); if (proposalDevelopmentDocument.getInvestigators().size() > 0) sort(proposalDevelopmentDocument.getInvestigators(), new ProposalPersonComparator()); return actionForward; } /** * * This method sets the flag for keyword display panel - display keyword panel if parameter is set to true * * @param request */ private void setKeywordsPanelFlag(HttpServletRequest request) { String keywordPanelDisplay = KraServiceLocator.getService(KualiConfigurationService.class).getParameterValue( Constants.PARAMETER_MODULE_PROPOSAL_DEVELOPMENT, Constants.PARAMETER_COMPONENT_DOCUMENT, Constants.KEYWORD_PANEL_DISPLAY); request.getSession().setAttribute(Constants.KEYWORD_PANEL_DISPLAY, keywordPanelDisplay); } /** * * Add new location to proposal document and reset newProplocation from form. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward addLocation(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ProposalDevelopmentForm proposalDevelopmentForm = (ProposalDevelopmentForm) form; ProposalLocation newProposalLocation = proposalDevelopmentForm.getNewPropLocation(); if (getKualiRuleService().applyRules( new AddProposalLocationEvent(Constants.EMPTY_STRING, proposalDevelopmentForm.getProposalDevelopmentDocument(), newProposalLocation))) { newProposalLocation.setLocationSequenceNumber(proposalDevelopmentForm.getProposalDevelopmentDocument() .getDocumentNextValue(Constants.PROPOSAL_LOCATION_SEQUENCE_NUMBER)); proposalDevelopmentForm.getProposalDevelopmentDocument().getProposalLocations().add(newProposalLocation); proposalDevelopmentForm.setNewPropLocation(new ProposalLocation()); } return mapping.findForward("basic"); } /** * * Delete one location/site from proposal document * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward deleteLocation(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ProposalDevelopmentForm proposalDevelopmentForm = (ProposalDevelopmentForm) form; proposalDevelopmentForm.getProposalDevelopmentDocument().getProposalLocations().remove(getLineToDelete(request)); return mapping.findForward("basic"); } /** * * Clear the address from the site/location selected. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward clearAddress(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ProposalDevelopmentForm proposalDevelopmentForm = (ProposalDevelopmentForm) form; int index = getSelectedLine(request); proposalDevelopmentForm.getProposalDevelopmentDocument().getProposalLocations().get(index).setRolodexId(new Integer(0)); proposalDevelopmentForm.getProposalDevelopmentDocument().getProposalLocations().get(index).setRolodex(new Rolodex()); return mapping.findForward("basic"); } private boolean isDuplicateKeyword(String newScienceKeywordCode, List<PropScienceKeyword> keywords) { for (Iterator iter = keywords.iterator(); iter.hasNext();) { PropScienceKeyword propScienceKeyword = (PropScienceKeyword) iter.next(); String scienceKeywordCode = propScienceKeyword.getScienceKeywordCode(); if (scienceKeywordCode.equalsIgnoreCase(newScienceKeywordCode)) { // duplicate keyword return true; } } return false; } public ActionForward selectAllScienceKeyword(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ProposalDevelopmentForm proposalDevelopmentForm = (ProposalDevelopmentForm) form; ProposalDevelopmentDocument proposalDevelopmentDocument = proposalDevelopmentForm.getProposalDevelopmentDocument(); List<PropScienceKeyword> keywords = proposalDevelopmentDocument.getPropScienceKeywords(); for (Iterator iter = keywords.iterator(); iter.hasNext();) { PropScienceKeyword propScienceKeyword = (PropScienceKeyword) iter.next(); propScienceKeyword.setSelectKeyword(true); } return mapping.findForward("basic"); } public ActionForward deleteSelectedScienceKeyword(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ProposalDevelopmentForm proposalDevelopmentForm = (ProposalDevelopmentForm) form; ProposalDevelopmentDocument proposalDevelopmentDocument = proposalDevelopmentForm.getProposalDevelopmentDocument(); List<PropScienceKeyword> keywords = proposalDevelopmentDocument.getPropScienceKeywords(); List<PropScienceKeyword> newKeywords = new ArrayList<PropScienceKeyword>(); for (Iterator iter = keywords.iterator(); iter.hasNext();) { PropScienceKeyword propScienceKeyword = (PropScienceKeyword) iter.next(); if (!propScienceKeyword.getSelectKeyword()) { newKeywords.add(propScienceKeyword); } } proposalDevelopmentDocument.setPropScienceKeywords(newKeywords); return mapping.findForward("basic"); } @Override public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { super.refresh(mapping, form, request, response); ProposalDevelopmentForm proposalDevelopmentForm = (ProposalDevelopmentForm) form; ProposalDevelopmentDocument proposalDevelopmentDocument = proposalDevelopmentForm.getProposalDevelopmentDocument(); if(proposalDevelopmentDocument!=null && proposalDevelopmentDocument.getPerformingOrganizationId()!=null && proposalDevelopmentDocument.getOwnedByUnit()!=null && proposalDevelopmentDocument.getOwnedByUnit().getOrganizationId()!=null && ((StringUtils.equalsIgnoreCase(proposalDevelopmentDocument.getPerformingOrganizationId(), proposalDevelopmentDocument.getOwnedByUnit().getOrganizationId())) ||(StringUtils.equalsIgnoreCase(proposalDevelopmentDocument.getPerformingOrganizationId().trim(), "")))){ proposalDevelopmentDocument.setPerformingOrganizationId(proposalDevelopmentDocument.getOrganizationId()); } proposalDevelopmentDocument.refreshReferenceObject("organization"); proposalDevelopmentDocument.refreshReferenceObject("performingOrganization"); // check to see if we are coming back from a lookup if (Constants.MULTIPLE_VALUE.equals(proposalDevelopmentForm.getRefreshCaller())) { // Multivalue lookup. Note that the multivalue keyword lookup results are returned persisted to avoid using session. // Since URLs have a max length of 2000 chars, field conversions can not be done. String lookupResultsSequenceNumber = proposalDevelopmentForm.getLookupResultsSequenceNumber(); if (StringUtils.isNotBlank(lookupResultsSequenceNumber)) { Class lookupResultsBOClass = Class.forName(proposalDevelopmentForm.getLookupResultsBOClassName()); Collection<PersistableBusinessObject> rawValues = KNSServiceLocator.getLookupResultsService() .retrieveSelectedResultBOs(lookupResultsSequenceNumber, lookupResultsBOClass, GlobalVariables.getUserSession().getUniversalUser().getPersonUniversalIdentifier()); if (lookupResultsBOClass.isAssignableFrom(ScienceKeyword.class)) { for (Iterator iter = rawValues.iterator(); iter.hasNext();) { ScienceKeyword scienceKeyword = (ScienceKeyword) iter.next(); PropScienceKeyword propScienceKeyword = new PropScienceKeyword(proposalDevelopmentDocument .getProposalNumber(), scienceKeyword); // ignore / drop duplicates if (!isDuplicateKeyword(propScienceKeyword.getScienceKeywordCode(), proposalDevelopmentDocument .getPropScienceKeywords())) { proposalDevelopmentDocument.addPropScienceKeyword(propScienceKeyword); } } } } } return mapping.findForward("basic"); } private KualiRuleService getKualiRuleService() { return getService(KualiRuleService.class); } }
KRACOEUS-473 - called refreshReferenceObject on rolodex in refresh method
src/main/java/org/kuali/kra/proposaldevelopment/web/struts/action/ProposalDevelopmentProposalAction.java
KRACOEUS-473 - called refreshReferenceObject on rolodex in refresh method
Java
agpl-3.0
6436a1fc2215e7ad453cbf9cd8a35b96020812fb
0
hltn/opencps,tuanta/opencps,VietOpenCPS/opencps,VietOpenCPS/opencps,hltn/opencps,hltn/opencps,tuanta/opencps,VietOpenCPS/opencps
/** * OpenCPS is the open source Core Public Services software * Copyright (C) 2016-present OpenCPS community * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package org.opencps.datamgt.util.comparator; import org.opencps.datamgt.model.DictVersion; import com.liferay.portal.kernel.util.DateUtil; import com.liferay.portal.kernel.util.OrderByComparator; public class DictVersionModifiedDateComparator extends OrderByComparator { public static final String ORDER_BY_ASC = "modifiedDate ASC"; public static final String ORDER_BY_DESC = "modifiedDate DESC"; public static final String[] ORDER_BY_FIELDS = { "modifiedDate" }; public DictVersionModifiedDateComparator() { this(false); } public DictVersionModifiedDateComparator(boolean ascending) { _ascending = ascending; } @Override public int compare(Object obj1, Object obj2) { DictVersion dictVersion1 = (DictVersion) obj1; DictVersion dictVersion2 = (DictVersion) obj2; int compareValue = DateUtil.compareTo(dictVersion1.getModifiedDate(), dictVersion2.getModifiedDate()); return _ascending ? compareValue : -compareValue; } @Override public String[] getOrderByFields() { return ORDER_BY_FIELDS; } @Override public boolean isAscending() { return _ascending; } private boolean _ascending; }
portlets/opencps-portlet/docroot/WEB-INF/src/org/opencps/datamgt/util/comparator/DictVersionModifiedDateComparator.java
/** * OpenCPS is the open source Core Public Services software * Copyright (C) 2016-present OpenCPS community * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package org.opencps.datamgt.util.comparator; import org.opencps.datamgt.model.DictVersion; import com.liferay.portal.kernel.util.DateUtil; import com.liferay.portal.kernel.util.OrderByComparator; public class DictVersionModifiedDateComparator extends OrderByComparator { public static final String ORDER_BY_ASC = "modifiedDate ASC"; public static final String ORDER_BY_DESC = "modifiedDate DESC"; public static final String[] ORDER_BY_FIELDS = { "modifiedDate" }; public DictVersionModifiedDateComparator() { this(false); } public DictVersionModifiedDateComparator(boolean ascending) { _ascending = ascending; } @Override public int compare(Object obj1, Object obj2) { DictVersion dictVersion1 = (DictVersion) obj1; DictVersion dictVersion2 = (DictVersion) obj2; int compareValue = DateUtil.compareTo(dictVersion1.getModifiedDate(), dictVersion2.getModifiedDate()); return _ascending ? compareValue : -compareValue; } private boolean _ascending; }
commit file DictVerSionModifiedDateComparator.java them mot so ham override
portlets/opencps-portlet/docroot/WEB-INF/src/org/opencps/datamgt/util/comparator/DictVersionModifiedDateComparator.java
commit file DictVerSionModifiedDateComparator.java them mot so ham override
Java
agpl-3.0
78eb1e71a6837fb14581becc110c0aa7f8e811c1
0
ozwillo/ozwillo-datacore,ozwillo/ozwillo-datacore,ozwillo/ozwillo-datacore,ozwillo/ozwillo-datacore,ozwillo/ozwillo-datacore
package org.oasis.datacore.historization.service; import org.oasis.datacore.core.entity.model.DCEntity; import org.oasis.datacore.core.meta.model.DCModel; import org.oasis.datacore.historization.exception.HistorizationException; /** * Historization service. * * Security of Historized data is (at least) the same as security of its latest version * (LATER OPT it could have additional business / Model-level permission to check). * Therefore it is not secured by itself, but by calling EntityService, which must therefore * be called (at least) once in each secured operation. * * @author agiraudon * */ public interface HistorizationService { /** * Historize an entity of a defined model. * Secured, by being called before entityService.create/update(). * @param entity * @param model * @return */ public void historize(DCEntity entity, DCModel model) throws HistorizationException; /** * Get the model where originalModel historization is stored * @param originalModel * @return */ public DCModel getHistorizationModel(DCModel originalModel) throws HistorizationException; /** * Create an historization model from an original model (it's a full copy of original model with only the name that differs : prefix "_h_" + name()) * @param originalModel * @return * @throws HistorizationException */ public DCModel createHistorizationModel(DCModel originalModel) throws HistorizationException; /** * * @param model * @return * @throws HistorizationException */ public boolean isHistorizable(DCModel model) throws HistorizationException; /** * Returns an historized entity matching uri AND version. * We are also checking that the original entity exists with this latest version, if not * we do not retrieve the historized one EVEN if it exists, because it would mean * that the historized one has been created before a failed create/update operation ! * * Secured, by calling EntityService for this exact purpose. * * @param uri * @param version * @param originalModel * @return * @throws HistorizationException */ public DCEntity getHistorizedEntity(String uri, int version, DCModel originalModel) throws HistorizationException; /** * Return the mongo collection name of the historized model (if original model is historizable) * @param originalModel * @return */ public String getHistorizedCollectionNameFromOriginalModel(DCModel originalModel) throws HistorizationException; }
oasis-datacore-rest-server/src/main/java/org/oasis/datacore/historization/service/HistorizationService.java
package org.oasis.datacore.historization.service; import org.oasis.datacore.core.entity.model.DCEntity; import org.oasis.datacore.core.meta.model.DCModel; import org.oasis.datacore.historization.exception.HistorizationException; /** * Historization service * @author agiraudon * */ public interface HistorizationService { /** * Historize an entity of a defined model * @param entity * @param model * @return */ public void historize(DCEntity entity, DCModel model) throws HistorizationException; /** * Get the model where originalModel historization is stored * @param originalModel * @return */ public DCModel getHistorizationModel(DCModel originalModel) throws HistorizationException; /** * Create an historization model from an original model (it's a full copy of original model with only the name that differs : prefix "_h_" + name()) * @param originalModel * @return * @throws HistorizationException */ public DCModel createHistorizationModel(DCModel originalModel) throws HistorizationException; /** * * @param model * @return * @throws HistorizationException */ public boolean isHistorizable(DCModel model) throws HistorizationException; /** * Return an historized entity matching uri AND version * We are also checking that the original entity exist, if not * we do net retrieve the historized one EVEN if it exist ! * @param uri * @param version * @param originalModel * @return * @throws HistorizationException */ public DCEntity getHistorizedEntity(String uri, int version, DCModel originalModel) throws HistorizationException; /** * Return the mongo collection name of the historized model (if original model is historizable) * @param originalModel * @return */ public String getHistorizedCollectionNameFromOriginalModel(DCModel originalModel) throws HistorizationException; }
patched HistoryService specs (security...), see #18
oasis-datacore-rest-server/src/main/java/org/oasis/datacore/historization/service/HistorizationService.java
patched HistoryService specs (security...), see #18
Java
lgpl-2.1
02f5f6342229f3d38f7448eb934a0dcc7024d8d9
0
CoderDojo-Porirua/minecraft-forge-1.8
package nz.cdr.minecrafttutorial; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; public class TutorialMod { public void preInit(FMLPreInitializationEvent event) { } }
src/main/java/nz/cdr/minecrafttutorial/TutorialMod.java
package nz.cdr.minecrafttutorial; public class TutorialMod { }
Adding preInit
src/main/java/nz/cdr/minecrafttutorial/TutorialMod.java
Adding preInit
Java
lgpl-2.1
994486013b112560351d45fcabab258ccdaa512f
0
johnscancella/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,sewe/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,sewe/spotbugs
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2003, University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs; import org.apache.bcel.classfile.*; import org.apache.bcel.generic.*; import edu.umd.cs.pugh.visitclass.BetterVisitor; import edu.umd.cs.pugh.visitclass.DismantleBytecode; /** * A BugAnnotation that records a range of source lines * in a class. * * @see BugAnnotation * @author David Hovemeyer */ public class SourceLineAnnotation implements BugAnnotation { private String description; private String className; private int startLine; private int endLine; /** * Constructor. * @param className the class to which the line number(s) refer * @param startLine the first line (inclusive) * @param endLine the ending line (inclusive) */ public SourceLineAnnotation(String className, int startLine, int endLine) { this.description = "SOURCE_LINE_DEFAULT"; this.className = className; this.startLine = startLine; this.endLine = endLine; } /** * Factory method for creating a source line annotation describing * an entire method. * @param visitor a BetterVisitor which is visiting the method * @return the SourceLineAnnotation, or null if we do not have line number information * for the method */ public static SourceLineAnnotation fromVisitedMethod(BetterVisitor visitor) { LineNumberTable lineNumberTable = getLineNumberTable(visitor); if (lineNumberTable == null) return null; return forEntireMethod(visitor.getBetterClassName(), lineNumberTable); } /** * Factory method for creating a source line annotation describing * an entire method. * @param methodGen the method being visited * @return the SourceLineAnnotation, or null if we do not have line number information * for the method */ public static SourceLineAnnotation fromVisitedMethod(MethodGen methodGen) { LineNumberTable lineNumberTable = methodGen.getLineNumberTable(methodGen.getConstantPool()); if (lineNumberTable == null) return null; return forEntireMethod(methodGen.getClassName(), lineNumberTable); } private static SourceLineAnnotation forEntireMethod(String className, LineNumberTable lineNumberTable) { LineNumber[] table = lineNumberTable.getLineNumberTable(); return (table != null && table.length > 0) ? new SourceLineAnnotation(className, table[0].getLineNumber(), table[table.length-1].getLineNumber()) : null; } /** * Factory method for creating a source line annotation describing the * source line number for the instruction being visited by given visitor. * @param visitor a BetterVisitor which is visiting the method * @param pc the bytecode offset of the instruction in the method * @return the SourceLineAnnotation, or null if we do not have line number information * for the instruction */ public static SourceLineAnnotation fromVisitedInstruction(BetterVisitor visitor, int pc) { return fromVisitedInstructionRange(visitor, pc, pc); } /** * Factory method for creating a source line annotation describing the * source line numbers for a range of instructions in the method being * visited by the given visitor. * @param visitor a BetterVisitor which is visiting the method * @param startPC the bytecode offset of the start instruction in the range * @param endPC the bytecode offset of the end instruction in the range * @return the SourceLineAnnotation, or null if we do not have line number information * for the instruction */ public static SourceLineAnnotation fromVisitedInstructionRange(BetterVisitor visitor, int startPC, int endPC) { LineNumberTable lineNumberTable = getLineNumberTable(visitor); if (lineNumberTable == null) return null; int startLine = lineNumberTable.getSourceLine(startPC); int endLine = lineNumberTable.getSourceLine(endPC); return new SourceLineAnnotation(visitor.getBetterClassName(), startLine, endLine); } /** * Factory method for creating a source line annotation describing the * source line number for the instruction being visited by given visitor. * @param visitor a DismantleBytecode visitor which is visiting the method * @return the SourceLineAnnotation, or null if we do not have line number information * for the instruction */ public static SourceLineAnnotation fromVisitedInstruction(DismantleBytecode visitor) { return fromVisitedInstruction(visitor, visitor.getPC()); } /** * Factory method for creating a source line annotation describing the * source line number for a visited instruction. * @param methodGen the MethodGen object representing the method * @param handle the InstructionHandle containing the visited instruction * @return the SourceLineAnnotation, or null if we do not have line number information * for the instruction */ public static SourceLineAnnotation fromVisitedInstruction(MethodGen methodGen, InstructionHandle handle) { LineNumberTable table = methodGen.getLineNumberTable(methodGen.getConstantPool()); if (table == null) return null; int lineNumber = table.getSourceLine(handle.getPosition()); return new SourceLineAnnotation(methodGen.getClassName(), lineNumber, lineNumber); } /** * Factory method for creating a source line annotation describing * the source line numbers for a range of instruction in a method. * @param methodGen the method * @param start the start instruction * @param end the end instruction (inclusive) */ public static SourceLineAnnotation fromVisitedInstructionRange(MethodGen methodGen, InstructionHandle start, InstructionHandle end) { LineNumberTable lineNumberTable = methodGen.getLineNumberTable(methodGen.getConstantPool()); if (lineNumberTable == null) return null; int startLine = lineNumberTable.getSourceLine(start.getPosition()); int endLine = lineNumberTable.getSourceLine(end.getPosition()); return new SourceLineAnnotation(methodGen.getClassName(), startLine, endLine); } private static LineNumberTable getLineNumberTable(BetterVisitor visitor) { Code code = visitor.getMethod().getCode(); if (code == null) return null; return code.getLineNumberTable(); } /** * Get the class name. */ public String getClassName() { return className; } /** * Get the package name. */ public String getPackageName() { int lastDot = className.lastIndexOf('.'); if (lastDot < 0) return ""; else return className.substring(0, lastDot); } /** * Get the start line (inclusive). */ public int getStartLine() { return startLine; } /** * Get the ending line (inclusive). */ public int getEndLine() { return endLine; } public void accept(BugAnnotationVisitor visitor) { visitor.visitSourceLineAnnotation(this); } public String format(String key) { if (key.equals("")) { StringBuffer buf = new StringBuffer(); buf.append(className); buf.append(":["); if (startLine == endLine) { buf.append("line "); buf.append(startLine); } else { buf.append("lines "); buf.append(startLine); buf.append('-'); buf.append(endLine); } buf.append(']'); return buf.toString(); } else throw new IllegalStateException("Unknown format key " + key); } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String toString() { String pattern = I18N.instance().getAnnotationDescription(description); FindBugsMessageFormat format = new FindBugsMessageFormat(pattern); return format.format(new BugAnnotation[]{this}); } public int compareTo(BugAnnotation o) { if (!(o instanceof SourceLineAnnotation)) // All BugAnnotations must be comparable return this.getClass().getName().compareTo(o.getClass().getName()); SourceLineAnnotation other = (SourceLineAnnotation) o; int cmp = className.compareTo(other.className); if (cmp != 0) return cmp; cmp = startLine - other.startLine; if (cmp != 0) return cmp; return endLine - other.endLine; } public int hashCode() { return className.hashCode() + startLine + endLine; } public boolean equals(Object o) { if (!(o instanceof SourceLineAnnotation)) return false; SourceLineAnnotation other = (SourceLineAnnotation) o; return className.equals(other.className) && startLine == other.startLine && endLine == other.endLine; } } // vim:ts=4
findbugs/src/java/edu/umd/cs/findbugs/SourceLineAnnotation.java
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2003, University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs; import org.apache.bcel.classfile.*; import org.apache.bcel.generic.*; import edu.umd.cs.pugh.visitclass.BetterVisitor; import edu.umd.cs.pugh.visitclass.DismantleBytecode; /** * A BugAnnotation that records a range of source lines * in a class. * * @see BugAnnotation * @author David Hovemeyer */ public class SourceLineAnnotation implements BugAnnotation { private String description; private String className; private int startLine; private int endLine; /** * Constructor. * @param className the class to which the line number(s) refer * @param startLine the first line (inclusive) * @param endLine the ending line (inclusive) */ public SourceLineAnnotation(String className, int startLine, int endLine) { this.description = "SOURCE_LINE_DEFAULT"; this.className = className; this.startLine = startLine; this.endLine = endLine; } /** * Factory method for creating a source line annotation describing * an entire method. * @param visitor a BetterVisitor which is visiting the method * @return the SourceLineAnnotation, or null if we do not have line number information * for the method */ public static SourceLineAnnotation fromVisitedMethod(BetterVisitor visitor) { LineNumberTable lineNumberTable = getLineNumberTable(visitor); if (lineNumberTable == null) return null; return forEntireMethod(visitor.getBetterClassName(), lineNumberTable); } /** * Factory method for creating a source line annotation describing * an entire method. * @param methodGen the method being visited * @return the SourceLineAnnotation, or null if we do not have line number information * for the method */ public static SourceLineAnnotation fromVisitedMethod(MethodGen methodGen) { LineNumberTable lineNumberTable = methodGen.getLineNumberTable(methodGen.getConstantPool()); if (lineNumberTable == null) return null; return forEntireMethod(methodGen.getClassName(), lineNumberTable); } private static SourceLineAnnotation forEntireMethod(String className, LineNumberTable lineNumberTable) { LineNumber[] table = lineNumberTable.getLineNumberTable(); return new SourceLineAnnotation(className, table[0].getLineNumber(), table[table.length-1].getLineNumber()); } /** * Factory method for creating a source line annotation describing the * source line number for the instruction being visited by given visitor. * @param visitor a BetterVisitor which is visiting the method * @param pc the bytecode offset of the instruction in the method * @return the SourceLineAnnotation, or null if we do not have line number information * for the instruction */ public static SourceLineAnnotation fromVisitedInstruction(BetterVisitor visitor, int pc) { return fromVisitedInstructionRange(visitor, pc, pc); } /** * Factory method for creating a source line annotation describing the * source line numbers for a range of instructions in the method being * visited by the given visitor. * @param visitor a BetterVisitor which is visiting the method * @param startPC the bytecode offset of the start instruction in the range * @param endPC the bytecode offset of the end instruction in the range * @return the SourceLineAnnotation, or null if we do not have line number information * for the instruction */ public static SourceLineAnnotation fromVisitedInstructionRange(BetterVisitor visitor, int startPC, int endPC) { LineNumberTable lineNumberTable = getLineNumberTable(visitor); if (lineNumberTable == null) return null; int startLine = lineNumberTable.getSourceLine(startPC); int endLine = lineNumberTable.getSourceLine(endPC); return new SourceLineAnnotation(visitor.getBetterClassName(), startLine, endLine); } /** * Factory method for creating a source line annotation describing the * source line number for the instruction being visited by given visitor. * @param visitor a DismantleBytecode visitor which is visiting the method * @return the SourceLineAnnotation, or null if we do not have line number information * for the instruction */ public static SourceLineAnnotation fromVisitedInstruction(DismantleBytecode visitor) { return fromVisitedInstruction(visitor, visitor.getPC()); } /** * Factory method for creating a source line annotation describing the * source line number for a visited instruction. * @param methodGen the MethodGen object representing the method * @param handle the InstructionHandle containing the visited instruction * @return the SourceLineAnnotation, or null if we do not have line number information * for the instruction */ public static SourceLineAnnotation fromVisitedInstruction(MethodGen methodGen, InstructionHandle handle) { LineNumberTable table = methodGen.getLineNumberTable(methodGen.getConstantPool()); if (table == null) return null; int lineNumber = table.getSourceLine(handle.getPosition()); return new SourceLineAnnotation(methodGen.getClassName(), lineNumber, lineNumber); } /** * Factory method for creating a source line annotation describing * the source line numbers for a range of instruction in a method. * @param methodGen the method * @param start the start instruction * @param end the end instruction (inclusive) */ public static SourceLineAnnotation fromVisitedInstructionRange(MethodGen methodGen, InstructionHandle start, InstructionHandle end) { LineNumberTable lineNumberTable = methodGen.getLineNumberTable(methodGen.getConstantPool()); if (lineNumberTable == null) return null; int startLine = lineNumberTable.getSourceLine(start.getPosition()); int endLine = lineNumberTable.getSourceLine(end.getPosition()); return new SourceLineAnnotation(methodGen.getClassName(), startLine, endLine); } private static LineNumberTable getLineNumberTable(BetterVisitor visitor) { Code code = visitor.getMethod().getCode(); if (code == null) return null; return code.getLineNumberTable(); } /** * Get the class name. */ public String getClassName() { return className; } /** * Get the package name. */ public String getPackageName() { int lastDot = className.lastIndexOf('.'); if (lastDot < 0) return ""; else return className.substring(0, lastDot); } /** * Get the start line (inclusive). */ public int getStartLine() { return startLine; } /** * Get the ending line (inclusive). */ public int getEndLine() { return endLine; } public void accept(BugAnnotationVisitor visitor) { visitor.visitSourceLineAnnotation(this); } public String format(String key) { if (key.equals("")) { StringBuffer buf = new StringBuffer(); buf.append(className); buf.append(":["); if (startLine == endLine) { buf.append("line "); buf.append(startLine); } else { buf.append("lines "); buf.append(startLine); buf.append('-'); buf.append(endLine); } buf.append(']'); return buf.toString(); } else throw new IllegalStateException("Unknown format key " + key); } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String toString() { String pattern = I18N.instance().getAnnotationDescription(description); FindBugsMessageFormat format = new FindBugsMessageFormat(pattern); return format.format(new BugAnnotation[]{this}); } public int compareTo(BugAnnotation o) { if (!(o instanceof SourceLineAnnotation)) // All BugAnnotations must be comparable return this.getClass().getName().compareTo(o.getClass().getName()); SourceLineAnnotation other = (SourceLineAnnotation) o; int cmp = className.compareTo(other.className); if (cmp != 0) return cmp; cmp = startLine - other.startLine; if (cmp != 0) return cmp; return endLine - other.endLine; } public int hashCode() { return className.hashCode() + startLine + endLine; } public boolean equals(Object o) { if (!(o instanceof SourceLineAnnotation)) return false; SourceLineAnnotation other = (SourceLineAnnotation) o; return className.equals(other.className) && startLine == other.startLine && endLine == other.endLine; } } // vim:ts=4
In forEntireMethod(), treat empty line number table as absence of line number information. git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@489 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
findbugs/src/java/edu/umd/cs/findbugs/SourceLineAnnotation.java
In forEntireMethod(), treat empty line number table as absence of line number information.
Java
lgpl-2.1
61b87592e9bf85c25b0affed45a98f22f7e8ecab
0
meg0man/languagetool,jimregan/languagetool,meg0man/languagetool,janissl/languagetool,lopescan/languagetool,languagetool-org/languagetool,meg0man/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,lopescan/languagetool,janissl/languagetool,meg0man/languagetool,janissl/languagetool,jimregan/languagetool,janissl/languagetool,janissl/languagetool,lopescan/languagetool,languagetool-org/languagetool,jimregan/languagetool,janissl/languagetool,lopescan/languagetool,meg0man/languagetool,jimregan/languagetool,jimregan/languagetool,languagetool-org/languagetool,lopescan/languagetool
/* LanguageTool, a natural language style checker * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.Nullable; import org.languagetool.chunking.Chunker; import org.languagetool.databroker.ResourceDataBroker; import org.languagetool.language.Contributor; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.rules.Rule; import org.languagetool.rules.patterns.PatternRule; import org.languagetool.rules.patterns.PatternRuleLoader; import org.languagetool.rules.patterns.Unifier; import org.languagetool.rules.patterns.UnifierConfiguration; import org.languagetool.synthesis.Synthesizer; import org.languagetool.tagging.Tagger; import org.languagetool.tagging.disambiguation.Disambiguator; import org.languagetool.tagging.disambiguation.xx.DemoDisambiguator; import org.languagetool.tagging.xx.DemoTagger; import org.languagetool.tokenizers.*; import org.languagetool.tools.MultiKeyProperties; import org.languagetool.tools.StringTools; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.net.URL; import java.util.*; import java.util.regex.Pattern; /** * Base class for any supported language (English, German, etc). Language classes * are detected at runtime by searching the classpath for files named * {@code META-INF/org/languagetool/language-module.properties}. Those file(s) * need to contain a key {@code languageClasses} which specifies the fully qualified * class name(s), e.g. {@code org.languagetool.language.English}. Use commas to specify * more than one class. */ public abstract class Language { private static final String PROPERTIES_PATH = "META-INF/org/languagetool/language-module.properties"; private static final String PROPERTIES_KEY = "languageClasses"; private static List<Language> externalLanguages = new ArrayList<>(); private final List<String> externalRuleFiles = new ArrayList<>(); private final List<String> externalFalseFriendFiles = new ArrayList<>(); private final List<String> externalBitextRules = new ArrayList<>(); private boolean isExternalLanguage = false; private Pattern ignoredCharactersRegex = Pattern.compile("[\u00AD]"); // soft hyphen private List<PatternRule> patternRules; /** * All languages supported by LanguageTool. This includes at least a "demo" language * for testing. * @deprecated use {@link Languages#getWithDemoLanguage()} instead (deprecated since 2.9) */ public static Language[] LANGUAGES = getLanguages(); // TODO: remove once LANGUAGES is removed private static Language[] getLanguages() { final List<Language> languages = new ArrayList<>(); final Set<String> languageClassNames = new HashSet<>(); try { final Enumeration<URL> propertyFiles = Language.class.getClassLoader().getResources(PROPERTIES_PATH); while (propertyFiles.hasMoreElements()) { final URL url = propertyFiles.nextElement(); try (InputStream inputStream = url.openStream()) { // We want to be able to read properties file with duplicate key, as produced by // Maven when merging files: final MultiKeyProperties props = new MultiKeyProperties(inputStream); final List<String> classNamesStr = props.getProperty(PROPERTIES_KEY); if (classNamesStr == null) { throw new RuntimeException("Key '" + PROPERTIES_KEY + "' not found in " + url); } for (String classNames : classNamesStr) { final String[] classNamesSplit = classNames.split("\\s*,\\s*"); for (String className : classNamesSplit) { if (languageClassNames.contains(className)) { // avoid duplicates - this way we are robust against problems with the maven assembly // plugin which aggregates files more than once (in case the deployment descriptor // contains both <format>zip</format> and <format>dir</format>): continue; } languages.add(createLanguageObjects(url, className)); languageClassNames.add(className); } } } } } catch (IOException e) { throw new RuntimeException(e); } return languages.toArray(new Language[languages.size()]); } private static Language createLanguageObjects(URL url, String className) { try { final Class<?> aClass = Class.forName(className); final Constructor<?> constructor = aClass.getConstructor(); return (Language) constructor.newInstance(); } catch (ClassNotFoundException e) { throw new RuntimeException("Class '" + className + "' specified in " + url + " could not be found in classpath", e); } catch (Exception e) { throw new RuntimeException("Object for class '" + className + "' specified in " + url + " could not created", e); } } /** * All languages supported by LanguageTool, but without the demo language. * @deprecated use {@link Languages#get()} instead (deprecated since 2.9) */ public static final Language[] REAL_LANGUAGES = getRealLanguages(); /** * Returns all languages supported by LanguageTool but without the demo language. * In contrast to Language.REAL_LANGUAGES contains external languages as well. * @return All supported languages. * @deprecated use {@link Languages#get()} instead (deprecated since 2.9) * @since 2.6 */ public static Language[] getRealLanguages() { List<Language> result = new ArrayList<>(); for (Language lang : LANGUAGES) { if (!"xx".equals(lang.getShortName())) { // skip demo language result.add(lang); } } return result.toArray(new Language[result.size()]); } private static final Language[] BUILTIN_LANGUAGES = LANGUAGES; private static final Disambiguator DEMO_DISAMBIGUATOR = new DemoDisambiguator(); private static final Tagger DEMO_TAGGER = new DemoTagger(); private static final SentenceTokenizer SENTENCE_TOKENIZER = new SimpleSentenceTokenizer(); private static final WordTokenizer WORD_TOKENIZER = new WordTokenizer(); private final UnifierConfiguration unifierConfiguration = new UnifierConfiguration(); private final UnifierConfiguration disambiguationUnifierConfiguration = new UnifierConfiguration(); // ------------------------------------------------------------------------- /** * Get this language's two character code, e.g. <code>en</code> for English. * The country parameter (e.g. "US"), if any, is not returned. * @return language code */ public abstract String getShortName(); /** * Get this language's name in English, e.g. <code>English</code> or * <code>German (Germany)</code>. * @return language name */ public abstract String getName(); /** * Set this language's name in English. * @since 2.6 */ public abstract void setName(final String name); /** * Get this language's country options , e.g. <code>US</code> (as in <code>en-US</code>) or * <code>PL</code> (as in <code>pl-PL</code>). * @return String[] - array of country options for the language. */ public abstract String[] getCountries(); /** * Get this language's variant, e.g. <code>valencia</code> (as in <code>ca-ES-valencia</code>) * or <code>null</code>. * Attention: not to be confused with "country" option * @return variant for the language or {@code null} * @since 2.3 */ @Nullable public String getVariant() { return null; } /** * Get enabled rules different from the default ones for this language variant. * * @return enabled rules for the language variant. * @since 2.4 */ public List<String> getDefaultEnabledRulesForVariant() { return new ArrayList<>(); } /** * Get disabled rules different from the default ones for this language variant. * * @return disabled rules for the language variant. * @since 2.4 */ public List<String> getDefaultDisabledRulesForVariant() { return new ArrayList<>(); } /** * Get the name(s) of the maintainer(s) for this language or <code>null</code>. */ @Nullable public abstract Contributor[] getMaintainers(); /** * Get the rules classes that should run for texts in this language. * @since 1.4 (signature modified in 2.7) */ public abstract List<Rule> getRelevantRules(ResourceBundle messages) throws IOException; // ------------------------------------------------------------------------- /** * @param indexDir directory with a '3grams' sub directory which contains a Lucene index with 3gram occurrence counts * @return a LanguageModel or {@code null} if this language doesn't support one * @since 2.7 */ @Nullable public LanguageModel getLanguageModel(File indexDir) throws IOException { return null; } /** * Get a list of rules that require a {@link LanguageModel}. Returns an empty list for * languages that don't have such rules. * @since 2.7 */ public List<Rule> getRelevantLanguageModelRules(ResourceBundle messages, LanguageModel languageModel) throws IOException { return Collections.emptyList(); } /** * Get this language's Java locale, not considering the country code. */ public Locale getLocale() { return new Locale(getShortName()); } /** * Get this language's Java locale, considering language code and country code (if any). * @since 2.1 */ public Locale getLocaleWithCountryAndVariant() { if (getCountries().length > 0) { if (getVariant() != null) { return new Locale(getShortName(), getCountries()[0], getVariant()); } else { return new Locale(getShortName(), getCountries()[0]); } } else { return getLocale(); } } /** * Get the location of the rule file(s) in a form like {@code /org/languagetool/rules/de/grammar.xml}. */ public List<String> getRuleFileNames() { final List<String> ruleFiles = new ArrayList<>(); ruleFiles.addAll(getExternalRuleFiles()); final ResourceDataBroker dataBroker = JLanguageTool.getDataBroker(); ruleFiles.add(dataBroker.getRulesDir() + "/" + getShortName() + "/" + JLanguageTool.PATTERN_FILE); if (getShortNameWithCountryAndVariant().length() > 2) { final String fileName = getShortName() + "/" + getShortNameWithCountryAndVariant() + "/" + JLanguageTool.PATTERN_FILE; if (dataBroker.ruleFileExists(fileName)) { ruleFiles.add(dataBroker.getRulesDir() + "/" + fileName); } } return ruleFiles; } /** * @since 2.6 */ public List<String> getExternalRuleFiles() { return externalRuleFiles; } /** * Adds an external rule file to the language. Call this method before * the language is given to the {@link JLanguageTool} constructor. * @param externalRuleFile Absolute file path to rules. * @since 2.6 */ public void addExternalRuleFile(String externalRuleFile) { externalRuleFiles.add(externalRuleFile); } /** * @return The list of file names for external false friend files. * @since 2.9 */ public List<String> getExternalFalseFriendFiles() { return externalFalseFriendFiles; } /** * Adds an external false friend rule file to the language. Call this method before * the language is given to the {@link JLanguageTool} constructor. * @since 2.9 */ public void addExternalFalseFriendFile(String externalFalseFriendFile) { externalFalseFriendFiles.add(externalFalseFriendFile); } /** * @return external bitext rule file names. * @since 2.9 */ public List<String> getExternalBitextRules() { return externalBitextRules; } /** * @param externalBitextRuleFile set an external bitext file to use in bitext checks * for this language (used as a target language) * @since 2.9 */ public void addExternalBitextRules(String externalBitextRuleFile) { externalBitextRules.add(externalBitextRuleFile); } /** * Languages that have country variants need to overwrite this to select their most common variant. * @return default country variant or {@code null} * @since 1.8 */ @Nullable public Language getDefaultLanguageVariant() { return null; } /** * Get this language's part-of-speech disambiguator implementation. */ public Disambiguator getDisambiguator() { return DEMO_DISAMBIGUATOR; } /** * Get this language's part-of-speech tagger implementation. The tagger must not * be {@code null}, but it can be a trivial pseudo-tagger that only assigns {@code null} tags. */ public Tagger getTagger() { return DEMO_TAGGER; } /** * Get this language's sentence tokenizer implementation. */ public SentenceTokenizer getSentenceTokenizer() { return SENTENCE_TOKENIZER; } /** * Get this language's word tokenizer implementation. */ public Tokenizer getWordTokenizer() { return WORD_TOKENIZER; } /** * Get this language's chunker implementation or {@code null}. * @since 2.3 */ @Nullable public Chunker getChunker() { return null; } /** * Get this language's chunker implementation or {@code null}. * @since 2.9 */ @Nullable public Chunker getPostDisambiguationChunker() { return null; } /** * Get this language's part-of-speech synthesizer implementation or {@code null}. */ @Nullable public Synthesizer getSynthesizer() { return null; } /** * Get this language's feature unifier. * @return Feature unifier for analyzed tokens. */ public Unifier getUnifier() { return unifierConfiguration.createUnifier(); } /** * Get this language's feature unifier used for disambiguation. * Note: it might be different from the normal rule unifier. * @return Feature unifier for analyzed tokens. */ public Unifier getDisambiguationUnifier() { return disambiguationUnifierConfiguration.createUnifier(); } /** * @since 2.3 */ public UnifierConfiguration getUnifierConfiguration() { return unifierConfiguration; } /** * @since 2.3 */ public UnifierConfiguration getDisambiguationUnifierConfiguration() { return disambiguationUnifierConfiguration; } /** * Get the name of the language translated to the current locale, * if available. Otherwise, get the untranslated name. */ public final String getTranslatedName(final ResourceBundle messages) { try { return messages.getString(getShortNameWithCountryAndVariant()); } catch (final MissingResourceException e) { try { return messages.getString(getShortName()); } catch (final MissingResourceException e1) { return getName(); } } } /** * Get the short name of the language with country and variant (if any), if it is * a single-country language. For generic language classes, get only a two- or * three-character code. * @since 1.8 */ public final String getShortNameWithCountryAndVariant() { String name = getShortName(); if (getCountries().length == 1 && !name.contains("-x-")) { // e.g. "de-DE-x-simple-language" name += "-" + getCountries()[0]; if (getVariant() != null) { // e.g. "ca-ES-valencia" name += "-" + getVariant(); } } return name; } // ------------------------------------------------------------------------- /** * Get the pattern rules as defined in the files returned by {@link #getRuleFileNames()}. * @since 2.7 */ @Experimental protected synchronized List<PatternRule> getPatternRules() throws IOException { if (patternRules == null) { patternRules = new ArrayList<>(); PatternRuleLoader ruleLoader = new PatternRuleLoader(); for (String fileName : getRuleFileNames()) { InputStream is = this.getClass().getResourceAsStream(fileName); if (is == null) { // files loaded via the dialog is = new FileInputStream(fileName); } patternRules.addAll(ruleLoader.getRules(is, fileName)); } } return patternRules; } // ------------------------------------------------------------------------- /** * Re-inits the built-in languages and adds the specified ones. * @deprecated (deprecated since 2.9) */ public static void reInit(final List<Language> languages) { LANGUAGES = new Language[BUILTIN_LANGUAGES.length + languages.size()]; int i = BUILTIN_LANGUAGES.length; System.arraycopy(BUILTIN_LANGUAGES, 0, LANGUAGES, 0, BUILTIN_LANGUAGES.length); for (final Language lang : languages) { LANGUAGES[i++] = lang; } externalLanguages = languages; } /** * Return languages that are not built-in but have been added manually. * @deprecated (deprecated since 2.9) */ public static List<Language> getExternalLanguages() { return externalLanguages; } /** * @deprecated use {@link Languages#get()} but note that is has slightly different semantics (no external languages) (deprecated since 2.9) */ public static List<Language> getAllLanguages() { final List<Language> langList = new ArrayList<>(); Collections.addAll(langList, LANGUAGES); langList.addAll(externalLanguages); return langList; } /** * @deprecated use {@link Languages#getLanguageForName(String)} (deprecated since 2.9) */ @Nullable public static Language getLanguageForName(final String languageName) { for (Language element : Language.LANGUAGES) { if (languageName.equals(element.getName())) { return element; } } return null; } /** * @deprecated use {@link Languages#getLanguageForShortName(String)} (deprecated since 2.9) */ public static Language getLanguageForShortName(final String langCode) { final Language language = getLanguageForShortNameOrNull(langCode); if (language == null) { final List<String> codes = new ArrayList<>(); for (Language realLanguage : LANGUAGES) { codes.add(realLanguage.getShortNameWithCountryAndVariant()); } Collections.sort(codes); throw new IllegalArgumentException("'" + langCode + "' is not a language code known to LanguageTool." + " Supported language codes are: " + StringUtils.join(codes, ", ") + ". The list of languages is read from " + PROPERTIES_PATH + " in the Java classpath. See http://wiki.languagetool.org/java-api for details."); } return language; } /** * @deprecated use {@link Languages#isLanguageSupported(String)} (deprecated since 2.9) */ public static boolean isLanguageSupported(final String langCode) { return getLanguageForShortNameOrNull(langCode) != null; } @Nullable private static Language getLanguageForShortNameOrNull(final String langCode) { StringTools.assureSet(langCode, "langCode"); Language result = null; if (langCode.contains("-x-")) { // e.g. "de-DE-x-simple-language" for (Language element : Language.LANGUAGES) { if (element.getShortName().equalsIgnoreCase(langCode)) { return element; } } } else if (langCode.contains("-")) { final String[] parts = langCode.split("-"); if (parts.length == 2) { // e.g. en-US for (Language element : Language.LANGUAGES) { if (parts[0].equalsIgnoreCase(element.getShortName()) && element.getCountries().length == 1 && parts[1].equalsIgnoreCase(element.getCountries()[0])) { result = element; break; } } } else if (parts.length == 3) { // e.g. ca-ES-valencia for (Language element : Language.LANGUAGES) { if (parts[0].equalsIgnoreCase(element.getShortName()) && element.getCountries().length == 1 && parts[1].equalsIgnoreCase(element.getCountries()[0]) && parts[2].equalsIgnoreCase(element.getVariant())) { result = element; break; } } } else { throw new IllegalArgumentException("'" + langCode + "' isn't a valid language code"); } } else { for (Language element : Language.LANGUAGES) { if (langCode.equalsIgnoreCase(element.getShortName())) { result = element; break; } } } return result; } /** * @deprecated use {@link Languages#getLanguageForLocale(java.util.Locale)} (deprecated since 2.9) */ public static Language getLanguageForLocale(final Locale locale) { final Language language = getLanguageForLanguageNameAndCountry(locale); if (language != null) { return language; } else { final Language firstFallbackLanguage = getLanguageForLanguageNameOnly(locale); if (firstFallbackLanguage != null) { return firstFallbackLanguage; } } for (Language aLanguage : REAL_LANGUAGES) { if (aLanguage.getShortNameWithCountryAndVariant().equals("en-US")) { return aLanguage; } } throw new RuntimeException("No appropriate language found, not even en-US. Supported languages: " + Arrays.toString(REAL_LANGUAGES)); } @Nullable private static Language getLanguageForLanguageNameAndCountry(Locale locale) { for (Language language : Language.REAL_LANGUAGES) { if (language.getShortName().equals(locale.getLanguage())) { final List<String> countryVariants = Arrays.asList(language.getCountries()); if (countryVariants.contains(locale.getCountry())) { return language; } } } return null; } @Nullable private static Language getLanguageForLanguageNameOnly(Locale locale) { // use default variant if available: for (Language language : Language.REAL_LANGUAGES) { if (language.getShortName().equals(locale.getLanguage()) && language.hasVariant()) { final Language defaultVariant = language.getDefaultLanguageVariant(); if (defaultVariant != null) { return defaultVariant; } } } // use the first match otherwise (which should be the only match): for (Language language : Language.REAL_LANGUAGES) { if (language.getShortName().equals(locale.getLanguage()) && !language.hasVariant()) { return language; } } return null; } @Override public final String toString() { return getName(); } /** * Whether this is a country variant of another language, i.e. whether it doesn't * directly extend {@link Language}, but a subclass of {@link Language}. * @since 1.8 */ public final boolean isVariant() { for (Language language : LANGUAGES) { final boolean skip = language.getShortNameWithCountryAndVariant().equals(getShortNameWithCountryAndVariant()); if (!skip && language.getClass().isAssignableFrom(getClass())) { return true; } } return false; } /** * Whether this class has at least one subclass that implements variants of this language. * @since 1.8 */ public final boolean hasVariant() { for (Language language : LANGUAGES) { final boolean skip = language.getShortNameWithCountryAndVariant().equals(getShortNameWithCountryAndVariant()); if (!skip && getClass().isAssignableFrom(language.getClass())) { return true; } } return false; } public boolean isExternal() { return isExternalLanguage; } /** * Sets the language as external. Useful for * making a copy of an existing language. * @since 2.6 */ public void makeExternal() { isExternalLanguage = true; } /** * Return true if this is the same language as the given one, considering country * variants only if set for both languages. For example: en = en, en = en-GB, en-GB = en-GB, * but en-US != en-GB * @since 1.8 */ public boolean equalsConsiderVariantsIfSpecified(Language otherLanguage) { if (getShortName().equals(otherLanguage.getShortName())) { final boolean thisHasCountry = hasCountry(); final boolean otherHasCountry = otherLanguage.hasCountry(); return !(thisHasCountry && otherHasCountry) || getShortNameWithCountryAndVariant().equals(otherLanguage.getShortNameWithCountryAndVariant()); } else { return false; } } private boolean hasCountry() { return getCountries().length == 1; } /** * @return Return compiled regular expression to ignore inside tokens * @since 2.9 */ public Pattern getIgnoredCharactersRegex() { return ignoredCharactersRegex; } /** * Sets the regular expression (usually set of chars) to ignore inside tokens. * By default only soft hyphen ({@code \u00AD}) is ignored. * @since 2.9 */ public void setIgnoredCharactersRegex(String ignoredCharactersRegex) { this.ignoredCharactersRegex = Pattern.compile(ignoredCharactersRegex); } }
languagetool-core/src/main/java/org/languagetool/Language.java
/* LanguageTool, a natural language style checker * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.Nullable; import org.languagetool.chunking.Chunker; import org.languagetool.databroker.ResourceDataBroker; import org.languagetool.language.Contributor; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.rules.Rule; import org.languagetool.rules.patterns.PatternRule; import org.languagetool.rules.patterns.PatternRuleLoader; import org.languagetool.rules.patterns.Unifier; import org.languagetool.rules.patterns.UnifierConfiguration; import org.languagetool.synthesis.Synthesizer; import org.languagetool.tagging.Tagger; import org.languagetool.tagging.disambiguation.Disambiguator; import org.languagetool.tagging.disambiguation.xx.DemoDisambiguator; import org.languagetool.tagging.xx.DemoTagger; import org.languagetool.tokenizers.*; import org.languagetool.tools.MultiKeyProperties; import org.languagetool.tools.StringTools; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.net.URL; import java.util.*; import java.util.regex.Pattern; /** * Base class for any supported language (English, German, etc). Language classes * are detected at runtime by searching the classpath for files named * {@code META-INF/org/languagetool/language-module.properties}. Those file(s) * need to contain a key {@code languageClasses} which specifies the fully qualified * class name(s), e.g. {@code org.languagetool.language.English}. Use commas to specify * more than one class. */ public abstract class Language { private static final String PROPERTIES_PATH = "META-INF/org/languagetool/language-module.properties"; private static final String PROPERTIES_KEY = "languageClasses"; private static List<Language> externalLanguages = new ArrayList<>(); private final List<String> externalRuleFiles = new ArrayList<>(); private final List<String> externalFalseFriendFiles = new ArrayList<>(); private final List<String> externalBitextRules = new ArrayList<>(); private boolean isExternalLanguage = false; private Pattern ignoredCharactersRegex = Pattern.compile("[\u00AD]"); // soft hyphen private List<PatternRule> patternRules; /** * All languages supported by LanguageTool. This includes at least a "demo" language * for testing. * @deprecated use {@link Languages#getWithDemoLanguage()} instead (deprecated since 2.9) */ public static Language[] LANGUAGES = getLanguages(); // TODO: remove once LANGUAGES is removed private static Language[] getLanguages() { final List<Language> languages = new ArrayList<>(); final Set<String> languageClassNames = new HashSet<>(); try { final Enumeration<URL> propertyFiles = Language.class.getClassLoader().getResources(PROPERTIES_PATH); while (propertyFiles.hasMoreElements()) { final URL url = propertyFiles.nextElement(); try (InputStream inputStream = url.openStream()) { // We want to be able to read properties file with duplicate key, as produced by // Maven when merging files: final MultiKeyProperties props = new MultiKeyProperties(inputStream); final List<String> classNamesStr = props.getProperty(PROPERTIES_KEY); if (classNamesStr == null) { throw new RuntimeException("Key '" + PROPERTIES_KEY + "' not found in " + url); } for (String classNames : classNamesStr) { final String[] classNamesSplit = classNames.split("\\s*,\\s*"); for (String className : classNamesSplit) { if (languageClassNames.contains(className)) { // avoid duplicates - this way we are robust against problems with the maven assembly // plugin which aggregates files more than once (in case the deployment descriptor // contains both <format>zip</format> and <format>dir</format>): continue; } languages.add(createLanguageObjects(url, className)); languageClassNames.add(className); } } } } } catch (IOException e) { throw new RuntimeException(e); } return languages.toArray(new Language[languages.size()]); } private static Language createLanguageObjects(URL url, String className) { try { final Class<?> aClass = Class.forName(className); final Constructor<?> constructor = aClass.getConstructor(); return (Language) constructor.newInstance(); } catch (ClassNotFoundException e) { throw new RuntimeException("Class '" + className + "' specified in " + url + " could not be found in classpath", e); } catch (Exception e) { throw new RuntimeException("Object for class '" + className + "' specified in " + url + " could not created", e); } } /** * All languages supported by LanguageTool, but without the demo language. * @deprecated use {@link Languages#get()} instead (deprecated since 2.9) */ public static final Language[] REAL_LANGUAGES = getRealLanguages(); /** * Returns all languages supported by LanguageTool but without the demo language. * In contrast to Language.REAL_LANGUAGES contains external languages as well. * @return All supported languages. * @deprecated use {@link Languages#get()} instead (deprecated since 2.9) * @since 2.6 */ public static Language[] getRealLanguages() { List<Language> result = new ArrayList<>(); for (Language lang : LANGUAGES) { if (!"xx".equals(lang.getShortName())) { // skip demo language result.add(lang); } } return result.toArray(new Language[result.size()]); } private static final Language[] BUILTIN_LANGUAGES = LANGUAGES; private static final Disambiguator DEMO_DISAMBIGUATOR = new DemoDisambiguator(); private static final Tagger DEMO_TAGGER = new DemoTagger(); private static final SentenceTokenizer SENTENCE_TOKENIZER = new SimpleSentenceTokenizer(); private static final WordTokenizer WORD_TOKENIZER = new WordTokenizer(); private final UnifierConfiguration unifierConfiguration = new UnifierConfiguration(); private final UnifierConfiguration disambiguationUnifierConfiguration = new UnifierConfiguration(); // ------------------------------------------------------------------------- /** * Get this language's two character code, e.g. <code>en</code> for English. * The country parameter (e.g. "US"), if any, is not returned. * @return language code */ public abstract String getShortName(); /** * Get this language's name in English, e.g. <code>English</code> or * <code>German (Germany)</code>. * @return language name */ public abstract String getName(); /** * Set this language's name in English. * @since 2.6 */ public abstract void setName(final String name); /** * Get this language's country options , e.g. <code>US</code> (as in <code>en-US</code>) or * <code>PL</code> (as in <code>pl-PL</code>). * @return String[] - array of country options for the language. */ public abstract String[] getCountries(); /** * Get this language's variant, e.g. <code>valencia</code> (as in <code>ca-ES-valencia</code>) * or <code>null</code>. * Attention: not to be confused with "country" option * @return variant for the language or {@code null} * @since 2.3 */ @Nullable public String getVariant() { return null; } /** * Get enabled rules different from the default ones for this language variant. * * @return enabled rules for the language variant. * @since 2.4 */ public List<String> getDefaultEnabledRulesForVariant() { return new ArrayList<>(); } /** * Get disabled rules different from the default ones for this language variant. * * @return disabled rules for the language variant. * @since 2.4 */ public List<String> getDefaultDisabledRulesForVariant() { return new ArrayList<>(); } /** * Get the name(s) of the maintainer(s) for this language or <code>null</code>. */ @Nullable public abstract Contributor[] getMaintainers(); /** * Get the rules classes that should run for texts in this language. * @since 1.4 (signature modified in 2.7) */ public abstract List<Rule> getRelevantRules(ResourceBundle messages) throws IOException; // ------------------------------------------------------------------------- /** * @param indexDir directory with a '3grams' sub directory which contains a Lucene index with 3gram occurrence counts * @return a LanguageModel or {@code null} if this language doesn't support one * @since 2.7 */ @Nullable public LanguageModel getLanguageModel(File indexDir) throws IOException { return null; } /** * Get a list of rules that require a {@link LanguageModel}. Returns an empty list for * languages that don't have such rules. * @since 2.7 */ public List<Rule> getRelevantLanguageModelRules(ResourceBundle messages, LanguageModel languageModel) throws IOException { return Collections.emptyList(); } /** * Get this language's Java locale, not considering the country code. */ public Locale getLocale() { return new Locale(getShortName()); } /** * Get this language's Java locale, considering language code and country code (if any). * @since 2.1 */ public Locale getLocaleWithCountryAndVariant() { if (getCountries().length > 0) { if (getVariant() != null) { return new Locale(getShortName(), getCountries()[0], getVariant()); } else { return new Locale(getShortName(), getCountries()[0]); } } else { return getLocale(); } } /** * Get the location of the rule file(s) in a form like {@code /org/languagetool/rules/de/grammar.xml}. */ public List<String> getRuleFileNames() { final List<String> ruleFiles = new ArrayList<>(); ruleFiles.addAll(getExternalRuleFiles()); final ResourceDataBroker dataBroker = JLanguageTool.getDataBroker(); ruleFiles.add(dataBroker.getRulesDir() + "/" + getShortName() + "/" + JLanguageTool.PATTERN_FILE); if (getShortNameWithCountryAndVariant().length() > 2) { final String fileName = getShortName() + "/" + getShortNameWithCountryAndVariant() + "/" + JLanguageTool.PATTERN_FILE; if (dataBroker.ruleFileExists(fileName)) { ruleFiles.add(dataBroker.getRulesDir() + "/" + fileName); } } return ruleFiles; } /** * @since 2.6 */ public List<String> getExternalRuleFiles() { return externalRuleFiles; } /** * Adds an external rule file to the language. After running this method, * one has to run JLanguageTool.activateDefaultPatternRules() to make sure * that all external rules are activated. * * @param externalRuleFile Absolute file path to rules. * @since 2.6 */ public void addExternalRuleFile(String externalRuleFile) { externalRuleFiles.add(externalRuleFile); } /** * @return The list of file names for external false friend files. * @since 2.9 */ public List<String> getExternalFalseFriendFiles() { return externalFalseFriendFiles; } /** * Adds an external false friend rule file to the language. After running this method, * one has to run JLanguageTool.activateDefaultFalseFriendRules() to make sure * that all external rules are activated. * @since 2.9 */ public void addExternalFalseFriendFile(String externalFalseFriendFile) { externalFalseFriendFiles.add(externalFalseFriendFile); } /** * @return external bitext rule file names. * @since 2.9 */ public List<String> getExternalBitextRules() { return externalBitextRules; } /** * @param externalBitextRuleFile set an external bitext file to use in bitext checks * for this language (used as a target language) * @since 2.9 */ public void addExternalBitextRules(String externalBitextRuleFile) { externalBitextRules.add(externalBitextRuleFile); } /** * Languages that have country variants need to overwrite this to select their most common variant. * @return default country variant or {@code null} * @since 1.8 */ @Nullable public Language getDefaultLanguageVariant() { return null; } /** * Get this language's part-of-speech disambiguator implementation. */ public Disambiguator getDisambiguator() { return DEMO_DISAMBIGUATOR; } /** * Get this language's part-of-speech tagger implementation. The tagger must not * be {@code null}, but it can be a trivial pseudo-tagger that only assigns {@code null} tags. */ public Tagger getTagger() { return DEMO_TAGGER; } /** * Get this language's sentence tokenizer implementation. */ public SentenceTokenizer getSentenceTokenizer() { return SENTENCE_TOKENIZER; } /** * Get this language's word tokenizer implementation. */ public Tokenizer getWordTokenizer() { return WORD_TOKENIZER; } /** * Get this language's chunker implementation or {@code null}. * @since 2.3 */ @Nullable public Chunker getChunker() { return null; } /** * Get this language's chunker implementation or {@code null}. * @since 2.9 */ @Nullable public Chunker getPostDisambiguationChunker() { return null; } /** * Get this language's part-of-speech synthesizer implementation or {@code null}. */ @Nullable public Synthesizer getSynthesizer() { return null; } /** * Get this language's feature unifier. * @return Feature unifier for analyzed tokens. */ public Unifier getUnifier() { return unifierConfiguration.createUnifier(); } /** * Get this language's feature unifier used for disambiguation. * Note: it might be different from the normal rule unifier. * @return Feature unifier for analyzed tokens. */ public Unifier getDisambiguationUnifier() { return disambiguationUnifierConfiguration.createUnifier(); } /** * @since 2.3 */ public UnifierConfiguration getUnifierConfiguration() { return unifierConfiguration; } /** * @since 2.3 */ public UnifierConfiguration getDisambiguationUnifierConfiguration() { return disambiguationUnifierConfiguration; } /** * Get the name of the language translated to the current locale, * if available. Otherwise, get the untranslated name. */ public final String getTranslatedName(final ResourceBundle messages) { try { return messages.getString(getShortNameWithCountryAndVariant()); } catch (final MissingResourceException e) { try { return messages.getString(getShortName()); } catch (final MissingResourceException e1) { return getName(); } } } /** * Get the short name of the language with country and variant (if any), if it is * a single-country language. For generic language classes, get only a two- or * three-character code. * @since 1.8 */ public final String getShortNameWithCountryAndVariant() { String name = getShortName(); if (getCountries().length == 1 && !name.contains("-x-")) { // e.g. "de-DE-x-simple-language" name += "-" + getCountries()[0]; if (getVariant() != null) { // e.g. "ca-ES-valencia" name += "-" + getVariant(); } } return name; } // ------------------------------------------------------------------------- /** * Get the pattern rules as defined in the files returned by {@link #getRuleFileNames()}. * @since 2.7 */ @Experimental protected synchronized List<PatternRule> getPatternRules() throws IOException { if (patternRules == null) { patternRules = new ArrayList<>(); PatternRuleLoader ruleLoader = new PatternRuleLoader(); for (String fileName : getRuleFileNames()) { InputStream is = this.getClass().getResourceAsStream(fileName); if (is == null) { // files loaded via the dialog is = new FileInputStream(fileName); } patternRules.addAll(ruleLoader.getRules(is, fileName)); } } return patternRules; } // ------------------------------------------------------------------------- /** * Re-inits the built-in languages and adds the specified ones. * @deprecated (deprecated since 2.9) */ public static void reInit(final List<Language> languages) { LANGUAGES = new Language[BUILTIN_LANGUAGES.length + languages.size()]; int i = BUILTIN_LANGUAGES.length; System.arraycopy(BUILTIN_LANGUAGES, 0, LANGUAGES, 0, BUILTIN_LANGUAGES.length); for (final Language lang : languages) { LANGUAGES[i++] = lang; } externalLanguages = languages; } /** * Return languages that are not built-in but have been added manually. * @deprecated (deprecated since 2.9) */ public static List<Language> getExternalLanguages() { return externalLanguages; } /** * @deprecated use {@link Languages#get()} but note that is has slightly different semantics (no external languages) (deprecated since 2.9) */ public static List<Language> getAllLanguages() { final List<Language> langList = new ArrayList<>(); Collections.addAll(langList, LANGUAGES); langList.addAll(externalLanguages); return langList; } /** * @deprecated use {@link Languages#getLanguageForName(String)} (deprecated since 2.9) */ @Nullable public static Language getLanguageForName(final String languageName) { for (Language element : Language.LANGUAGES) { if (languageName.equals(element.getName())) { return element; } } return null; } /** * @deprecated use {@link Languages#getLanguageForShortName(String)} (deprecated since 2.9) */ public static Language getLanguageForShortName(final String langCode) { final Language language = getLanguageForShortNameOrNull(langCode); if (language == null) { final List<String> codes = new ArrayList<>(); for (Language realLanguage : LANGUAGES) { codes.add(realLanguage.getShortNameWithCountryAndVariant()); } Collections.sort(codes); throw new IllegalArgumentException("'" + langCode + "' is not a language code known to LanguageTool." + " Supported language codes are: " + StringUtils.join(codes, ", ") + ". The list of languages is read from " + PROPERTIES_PATH + " in the Java classpath. See http://wiki.languagetool.org/java-api for details."); } return language; } /** * @deprecated use {@link Languages#isLanguageSupported(String)} (deprecated since 2.9) */ public static boolean isLanguageSupported(final String langCode) { return getLanguageForShortNameOrNull(langCode) != null; } @Nullable private static Language getLanguageForShortNameOrNull(final String langCode) { StringTools.assureSet(langCode, "langCode"); Language result = null; if (langCode.contains("-x-")) { // e.g. "de-DE-x-simple-language" for (Language element : Language.LANGUAGES) { if (element.getShortName().equalsIgnoreCase(langCode)) { return element; } } } else if (langCode.contains("-")) { final String[] parts = langCode.split("-"); if (parts.length == 2) { // e.g. en-US for (Language element : Language.LANGUAGES) { if (parts[0].equalsIgnoreCase(element.getShortName()) && element.getCountries().length == 1 && parts[1].equalsIgnoreCase(element.getCountries()[0])) { result = element; break; } } } else if (parts.length == 3) { // e.g. ca-ES-valencia for (Language element : Language.LANGUAGES) { if (parts[0].equalsIgnoreCase(element.getShortName()) && element.getCountries().length == 1 && parts[1].equalsIgnoreCase(element.getCountries()[0]) && parts[2].equalsIgnoreCase(element.getVariant())) { result = element; break; } } } else { throw new IllegalArgumentException("'" + langCode + "' isn't a valid language code"); } } else { for (Language element : Language.LANGUAGES) { if (langCode.equalsIgnoreCase(element.getShortName())) { result = element; break; } } } return result; } /** * @deprecated use {@link Languages#getLanguageForLocale(java.util.Locale)} (deprecated since 2.9) */ public static Language getLanguageForLocale(final Locale locale) { final Language language = getLanguageForLanguageNameAndCountry(locale); if (language != null) { return language; } else { final Language firstFallbackLanguage = getLanguageForLanguageNameOnly(locale); if (firstFallbackLanguage != null) { return firstFallbackLanguage; } } for (Language aLanguage : REAL_LANGUAGES) { if (aLanguage.getShortNameWithCountryAndVariant().equals("en-US")) { return aLanguage; } } throw new RuntimeException("No appropriate language found, not even en-US. Supported languages: " + Arrays.toString(REAL_LANGUAGES)); } @Nullable private static Language getLanguageForLanguageNameAndCountry(Locale locale) { for (Language language : Language.REAL_LANGUAGES) { if (language.getShortName().equals(locale.getLanguage())) { final List<String> countryVariants = Arrays.asList(language.getCountries()); if (countryVariants.contains(locale.getCountry())) { return language; } } } return null; } @Nullable private static Language getLanguageForLanguageNameOnly(Locale locale) { // use default variant if available: for (Language language : Language.REAL_LANGUAGES) { if (language.getShortName().equals(locale.getLanguage()) && language.hasVariant()) { final Language defaultVariant = language.getDefaultLanguageVariant(); if (defaultVariant != null) { return defaultVariant; } } } // use the first match otherwise (which should be the only match): for (Language language : Language.REAL_LANGUAGES) { if (language.getShortName().equals(locale.getLanguage()) && !language.hasVariant()) { return language; } } return null; } @Override public final String toString() { return getName(); } /** * Whether this is a country variant of another language, i.e. whether it doesn't * directly extend {@link Language}, but a subclass of {@link Language}. * @since 1.8 */ public final boolean isVariant() { for (Language language : LANGUAGES) { final boolean skip = language.getShortNameWithCountryAndVariant().equals(getShortNameWithCountryAndVariant()); if (!skip && language.getClass().isAssignableFrom(getClass())) { return true; } } return false; } /** * Whether this class has at least one subclass that implements variants of this language. * @since 1.8 */ public final boolean hasVariant() { for (Language language : LANGUAGES) { final boolean skip = language.getShortNameWithCountryAndVariant().equals(getShortNameWithCountryAndVariant()); if (!skip && getClass().isAssignableFrom(language.getClass())) { return true; } } return false; } public boolean isExternal() { return isExternalLanguage; } /** * Sets the language as external. Useful for * making a copy of an existing language. * @since 2.6 */ public void makeExternal() { isExternalLanguage = true; } /** * Return true if this is the same language as the given one, considering country * variants only if set for both languages. For example: en = en, en = en-GB, en-GB = en-GB, * but en-US != en-GB * @since 1.8 */ public boolean equalsConsiderVariantsIfSpecified(Language otherLanguage) { if (getShortName().equals(otherLanguage.getShortName())) { final boolean thisHasCountry = hasCountry(); final boolean otherHasCountry = otherLanguage.hasCountry(); return !(thisHasCountry && otherHasCountry) || getShortNameWithCountryAndVariant().equals(otherLanguage.getShortNameWithCountryAndVariant()); } else { return false; } } private boolean hasCountry() { return getCountries().length == 1; } /** * @return Return compiled regular expression to ignore inside tokens * @since 2.9 */ public Pattern getIgnoredCharactersRegex() { return ignoredCharactersRegex; } /** * Sets the regular expression (usually set of chars) to ignore inside tokens. * By default only soft hyphen ({@code \u00AD}) is ignored. * @since 2.9 */ public void setIgnoredCharactersRegex(String ignoredCharactersRegex) { this.ignoredCharactersRegex = Pattern.compile(ignoredCharactersRegex); } }
fix javadoc
languagetool-core/src/main/java/org/languagetool/Language.java
fix javadoc
Java
lgpl-2.1
8b5bced3d7a93ced958fe4f281bcac5844ebd247
0
SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer
package eu.seebetter.ini.chips.davis; import java.awt.Point; import eu.seebetter.ini.chips.DavisChip; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.event.ApsDvsEvent.ColorFilter; import net.sf.jaer.hardwareinterface.HardwareInterface; @Description("Davis128 base class for 128x128 pixel sensitive APS-DVS DAVIS sensor with RGBG color filter") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class Davis128Color extends DavisBaseCamera { public static final short WIDTH_PIXELS = 128; public static final short HEIGHT_PIXELS = 128; public static final ColorFilter[] COLOR_FILTER = { ColorFilter.B, ColorFilter.G, ColorFilter.R, ColorFilter.G }; public static final float[][] COLOR_CORRECTION = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 } }; public Davis128Color() { setName("Davis128"); setDefaultPreferencesFile("biasgenSettings/Davis128/Davis128.xml"); setSizeX(Davis128Color.WIDTH_PIXELS); setSizeY(Davis128Color.HEIGHT_PIXELS); setEventExtractor(new DavisColorEventExtractor(this, false, true, Davis128Color.COLOR_FILTER, false)); setBiasgen(davisConfig = new DavisTowerBaseConfig(this)); davisRenderer = new DavisColorRenderer(this, false, Davis128Color.COLOR_FILTER, false, Davis128Color.COLOR_CORRECTION); davisRenderer.setMaxADC(DavisChip.MAX_ADC); setRenderer(davisRenderer); setApsFirstPixelReadOut(new Point(getSizeX() - 1, getSizeY() - 1)); setApsLastPixelReadOut(new Point(0, 0)); } public Davis128Color(final HardwareInterface hardwareInterface) { this(); setHardwareInterface(hardwareInterface); } }
src/eu/seebetter/ini/chips/davis/Davis128Color.java
package eu.seebetter.ini.chips.davis; import java.awt.Point; import eu.seebetter.ini.chips.DavisChip; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.event.ApsDvsEvent.ColorFilter; import net.sf.jaer.hardwareinterface.HardwareInterface; @Description("Davis128 base class for 128x128 pixel sensitive APS-DVS DAVIS sensor with RGBG color filter") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class Davis128Color extends DavisBaseCamera { public static final short WIDTH_PIXELS = 128; public static final short HEIGHT_PIXELS = 128; public static final ColorFilter[] COLOR_FILTER = { ColorFilter.B, ColorFilter.G, ColorFilter.R, ColorFilter.B }; public static final float[][] COLOR_CORRECTION = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 } }; public Davis128Color() { setName("Davis128"); setDefaultPreferencesFile("biasgenSettings/Davis128/Davis128.xml"); setSizeX(Davis128Color.WIDTH_PIXELS); setSizeY(Davis128Color.HEIGHT_PIXELS); setEventExtractor(new DavisColorEventExtractor(this, false, true, Davis128Color.COLOR_FILTER, false)); setBiasgen(davisConfig = new DavisTowerBaseConfig(this)); davisRenderer = new DavisColorRenderer(this, false, Davis128Color.COLOR_FILTER, false, Davis128Color.COLOR_CORRECTION); davisRenderer.setMaxADC(DavisChip.MAX_ADC); setRenderer(davisRenderer); setApsFirstPixelReadOut(new Point(getSizeX() - 1, getSizeY() - 1)); setApsLastPixelReadOut(new Point(0, 0)); } public Davis128Color(final HardwareInterface hardwareInterface) { this(); setHardwareInterface(hardwareInterface); } }
fixed reticle git-svn-id: fe6b3b33f0410f5f719dcd9e0c58b92353e7a5d3@9149 b7f4320f-462c-0410-a916-d9f35bb82d52
src/eu/seebetter/ini/chips/davis/Davis128Color.java
fixed reticle
Java
apache-2.0
ec0d03057184bc967ca5cbf662dd9235f91db0f3
0
TangHao1987/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,allotria/intellij-community,consulo/consulo,fnouama/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,signed/intellij-community,robovm/robovm-studio,holmes/intellij-community,amith01994/intellij-community,apixandru/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,allotria/intellij-community,amith01994/intellij-community,asedunov/intellij-community,da1z/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,ryano144/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,caot/intellij-community,holmes/intellij-community,ernestp/consulo,joewalnes/idea-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,jagguli/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,asedunov/intellij-community,retomerz/intellij-community,kdwink/intellij-community,semonte/intellij-community,fitermay/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,petteyg/intellij-community,consulo/consulo,mglukhikh/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,caot/intellij-community,izonder/intellij-community,fnouama/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,slisson/intellij-community,semonte/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,slisson/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,ryano144/intellij-community,ibinti/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,jagguli/intellij-community,hurricup/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,adedayo/intellij-community,kool79/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,caot/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,diorcety/intellij-community,da1z/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,jagguli/intellij-community,robovm/robovm-studio,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,allotria/intellij-community,ahb0327/intellij-community,signed/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,dslomov/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,wreckJ/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,slisson/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,apixandru/intellij-community,adedayo/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,joewalnes/idea-community,apixandru/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,fitermay/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,apixandru/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,da1z/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,blademainer/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,ernestp/consulo,petteyg/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,supersven/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,samthor/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,consulo/consulo,akosyakov/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,supersven/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,holmes/intellij-community,signed/intellij-community,apixandru/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,kdwink/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,signed/intellij-community,clumsy/intellij-community,ryano144/intellij-community,FHannes/intellij-community,joewalnes/idea-community,adedayo/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,xfournet/intellij-community,holmes/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,allotria/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,fnouama/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,signed/intellij-community,supersven/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,slisson/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,supersven/intellij-community,semonte/intellij-community,ryano144/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,signed/intellij-community,salguarnieri/intellij-community,caot/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,semonte/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,kool79/intellij-community,asedunov/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,ernestp/consulo,izonder/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,slisson/intellij-community,signed/intellij-community,blademainer/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,allotria/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,kool79/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,caot/intellij-community,izonder/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,kool79/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,petteyg/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,consulo/consulo,mglukhikh/intellij-community,dslomov/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,vladmm/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,xfournet/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,da1z/intellij-community,caot/intellij-community,clumsy/intellij-community,fnouama/intellij-community,slisson/intellij-community,kool79/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,gnuhub/intellij-community,supersven/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,fitermay/intellij-community,jagguli/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,hurricup/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,holmes/intellij-community,dslomov/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,signed/intellij-community,holmes/intellij-community,tmpgit/intellij-community,izonder/intellij-community,joewalnes/idea-community,idea4bsd/idea4bsd,semonte/intellij-community,fnouama/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,asedunov/intellij-community,allotria/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,ernestp/consulo,clumsy/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,caot/intellij-community,supersven/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,consulo/consulo,kool79/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,supersven/intellij-community,joewalnes/idea-community,da1z/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,signed/intellij-community,da1z/intellij-community,samthor/intellij-community,signed/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,slisson/intellij-community,hurricup/intellij-community,da1z/intellij-community,adedayo/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,signed/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,amith01994/intellij-community,kdwink/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,fitermay/intellij-community,signed/intellij-community,da1z/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,ibinti/intellij-community,diorcety/intellij-community,kdwink/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,petteyg/intellij-community,allotria/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,allotria/intellij-community,slisson/intellij-community,dslomov/intellij-community,ibinti/intellij-community,kdwink/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,joewalnes/idea-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,caot/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,clumsy/intellij-community,blademainer/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,joewalnes/idea-community,amith01994/intellij-community,holmes/intellij-community,fnouama/intellij-community,retomerz/intellij-community,xfournet/intellij-community,samthor/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,supersven/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,allotria/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,fnouama/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,amith01994/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,holmes/intellij-community,izonder/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,consulo/consulo,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,izonder/intellij-community,kdwink/intellij-community,petteyg/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,da1z/intellij-community,orekyuu/intellij-community,samthor/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,xfournet/intellij-community,retomerz/intellij-community,vladmm/intellij-community,ryano144/intellij-community,clumsy/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,diorcety/intellij-community,kool79/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,samthor/intellij-community,apixandru/intellij-community,samthor/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community
/* * Copyright 2006 Sascha Weinreuter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.intelliLang.util; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInspection.dataFlow.DfaUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.psi.*; import com.intellij.psi.util.CachedValue; import com.intellij.util.containers.ConcurrentHashMap; import org.intellij.plugins.intelliLang.Configuration; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; import java.util.concurrent.ConcurrentMap; /** * Computes the constant value of an expression while considering the substitution annotation for non-compile-time * constant expressions. * <p/> * This is a quite simplified implementation at the moment. */ public class SubstitutedExpressionEvaluationHelper { private static final Key<CachedValue<ConcurrentMap<PsiElement, Object>>> COMPUTED_MAP_KEY = Key.create("COMPUTED_MAP_KEY"); private final PsiConstantEvaluationHelper myHelper; private final Configuration myConfiguration; public SubstitutedExpressionEvaluationHelper(final Project project) { myHelper = JavaPsiFacade.getInstance(project).getConstantEvaluationHelper(); myConfiguration = Configuration.getInstance(); } public Object computeExpression(final PsiExpression e, final boolean includeUncomputablesAsLiterals) { return computeExpression(e, includeUncomputablesAsLiterals, null); } public Object computeExpression(final PsiExpression e, final boolean includeUncomputablesAsLiterals, final List<PsiExpression> uncomputables) { final ConcurrentMap<PsiElement, Object> map = new ConcurrentHashMap<PsiElement, Object>(); //if (true) return myHelper.computeConstantExpression(e, false); return myHelper.computeExpression(e, false, new PsiConstantEvaluationHelper.AuxEvaluator() { @Nullable public Object computeExpression(final PsiExpression o, final PsiConstantEvaluationHelper.AuxEvaluator auxEvaluator) { PsiType resolvedType = null; if (o instanceof PsiMethodCallExpression) { final PsiMethodCallExpression c = (PsiMethodCallExpression)o; final PsiMethod m = (PsiMethod)c.getMethodExpression().resolve(); final PsiType returnType = m != null? m.getReturnType() : null; if (returnType != null && returnType != PsiType.VOID) { // find substitution final Object substituted = calcSubstituted(m); if (substituted != null) return substituted; } resolvedType = returnType; } else if (o instanceof PsiReferenceExpression) { final PsiElement resolved = ((PsiReferenceExpression)o).resolve(); if (resolved instanceof PsiModifierListOwner) { // find substitution final Object substituted = calcSubstituted((PsiModifierListOwner)resolved); if (substituted != null) return substituted; if (resolved instanceof PsiVariable) { resolvedType = ((PsiVariable)resolved).getType(); final Collection<PsiExpression> values = DfaUtil.getCachedVariableValues(((PsiVariable)resolved), o); // return the first computed value as far as we do not support multiple injection for (PsiExpression value : values) { final Object computedValue = auxEvaluator.computeExpression(value, this); if (computedValue != null) { return computedValue; } } } } } if (uncomputables != null) uncomputables.add(o); if (includeUncomputablesAsLiterals) { if (resolvedType != null) { if (PsiPrimitiveType.DOUBLE.isAssignableFrom(resolvedType)) return 1; // magic number! } final StringBuilder sb = new StringBuilder(); o.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(PsiElement element) { if (element instanceof PsiExpressionList) return; if (element instanceof PsiIdentifier) { if (sb.length() > 0) sb.append("."); sb.append(element.getText()); } super.visitElement(element); } }); return sb.toString(); } return null; } public ConcurrentMap<PsiElement, Object> getCacheMap(final boolean overflow) { return map; //return PsiManager.getInstance(project).getCachedValuesManager().getCachedValue(project, COMPUTED_MAP_KEY, PROVIDER, false); } }); } @Nullable private Object calcSubstituted(final PsiModifierListOwner owner) { final PsiAnnotation annotation = AnnotationUtil.findAnnotation(owner, myConfiguration.getSubstAnnotationPair().second); if (annotation != null) { return AnnotationUtilEx.calcAnnotationValue(annotation, "value"); } return null; } /** * Computes the value for the passed expression. * * @param e The expression whose value to compute * @param nonConstant list that returns non-constant and non-substituted expressions * @return the computed value, or null if the expression isn't compile time constant and not susbtituted */ @Nullable public static String computeExpression(@NotNull final PsiExpression e, @Nullable List<PsiExpression> nonConstant) { final Object result = new SubstitutedExpressionEvaluationHelper(e.getProject()).computeExpression(e, false, nonConstant); return result == null? null : String.valueOf(result); } }
plugins/IntelliLang/src/org/intellij/plugins/intelliLang/util/SubstitutedExpressionEvaluationHelper.java
/* * Copyright 2006 Sascha Weinreuter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.intelliLang.util; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInspection.dataFlow.DfaUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.util.CachedValue; import com.intellij.util.containers.ConcurrentHashMap; import org.intellij.plugins.intelliLang.Configuration; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; import java.util.concurrent.ConcurrentMap; /** * Computes the constant value of an expression while considering the substitution annotation for non-compile-time * constant expressions. * <p/> * This is a quite simplified implementation at the moment. */ public class SubstitutedExpressionEvaluationHelper { private static final Key<CachedValue<ConcurrentMap<PsiElement, Object>>> COMPUTED_MAP_KEY = Key.create("COMPUTED_MAP_KEY"); private final PsiConstantEvaluationHelper myHelper; private final Configuration myConfiguration; public SubstitutedExpressionEvaluationHelper(final Project project) { myHelper = JavaPsiFacade.getInstance(project).getConstantEvaluationHelper(); myConfiguration = Configuration.getInstance(); } public Object computeExpression(final PsiExpression e, final boolean includeUncomputablesAsLiterals) { return computeExpression(e, includeUncomputablesAsLiterals, null); } public Object computeExpression(final PsiExpression e, final boolean includeUncomputablesAsLiterals, final List<PsiExpression> uncomputables) { final ConcurrentMap<PsiElement, Object> map = new ConcurrentHashMap<PsiElement, Object>(); //if (true) return myHelper.computeConstantExpression(e, false); return myHelper.computeExpression(e, false, new PsiConstantEvaluationHelper.AuxEvaluator() { @Nullable public Object computeExpression(final PsiExpression o, final PsiConstantEvaluationHelper.AuxEvaluator auxEvaluator) { if (o instanceof PsiMethodCallExpression) { final PsiMethodCallExpression c = (PsiMethodCallExpression)o; final PsiMethod m = (PsiMethod)c.getMethodExpression().resolve(); final PsiType returnType = m != null? m.getReturnType() : null; if (returnType != null && returnType != PsiType.VOID) { // find substitution final Object substituted = calcSubstituted(m); if (substituted != null) return substituted; //return returnType.getCanonicalText().equals(CommonClassNames.JAVA_LANG_STRING)? "\""+ o.getText()+"\"" : o.getText(); } } else if (o instanceof PsiReferenceExpression) { final PsiElement resolved = ((PsiReferenceExpression)o).resolve(); if (resolved instanceof PsiModifierListOwner) { // find substitution final Object substituted = calcSubstituted((PsiModifierListOwner)resolved); if (substituted != null) return substituted; if (resolved instanceof PsiVariable) { final Collection<PsiExpression> values = DfaUtil.getCachedVariableValues(((PsiVariable)resolved), o); // return the first computed value as far as we do not support multiple injection for (PsiExpression value : values) { final Object computedValue = auxEvaluator.computeExpression(value, this); if (computedValue != null) { return computedValue; } } } } } if (uncomputables != null) uncomputables.add(o); if (includeUncomputablesAsLiterals) { final PsiExpression expression = o instanceof PsiMethodCallExpression ? ((PsiMethodCallExpression)o).getMethodExpression() : o; final String text = expression.getText().replaceAll("\\s", ""); return "\"" + StringUtil.escapeStringCharacters(text) + "\""; } return null; } public ConcurrentMap<PsiElement, Object> getCacheMap(final boolean overflow) { return map; //return PsiManager.getInstance(project).getCachedValuesManager().getCachedValue(project, COMPUTED_MAP_KEY, PROVIDER, false); } }); } @Nullable private Object calcSubstituted(final PsiModifierListOwner owner) { final PsiAnnotation annotation = AnnotationUtil.findAnnotation(owner, myConfiguration.getSubstAnnotationPair().second); if (annotation != null) { return AnnotationUtilEx.calcAnnotationValue(annotation, "value"); } return null; } /** * Computes the value for the passed expression. * * @param e The expression whose value to compute * @param nonConstant list that returns non-constant and non-substituted expressions * @return the computed value, or null if the expression isn't compile time constant and not susbtituted */ @Nullable public static String computeExpression(@NotNull final PsiExpression e, @Nullable List<PsiExpression> nonConstant) { final Object result = new SubstitutedExpressionEvaluationHelper(e.getProject()).computeExpression(e, false, nonConstant); return result == null? null : String.valueOf(result); } }
more precise magic constant computation (IDEADEV-41161)
plugins/IntelliLang/src/org/intellij/plugins/intelliLang/util/SubstitutedExpressionEvaluationHelper.java
more precise magic constant computation (IDEADEV-41161)
Java
apache-2.0
0f4dbc1bb57f0e3323a6b3312a5cc702e04b1ece
0
ZUGFeRD/mustangproject,ZUGFeRD/mustangproject,ZUGFeRD/mustangproject
package org.mustangproject.toecount; /*** * This is the command line interface to mustangproject * */ import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.mustangproject.ZUGFeRD.ZUGFeRDExporter; import org.mustangproject.ZUGFeRD.ZUGFeRDExporterFromA1Factory; import org.mustangproject.ZUGFeRD.ZUGFeRDExporterFromA3Factory; import org.mustangproject.ZUGFeRD.ZUGFeRDImporter; import org.mustangproject.ZUGFeRD.ZUGFeRDMigrator; import com.sanityinc.jargs.CmdLineParser; import com.sanityinc.jargs.CmdLineParser.Option; public class Toecount { // build with: /opt/local/bin/mvn clean compile assembly:single private static void printUsage() { System.err.println(getUsage()); } private static String getUsage() { return "Usage: [-d,--directory] [-l,--listfromstdin] [-i,--ignorefileextension] | [-c,--combine] | [-e,--extract] | [-u,--upgrade] | [-a,--a3only] | [-h,--help]\r\n"; } private static void printHelp() { System.out.println("Mustangproject.org " + org.mustangproject.ZUGFeRD.Version.VERSION + " \r\n" + "A Apache Public License library and command line tool for statistics on PDF invoices with\r\n" + "ZUGFeRD Metadata (http://www.zugferd.org)\r\n" + "\r\n" + getUsage() + "Count operations" + "\t--directory= count ZUGFeRD files in directory to be scanned\r\n" + "\t\tIf it is a directory, it will recurse.\r\n" + "\t--listfromstdin=count ZUGFeRD files from a list of linefeed separated files on runtime.\r\n" + "\t\tIt will start once a blank line has been entered.\r\n" + "\t--ignorefileextension=if PDF files are counted check *.* instead of *.pdf files" + "Merge operations" + "\t--combine= combine XML and PDF file to ZUGFeRD PDF file\r\n" + "\t--extract= extract ZUGFeRD PDF to XML file\r\n" + "\t--upgrade= upgrade ZUGFeRD XML to ZUGFeRD 2 XML\r\n" + "\t--a3only= upgrade from PDF/A1 to A3 only (no ZUGFeRD data attached) \r\n" ); } /*** * Asks the user for a String (offering a defaultValue) conforming to a Regex * pattern * * @param prompt * @param defaultValue * @param pattern * @return * @throws Exception */ protected static String getStringFromUser(String prompt, String defaultValue, String pattern) throws Exception { String input = ""; if (!defaultValue.matches(pattern)) { throw new Exception("Default value must match pattern"); } boolean firstInput = true; do { // for a more sophisticated dialogue maybe https://github.com/mabe02/lanterna/ // could be taken into account System.out.print(prompt + " (default: " + defaultValue + ")"); if (!firstInput) { System.out.print("\n(allowed pattern: " + pattern + ")"); } System.out.print(":"); BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); try { input = buffer.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (input.isEmpty()) { // pressed return without entering anything input = defaultValue; } firstInput = false; } while (!input.matches(pattern)); return input; } /*** * Prompts the user for a input or output filename * @param prompt * @param defaultFilename * @param expectedExtension will warn if filename does not match expected file extension * @param ensureFileExists will warn if file does NOT exist (for input files) * @param ensureFileNotExists will warn if file DOES exist (for output files) * * @return String */ protected static String getFilenameFromUser(String prompt, String defaultFilename, String expectedExtension, boolean ensureFileExists, boolean ensureFileNotExists) { boolean fileExistenceOK = false; String selectedName = ""; do { // for a more sophisticated dialogue maybe https://github.com/mabe02/lanterna/ could be taken into account System.out.print(prompt + " (default: " + defaultFilename + "):"); BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in)); try { selectedName=buffer.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (selectedName.isEmpty()) { // pressed return without entering anything selectedName = defaultFilename; } // error cases if (!selectedName.toLowerCase().endsWith(expectedExtension.toLowerCase())) { System.err.println("Expected "+expectedExtension+" extension, this may corrupt your file. Do you still want to continue?(Y|N)"); String selectedAnswer=""; try { selectedAnswer=buffer.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (!selectedAnswer.equals("Y")&&!selectedAnswer.equals("y")) { System.err.println("Aborted by user"); System.exit(-1); } } else if (ensureFileExists) { File f = new File(selectedName); if (f.exists()) { fileExistenceOK = true; } else { System.out.println("File does not exist, try again or CTRL+C to cancel"); // discard the input, a scanner.reset is not sufficient fileExistenceOK = false; } } else { fileExistenceOK=true; if (ensureFileNotExists) { File f = new File(selectedName); if (f.exists()) { fileExistenceOK = false; System.out.println("Output file already exists, try again or CTRL+C to cancel"); // discard the input, a scanner.reset is not sufficient } } else { fileExistenceOK=true; } } } while (!fileExistenceOK); return selectedName; } // /opt/local/bin/mvn clean compile assembly:single public static void main(String[] args) { CmdLineParser parser = new CmdLineParser(); Option<String> dirnameOption = parser.addStringOption('d', "directory"); Option<Boolean> filesFromStdInOption = parser.addBooleanOption('l', "listfromstdin"); Option<Boolean> ignoreFileExtOption = parser.addBooleanOption('i', "ignorefileextension"); Option<Boolean> combineOption = parser.addBooleanOption('c', "combine"); Option<Boolean> extractOption = parser.addBooleanOption('e', "extract"); Option<Boolean> helpOption = parser.addBooleanOption('h', "help"); Option<Boolean> upgradeOption = parser.addBooleanOption('u', "upgrade"); Option<Boolean> a3onlyOption = parser.addBooleanOption('a', "a3only"); try { parser.parse(args); } catch (CmdLineParser.OptionException e) { System.err.println(e.getMessage()); printUsage(); System.exit(2); } String directoryName = parser.getOptionValue(dirnameOption); Boolean filesFromStdIn = parser.getOptionValue(filesFromStdInOption, Boolean.FALSE); Boolean combineRequested = parser.getOptionValue(combineOption, Boolean.FALSE); Boolean extractRequested = parser.getOptionValue(extractOption, Boolean.FALSE); Boolean helpRequested = parser.getOptionValue(helpOption, Boolean.FALSE); Boolean upgradeRequested = parser.getOptionValue(upgradeOption, Boolean.FALSE); Boolean ignoreFileExt = parser.getOptionValue(ignoreFileExtOption, Boolean.FALSE); Boolean a3only = parser.getOptionValue(a3onlyOption, Boolean.FALSE); if (helpRequested) { printHelp(); } else if (((directoryName != null) && (directoryName.length() > 0)) || filesFromStdIn.booleanValue()) { StatRun sr = new StatRun(); if (ignoreFileExt) { sr.ignoreFileExtension(); } if (directoryName != null) { Path startingDir = Paths.get(directoryName); if (Files.isRegularFile(startingDir)) { String filename = startingDir.toString(); FileChecker fc = new FileChecker(filename, sr); fc.checkForZUGFeRD(); System.out.print(fc.getOutputLine()); } else if (Files.isDirectory(startingDir)) { FileTraverser pf = new FileTraverser(sr); try { Files.walkFileTree(startingDir, pf); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if (filesFromStdIn) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s; try { while ((s = in.readLine()) != null && s.length() != 0) { FileChecker fc = new FileChecker(s, sr); fc.checkForZUGFeRD(); System.out.print(fc.getOutputLine()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(sr.getSummaryLine()); } else if (combineRequested) { /* * ZUGFeRDExporter ze= new ZUGFeRDExporterFromA1Factory() * .setProducer("toecount") .setCreator(System.getProperty("user.name")) * .loadFromPDFA1("invoice.pdf"); */ String pdfName = ""; String xmlName = ""; String outName = ""; try { pdfName = getFilenameFromUser("Source PDF", "invoice.pdf", "pdf", true, false); xmlName = getFilenameFromUser("ZUGFeRD XML", "ZUGFeRD-invoice.xml", "xml", true, false); outName = getFilenameFromUser("Ouput PDF", "invoice.ZUGFeRD.pdf", "pdf", false, true); String versionInput = ""; try { versionInput = getStringFromUser("ZUGFeRD version", "1", "1|2"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // get version // get profile ZUGFeRDExporter ze = new ZUGFeRDExporterFromA3Factory().setProducer("Toecount") .setCreator(System.getProperty("user.name")).load(pdfName); ze.setZUGFeRDVersion(Integer.valueOf(versionInput)); ze.setZUGFeRDXMLData(Files.readAllBytes(Paths.get(xmlName))); ze.export(outName); } catch (IOException e) { e.printStackTrace(); // } catch (JAXBException e) { // e.printStackTrace(); } System.out.println("Written to " + outName); } else if (extractRequested) { ZUGFeRDImporter zi = new ZUGFeRDImporter(); String pdfName = getFilenameFromUser("Source PDF", "invoice.pdf", "pdf", true, false); String xmlName = getFilenameFromUser("ZUGFeRD XML", "ZUGFeRD-invoice.xml", "xml", false, true); zi.extract(pdfName); try { Files.write(Paths.get(xmlName), zi.getRawXML()); } catch (IOException e) { e.printStackTrace(); } System.out.println("Written to " + xmlName); } else if (a3only) { /* * ZUGFeRDExporter ze= new ZUGFeRDExporterFromA1Factory() * .setProducer("toecount") .setCreator(System.getProperty("user.name")) * .loadFromPDFA1("invoice.pdf"); */ String pdfName = ""; String outName = ""; try { pdfName = getFilenameFromUser("Source PDF", "invoice.pdf", "pdf", true, false); outName = getFilenameFromUser("Target PDF", "invoice.a3.pdf", "pdf", false, true); ZUGFeRDExporter ze = new ZUGFeRDExporterFromA1Factory().setAttachZUGFeRDHeaders(false).load(pdfName); ze.export(outName); } catch (IOException e) { e.printStackTrace(); } System.out.println("Written to " + outName); } else if (upgradeRequested) { String xmlName = ""; String outName = ""; try { xmlName = getFilenameFromUser("ZUGFeRD 1.0 XML source", "ZUGFeRD-invoice.xml", "xml", true, false); outName = getFilenameFromUser("ZUGFeRD 2.0 XML target", "ZUGFeRD-2-invoice.xml", "xml", false, true); ZUGFeRDMigrator zmi = new ZUGFeRDMigrator(); String xml = zmi.migrateFromV1ToV2(xmlName); Files.write(Paths.get(outName), xml.getBytes()); } catch (IOException e) { e.printStackTrace(); } System.out.println("Written to " + outName); } else { // no argument or argument unknown printUsage(); System.exit(2); } } }
src/main/java/org/mustangproject/toecount/Toecount.java
package org.mustangproject.toecount; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.regex.Pattern; import javax.xml.bind.JAXBException; import javax.xml.transform.TransformerException; import org.mustangproject.ZUGFeRD.ZUGFeRDExporter; import org.mustangproject.ZUGFeRD.ZUGFeRDExporterFromA1Factory; import org.mustangproject.ZUGFeRD.ZUGFeRDExporterFromA3Factory; import org.mustangproject.ZUGFeRD.ZUGFeRDImporter; import org.mustangproject.ZUGFeRD.ZUGFeRDMigrator; import com.sanityinc.jargs.CmdLineParser; import com.sanityinc.jargs.CmdLineParser.Option; public class Toecount { // build with: /opt/local/bin/mvn clean compile assembly:single private static void printUsage() { System.err.println(getUsage()); } private static String getUsage() { return "Usage: [-d,--directory] [-l,--listfromstdin] [-i,--ignorefileextension] | [-c,--combine] | [-e,--extract] | [-u,--upgrade] | [-a,--a3only] | [-h,--help]\r\n"; } private static void printHelp() { System.out.println("Mustangproject.org "+ org.mustangproject.ZUGFeRD.Version.VERSION + " \r\n" + "A Apache Public License library and command line tool for statistics on PDF invoices with\r\n" + "ZUGFeRD Metadata (http://www.zugferd.org)\r\n" + "\r\n" + getUsage() + "Count operations" + "\t--directory= count ZUGFeRD files in directory to be scanned\r\n" + "\t\tIf it is a directory, it will recurse.\r\n" + "\t--listfromstdin=count ZUGFeRD files from a list of linefeed separated files on runtime.\r\n" + "\t\tIt will start once a blank line has been entered.\r\n" + "\t--ignorefileextension=if PDF files are counted check *.* instead of *.pdf files" + "Merge operations" + "\t--combine= combine XML and PDF file to ZUGFeRD PDF file\r\n" + "\t--extract= extract ZUGFeRD PDF to XML file\r\n" + "\t--upgrade= upgrade ZUGFeRD XML to ZUGFeRD 2 XML\r\n" + "\t--a3only= upgrade from PDF/A1 to A3 only \r\n" ); } /*** * Prompts the user for a input or output filename * @param prompt * @param defaultFilename * @param expectedExtension will warn if filename does not match expected file extension * @param ensureFileExists will warn if file does NOT exist (for input files) * @param ensureFileNotExists will warn if file DOES exist (for output files) * * @return String */ protected static String getFilenameFromUser(String prompt, String defaultFilename, String expectedExtension, boolean ensureFileExists, boolean ensureFileNotExists) { boolean fileExistenceOK = false; String selectedName = ""; do { // for a more sophisticated dialogue maybe https://github.com/mabe02/lanterna/ could be taken into account System.out.print(prompt + " (default: " + defaultFilename + "):"); BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in)); try { selectedName=buffer.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (selectedName.isEmpty()) { // pressed return without entering anything selectedName = defaultFilename; } if (!selectedName.toLowerCase().endsWith(expectedExtension.toLowerCase())) { System.err.println("Expected "+expectedExtension+" extension, this may corrupt your file. Do you still want to continue?(Y|N)"); String selectedAnswer=""; try { selectedAnswer=buffer.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (!selectedAnswer.equals("Y")&&!selectedAnswer.equals("y")) { System.err.println("Aborted by user"); System.exit(-1); } } if (ensureFileExists) { File f = new File(selectedName); if (f.exists()) { fileExistenceOK = true; } else { System.out.println("File does not exist, try again or CTRL+C to cancel"); // discard the input, a scanner.reset is not sufficient } } else { fileExistenceOK=true; } if (ensureFileNotExists) { File f = new File(selectedName); if (f.exists()) { fileExistenceOK = false; System.out.println("Output file already exists, try again or CTRL+C to cancel"); // discard the input, a scanner.reset is not sufficient } } else { fileExistenceOK=true; } } while (!fileExistenceOK); return selectedName; } // /opt/local/bin/mvn clean compile assembly:single public static void main(String[] args) { CmdLineParser parser = new CmdLineParser(); Option<String> dirnameOption = parser.addStringOption('d', "directory"); Option<Boolean> filesFromStdInOption = parser.addBooleanOption('l', "listfromstdin"); Option<Boolean> ignoreFileExtOption = parser.addBooleanOption('i', "ignorefileextension"); Option<Boolean> combineOption = parser.addBooleanOption('c', "combine"); Option<Boolean> extractOption = parser.addBooleanOption('e', "extract"); Option<Boolean> helpOption = parser.addBooleanOption('h', "help"); Option<Boolean> upgradeOption = parser.addBooleanOption('u', "upgrade"); Option<Boolean> a3onlyOption = parser.addBooleanOption('a', "a3only"); try { parser.parse(args); } catch (CmdLineParser.OptionException e) { System.err.println(e.getMessage()); printUsage(); System.exit(2); } String directoryName = parser.getOptionValue(dirnameOption); Boolean filesFromStdIn = parser.getOptionValue(filesFromStdInOption, Boolean.FALSE); Boolean combineRequested = parser.getOptionValue(combineOption, Boolean.FALSE); Boolean extractRequested = parser.getOptionValue(extractOption, Boolean.FALSE); Boolean helpRequested = parser.getOptionValue(helpOption, Boolean.FALSE); Boolean upgradeRequested = parser.getOptionValue(upgradeOption, Boolean.FALSE); Boolean ignoreFileExt = parser.getOptionValue(ignoreFileExtOption, Boolean.FALSE); Boolean a3only = parser.getOptionValue(a3onlyOption, Boolean.FALSE); if (helpRequested) { printHelp(); } else if (((directoryName != null) && (directoryName.length() > 0)) || filesFromStdIn.booleanValue()) { StatRun sr = new StatRun(); if (ignoreFileExt) { sr.ignoreFileExtension(); } if (directoryName != null) { Path startingDir = Paths.get(directoryName); if (Files.isRegularFile(startingDir)) { String filename = startingDir.toString(); FileChecker fc = new FileChecker(filename, sr); fc.checkForZUGFeRD(); System.out.print(fc.getOutputLine()); } else if (Files.isDirectory(startingDir)) { FileTraverser pf = new FileTraverser(sr); try { Files.walkFileTree(startingDir, pf); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if (filesFromStdIn) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s; try { while ((s = in.readLine()) != null && s.length() != 0) { FileChecker fc = new FileChecker(s, sr); fc.checkForZUGFeRD(); System.out.print(fc.getOutputLine()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(sr.getSummaryLine()); } else if (combineRequested) { /* * ZUGFeRDExporter ze= new ZUGFeRDExporterFromA1Factory() * .setProducer("toecount") .setCreator(System.getProperty("user.name")) * .loadFromPDFA1("invoice.pdf"); */ String pdfName=""; String xmlName=""; String outName=""; try { pdfName=getFilenameFromUser("Source PDF", "invoice.pdf", "pdf", true, false); xmlName=getFilenameFromUser("ZUGFeRD XML", "ZUGFeRD-invoice.xml", "xml", true, false); outName=getFilenameFromUser("Ouput PDF", "invoice.ZUGFeRD.pdf", "pdf", false, true); ZUGFeRDExporter ze = new ZUGFeRDExporterFromA3Factory().setProducer("Toecount") .setCreator(System.getProperty("user.name")).load(pdfName); ze.setZUGFeRDXMLData(Files.readAllBytes(Paths.get(xmlName))); ze.export(outName); } catch (IOException e) { e.printStackTrace(); // } catch (JAXBException e) { // e.printStackTrace(); } System.out.println("Written to "+outName); } else if (extractRequested) { ZUGFeRDImporter zi = new ZUGFeRDImporter(); String pdfName=getFilenameFromUser("Source PDF", "invoice.pdf", "pdf", true, false); String xmlName=getFilenameFromUser("ZUGFeRD XML", "ZUGFeRD-invoice.xml", "xml", false, true); zi.extract(pdfName); try { Files.write(Paths.get(xmlName), zi.getRawXML()); } catch (IOException e) { e.printStackTrace(); } System.out.println("Written to "+xmlName); } else if (a3only) { /* * ZUGFeRDExporter ze= new ZUGFeRDExporterFromA1Factory() * .setProducer("toecount") .setCreator(System.getProperty("user.name")) * .loadFromPDFA1("invoice.pdf"); */ String pdfName=""; String outName=""; try { pdfName=getFilenameFromUser("Source PDF", "invoice.pdf", "pdf", true, false); outName=getFilenameFromUser("Target PDF", "invoice.a3.pdf", "pdf", false, true); ZUGFeRDExporter ze = new ZUGFeRDExporterFromA1Factory().setAttachZUGFeRDHeaders(false) .load(pdfName); ze.export(outName); } catch (IOException e) { e.printStackTrace(); } System.out.println("Written to "+outName); } else if (upgradeRequested) { String xmlName=""; String outName=""; try { xmlName=getFilenameFromUser("ZUGFeRD 1.0 XML source", "ZUGFeRD-invoice.xml", "xml", true, false); outName=getFilenameFromUser("ZUGFeRD 2.0 XML target", "ZUGFeRD-2-invoice.xml", "xml", false, true); ZUGFeRDMigrator zmi=new ZUGFeRDMigrator(); String xml=zmi.migrateFromV1ToV2(xmlName); Files.write(Paths.get(outName), xml.getBytes()); } catch (IOException e) { e.printStackTrace(); } System.out.println("Written to "+outName); } else { // no argument or argument unknown printUsage(); System.exit(2); } } }
corrected reattempt on nonexistent files, added version selection
src/main/java/org/mustangproject/toecount/Toecount.java
corrected reattempt on nonexistent files, added version selection
Java
apache-2.0
7ceabb478655b0a3558cbc6caab4b0386e14ce75
0
ullgren/camel,prashant2402/camel,MohammedHammam/camel,veithen/camel,dsimansk/camel,woj-i/camel,isavin/camel,objectiser/camel,jonmcewen/camel,veithen/camel,chirino/camel,hqstevenson/camel,mgyongyosi/camel,duro1/camel,jlpedrosa/camel,salikjan/camel,lburgazzoli/camel,w4tson/camel,curso007/camel,anoordover/camel,lburgazzoli/camel,borcsokj/camel,dvankleef/camel,gyc567/camel,jarst/camel,erwelch/camel,edigrid/camel,satishgummadelli/camel,w4tson/camel,stalet/camel,chirino/camel,dmvolod/camel,lowwool/camel,josefkarasek/camel,duro1/camel,jpav/camel,ullgren/camel,jameszkw/camel,mnki/camel,bdecoste/camel,lowwool/camel,DariusX/camel,royopa/camel,isavin/camel,lburgazzoli/apache-camel,mnki/camel,adessaigne/camel,lasombra/camel,nikhilvibhav/camel,snurmine/camel,dmvolod/camel,nboukhed/camel,maschmid/camel,scranton/camel,askannon/camel,sebi-hgdata/camel,Thopap/camel,gnodet/camel,lowwool/camel,davidwilliams1978/camel,tdiesler/camel,nicolaferraro/camel,joakibj/camel,aaronwalker/camel,JYBESSON/camel,askannon/camel,mgyongyosi/camel,allancth/camel,christophd/camel,ekprayas/camel,davidkarlsen/camel,yogamaha/camel,salikjan/camel,davidwilliams1978/camel,mike-kukla/camel,sabre1041/camel,yogamaha/camel,RohanHart/camel,rmarting/camel,gautric/camel,chirino/camel,jkorab/camel,driseley/camel,askannon/camel,gilfernandes/camel,dmvolod/camel,gyc567/camel,stravag/camel,askannon/camel,bhaveshdt/camel,manuelh9r/camel,satishgummadelli/camel,dmvolod/camel,davidkarlsen/camel,gautric/camel,jmandawg/camel,rparree/camel,tadayosi/camel,akhettar/camel,josefkarasek/camel,veithen/camel,gyc567/camel,YMartsynkevych/camel,logzio/camel,logzio/camel,ssharma/camel,zregvart/camel,joakibj/camel,curso007/camel,davidwilliams1978/camel,gnodet/camel,igarashitm/camel,gautric/camel,bgaudaen/camel,partis/camel,nicolaferraro/camel,haku/camel,tadayosi/camel,atoulme/camel,chirino/camel,dmvolod/camel,YoshikiHigo/camel,oalles/camel,onders86/camel,engagepoint/camel,pmoerenhout/camel,gilfernandes/camel,koscejev/camel,CandleCandle/camel,mzapletal/camel,lasombra/camel,neoramon/camel,dsimansk/camel,haku/camel,drsquidop/camel,gyc567/camel,borcsokj/camel,acartapanis/camel,johnpoth/camel,bdecoste/camel,mgyongyosi/camel,chanakaudaya/camel,tdiesler/camel,yury-vashchyla/camel,CandleCandle/camel,tarilabs/camel,sverkera/camel,punkhorn/camel-upstream,mnki/camel,pmoerenhout/camel,mzapletal/camel,snurmine/camel,ramonmaruko/camel,bgaudaen/camel,anton-k11/camel,gautric/camel,jonmcewen/camel,yury-vashchyla/camel,grange74/camel,bfitzpat/camel,tlehoux/camel,zregvart/camel,veithen/camel,pax95/camel,CodeSmell/camel,veithen/camel,YMartsynkevych/camel,skinzer/camel,borcsokj/camel,stravag/camel,acartapanis/camel,erwelch/camel,cunningt/camel,apache/camel,mgyongyosi/camel,haku/camel,NetNow/camel,ge0ffrey/camel,mcollovati/camel,JYBESSON/camel,rmarting/camel,tlehoux/camel,jamesnetherton/camel,dvankleef/camel,sverkera/camel,qst-jdc-labs/camel,nboukhed/camel,JYBESSON/camel,brreitme/camel,nikvaessen/camel,stalet/camel,DariusX/camel,koscejev/camel,zregvart/camel,borcsokj/camel,apache/camel,edigrid/camel,skinzer/camel,grgrzybek/camel,FingolfinTEK/camel,nikvaessen/camel,royopa/camel,atoulme/camel,bdecoste/camel,qst-jdc-labs/camel,tadayosi/camel,jameszkw/camel,tkopczynski/camel,coderczp/camel,tlehoux/camel,aaronwalker/camel,koscejev/camel,pkletsko/camel,yogamaha/camel,FingolfinTEK/camel,johnpoth/camel,drsquidop/camel,iweiss/camel,brreitme/camel,NickCis/camel,nikhilvibhav/camel,driseley/camel,sverkera/camel,NickCis/camel,anton-k11/camel,oscerd/camel,igarashitm/camel,dvankleef/camel,jkorab/camel,ge0ffrey/camel,oscerd/camel,yury-vashchyla/camel,anoordover/camel,haku/camel,atoulme/camel,bhaveshdt/camel,anton-k11/camel,yogamaha/camel,curso007/camel,christophd/camel,allancth/camel,mike-kukla/camel,erwelch/camel,alvinkwekel/camel,iweiss/camel,skinzer/camel,acartapanis/camel,mohanaraosv/camel,trohovsky/camel,YMartsynkevych/camel,MrCoder/camel,punkhorn/camel-upstream,royopa/camel,jpav/camel,mohanaraosv/camel,NetNow/camel,grgrzybek/camel,jkorab/camel,duro1/camel,yury-vashchyla/camel,grgrzybek/camel,pax95/camel,tlehoux/camel,igarashitm/camel,maschmid/camel,aaronwalker/camel,bgaudaen/camel,oalles/camel,prashant2402/camel,alvinkwekel/camel,haku/camel,YMartsynkevych/camel,anoordover/camel,dkhanolkar/camel,mike-kukla/camel,christophd/camel,brreitme/camel,lowwool/camel,duro1/camel,w4tson/camel,lasombra/camel,oalles/camel,grgrzybek/camel,driseley/camel,isavin/camel,pkletsko/camel,gnodet/camel,pkletsko/camel,anoordover/camel,mike-kukla/camel,mohanaraosv/camel,scranton/camel,chirino/camel,johnpoth/camel,driseley/camel,allancth/camel,jameszkw/camel,curso007/camel,anoordover/camel,jlpedrosa/camel,coderczp/camel,snurmine/camel,jamesnetherton/camel,yuruki/camel,yuruki/camel,oalles/camel,nikvaessen/camel,pax95/camel,Fabryprog/camel,sebi-hgdata/camel,snurmine/camel,aaronwalker/camel,lasombra/camel,pplatek/camel,ekprayas/camel,CandleCandle/camel,CodeSmell/camel,erwelch/camel,askannon/camel,arnaud-deprez/camel,qst-jdc-labs/camel,RohanHart/camel,jollygeorge/camel,CodeSmell/camel,tarilabs/camel,neoramon/camel,MohammedHammam/camel,tdiesler/camel,FingolfinTEK/camel,rparree/camel,lburgazzoli/camel,nboukhed/camel,sverkera/camel,FingolfinTEK/camel,adessaigne/camel,snadakuduru/camel,yuruki/camel,skinzer/camel,dpocock/camel,pkletsko/camel,YMartsynkevych/camel,curso007/camel,nikvaessen/camel,arnaud-deprez/camel,lasombra/camel,stalet/camel,duro1/camel,snadakuduru/camel,davidwilliams1978/camel,Thopap/camel,arnaud-deprez/camel,logzio/camel,yogamaha/camel,jonmcewen/camel,lburgazzoli/camel,jlpedrosa/camel,jkorab/camel,erwelch/camel,pplatek/camel,dpocock/camel,mzapletal/camel,rmarting/camel,jpav/camel,davidkarlsen/camel,hqstevenson/camel,pkletsko/camel,qst-jdc-labs/camel,gyc567/camel,royopa/camel,nicolaferraro/camel,ullgren/camel,tadayosi/camel,sabre1041/camel,noelo/camel,joakibj/camel,trohovsky/camel,manuelh9r/camel,johnpoth/camel,edigrid/camel,johnpoth/camel,tdiesler/camel,nikhilvibhav/camel,trohovsky/camel,rparree/camel,driseley/camel,MrCoder/camel,YoshikiHigo/camel,lburgazzoli/apache-camel,isavin/camel,jonmcewen/camel,jonmcewen/camel,edigrid/camel,NetNow/camel,mohanaraosv/camel,pax95/camel,akhettar/camel,atoulme/camel,bhaveshdt/camel,gnodet/camel,dsimansk/camel,sebi-hgdata/camel,tkopczynski/camel,engagepoint/camel,tarilabs/camel,w4tson/camel,grange74/camel,lowwool/camel,iweiss/camel,grange74/camel,jarst/camel,rmarting/camel,lburgazzoli/apache-camel,josefkarasek/camel,grange74/camel,bfitzpat/camel,qst-jdc-labs/camel,ssharma/camel,nboukhed/camel,isavin/camel,stravag/camel,joakibj/camel,woj-i/camel,jpav/camel,jlpedrosa/camel,Fabryprog/camel,scranton/camel,jlpedrosa/camel,coderczp/camel,dpocock/camel,prashant2402/camel,dkhanolkar/camel,brreitme/camel,satishgummadelli/camel,sirlatrom/camel,oalles/camel,tadayosi/camel,logzio/camel,ekprayas/camel,joakibj/camel,dpocock/camel,onders86/camel,akhettar/camel,prashant2402/camel,allancth/camel,partis/camel,eformat/camel,noelo/camel,allancth/camel,RohanHart/camel,prashant2402/camel,scranton/camel,jonmcewen/camel,allancth/camel,YoshikiHigo/camel,mcollovati/camel,zregvart/camel,christophd/camel,Thopap/camel,bgaudaen/camel,akhettar/camel,jameszkw/camel,grgrzybek/camel,NickCis/camel,isururanawaka/camel,lburgazzoli/apache-camel,sirlatrom/camel,partis/camel,borcsokj/camel,grgrzybek/camel,woj-i/camel,drsquidop/camel,jkorab/camel,MohammedHammam/camel,jamesnetherton/camel,lburgazzoli/apache-camel,nboukhed/camel,edigrid/camel,ramonmaruko/camel,mike-kukla/camel,bfitzpat/camel,duro1/camel,dvankleef/camel,jkorab/camel,woj-i/camel,FingolfinTEK/camel,dsimansk/camel,snadakuduru/camel,jollygeorge/camel,mohanaraosv/camel,dmvolod/camel,iweiss/camel,onders86/camel,coderczp/camel,gilfernandes/camel,jollygeorge/camel,eformat/camel,chanakaudaya/camel,maschmid/camel,eformat/camel,isururanawaka/camel,bgaudaen/camel,NickCis/camel,bhaveshdt/camel,prashant2402/camel,pmoerenhout/camel,tarilabs/camel,isururanawaka/camel,eformat/camel,snurmine/camel,ssharma/camel,jarst/camel,sverkera/camel,pmoerenhout/camel,satishgummadelli/camel,edigrid/camel,joakibj/camel,mike-kukla/camel,neoramon/camel,engagepoint/camel,akhettar/camel,isururanawaka/camel,borcsokj/camel,onders86/camel,yuruki/camel,ramonmaruko/camel,jameszkw/camel,hqstevenson/camel,dkhanolkar/camel,isururanawaka/camel,jlpedrosa/camel,bgaudaen/camel,manuelh9r/camel,logzio/camel,yogamaha/camel,alvinkwekel/camel,hqstevenson/camel,koscejev/camel,NetNow/camel,sebi-hgdata/camel,arnaud-deprez/camel,tkopczynski/camel,NickCis/camel,sirlatrom/camel,curso007/camel,trohovsky/camel,YoshikiHigo/camel,ekprayas/camel,gautric/camel,oscerd/camel,rparree/camel,stalet/camel,neoramon/camel,noelo/camel,acartapanis/camel,isavin/camel,bdecoste/camel,mcollovati/camel,hqstevenson/camel,arnaud-deprez/camel,stalet/camel,christophd/camel,MohammedHammam/camel,rparree/camel,adessaigne/camel,satishgummadelli/camel,w4tson/camel,maschmid/camel,kevinearls/camel,oscerd/camel,akhettar/camel,chanakaudaya/camel,CodeSmell/camel,cunningt/camel,neoramon/camel,neoramon/camel,objectiser/camel,jamesnetherton/camel,noelo/camel,ge0ffrey/camel,eformat/camel,yuruki/camel,JYBESSON/camel,tkopczynski/camel,haku/camel,christophd/camel,rmarting/camel,sirlatrom/camel,adessaigne/camel,jollygeorge/camel,josefkarasek/camel,davidwilliams1978/camel,snadakuduru/camel,manuelh9r/camel,onders86/camel,cunningt/camel,stravag/camel,stalet/camel,yury-vashchyla/camel,cunningt/camel,chanakaudaya/camel,mcollovati/camel,stravag/camel,anton-k11/camel,ssharma/camel,igarashitm/camel,ge0ffrey/camel,kevinearls/camel,apache/camel,mnki/camel,pplatek/camel,pmoerenhout/camel,Fabryprog/camel,mgyongyosi/camel,lowwool/camel,iweiss/camel,sverkera/camel,FingolfinTEK/camel,aaronwalker/camel,RohanHart/camel,veithen/camel,jarst/camel,mzapletal/camel,tdiesler/camel,cunningt/camel,MohammedHammam/camel,sabre1041/camel,YMartsynkevych/camel,kevinearls/camel,MrCoder/camel,noelo/camel,objectiser/camel,stravag/camel,CandleCandle/camel,jmandawg/camel,NickCis/camel,acartapanis/camel,gyc567/camel,sirlatrom/camel,koscejev/camel,satishgummadelli/camel,logzio/camel,nikhilvibhav/camel,tkopczynski/camel,jpav/camel,CandleCandle/camel,YoshikiHigo/camel,kevinearls/camel,grange74/camel,johnpoth/camel,scranton/camel,NetNow/camel,engagepoint/camel,ge0ffrey/camel,gautric/camel,partis/camel,tarilabs/camel,maschmid/camel,atoulme/camel,mnki/camel,jollygeorge/camel,jmandawg/camel,erwelch/camel,apache/camel,askannon/camel,RohanHart/camel,royopa/camel,lburgazzoli/camel,arnaud-deprez/camel,chanakaudaya/camel,pplatek/camel,ekprayas/camel,apache/camel,partis/camel,rmarting/camel,chirino/camel,coderczp/camel,nikvaessen/camel,tkopczynski/camel,MohammedHammam/camel,oscerd/camel,JYBESSON/camel,sabre1041/camel,dvankleef/camel,coderczp/camel,jarst/camel,ssharma/camel,pmoerenhout/camel,mzapletal/camel,JYBESSON/camel,ge0ffrey/camel,dkhanolkar/camel,sirlatrom/camel,woj-i/camel,manuelh9r/camel,drsquidop/camel,anton-k11/camel,bfitzpat/camel,lburgazzoli/camel,drsquidop/camel,DariusX/camel,scranton/camel,DariusX/camel,ekprayas/camel,punkhorn/camel-upstream,tlehoux/camel,davidkarlsen/camel,NetNow/camel,aaronwalker/camel,nikvaessen/camel,cunningt/camel,rparree/camel,gnodet/camel,noelo/camel,tdiesler/camel,onders86/camel,sabre1041/camel,ramonmaruko/camel,koscejev/camel,pax95/camel,mnki/camel,jmandawg/camel,Thopap/camel,alvinkwekel/camel,josefkarasek/camel,atoulme/camel,bdecoste/camel,MrCoder/camel,yury-vashchyla/camel,royopa/camel,jarst/camel,kevinearls/camel,jamesnetherton/camel,kevinearls/camel,partis/camel,trohovsky/camel,Thopap/camel,mzapletal/camel,drsquidop/camel,engagepoint/camel,acartapanis/camel,grange74/camel,davidwilliams1978/camel,trohovsky/camel,ssharma/camel,objectiser/camel,woj-i/camel,jamesnetherton/camel,jmandawg/camel,tarilabs/camel,manuelh9r/camel,pax95/camel,tlehoux/camel,CandleCandle/camel,ramonmaruko/camel,eformat/camel,bhaveshdt/camel,yuruki/camel,jpav/camel,brreitme/camel,dpocock/camel,sebi-hgdata/camel,w4tson/camel,bdecoste/camel,jameszkw/camel,dpocock/camel,igarashitm/camel,bfitzpat/camel,apache/camel,brreitme/camel,ullgren/camel,qst-jdc-labs/camel,maschmid/camel,gilfernandes/camel,driseley/camel,sebi-hgdata/camel,dsimansk/camel,lasombra/camel,sabre1041/camel,snadakuduru/camel,skinzer/camel,RohanHart/camel,pplatek/camel,bfitzpat/camel,logzio/camel,mgyongyosi/camel,iweiss/camel,skinzer/camel,pplatek/camel,oalles/camel,snadakuduru/camel,mohanaraosv/camel,igarashitm/camel,snurmine/camel,gilfernandes/camel,adessaigne/camel,Fabryprog/camel,YoshikiHigo/camel,tadayosi/camel,punkhorn/camel-upstream,anoordover/camel,dvankleef/camel,jmandawg/camel,dkhanolkar/camel,nicolaferraro/camel,pplatek/camel,chanakaudaya/camel,dkhanolkar/camel,MrCoder/camel,oscerd/camel,hqstevenson/camel,adessaigne/camel,isururanawaka/camel,Thopap/camel,jollygeorge/camel,bhaveshdt/camel,lburgazzoli/apache-camel,ramonmaruko/camel,MrCoder/camel,pkletsko/camel,anton-k11/camel,gilfernandes/camel,nboukhed/camel,josefkarasek/camel,dsimansk/camel
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel; import java.security.spec.ECField; import java.util.HashMap; import java.util.Map; import org.apache.camel.impl.ServiceSupport; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.ProducerCache; /** * A client helper object (named like Spring's TransactionTemplate & JmsTemplate * et al) for working with Camel and sending {@link Message} instances in an * {@link Exchange} to an {@link Endpoint}. * * @version $Revision$ */ public class CamelTemplate<E extends Exchange> extends ServiceSupport implements ProducerTemplate<E> { private CamelContext context; private ProducerCache<E> producerCache = new ProducerCache<E>(); private boolean useEndpointCache = true; private Map<String, Endpoint<E>> endpointCache = new HashMap<String, Endpoint<E>>(); private Endpoint<E> defaultEndpoint; public CamelTemplate(CamelContext context) { this.context = context; } public CamelTemplate(CamelContext context, Endpoint defaultEndpoint) { this(context); this.defaultEndpoint = defaultEndpoint; } /** * Sends the exchange to the given endpoint * * @param endpointUri the endpoint URI to send the exchange to * @param exchange the exchange to send */ public E send(String endpointUri, E exchange) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return send(endpoint, exchange); } /** * Sends an exchange to an endpoint using a supplied * * @param endpointUri the endpoint URI to send the exchange to * @param processor the transformer used to populate the new exchange * {@link Processor} to populate the exchange */ public E send(String endpointUri, Processor processor) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return send(endpoint, processor); } /** * Sends an exchange to an endpoint using a supplied * * @param endpointUri the endpoint URI to send the exchange to * @param processor the transformer used to populate the new exchange * {@link Processor} to populate the exchange. The callback * will be called when the exchange is completed. */ public E send(String endpointUri, Processor processor, AsyncCallback callback) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return send(endpoint, processor, callback); } /** * Sends an exchange to an endpoint using a supplied * * @param endpointUri the endpoint URI to send the exchange to * @param pattern the message {@link ExchangePattern} such as * {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut} * @param processor the transformer used to populate the new exchange * {@link Processor} to populate the exchange */ public E send(String endpointUri, ExchangePattern pattern, Processor processor) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return send(endpoint, pattern, processor); } /** * Sends the exchange to the given endpoint * * @param endpoint the endpoint to send the exchange to * @param exchange the exchange to send */ public E send(Endpoint<E> endpoint, E exchange) { //E convertedExchange = endpoint.createExchange(exchange); E convertedExchange = exchange; producerCache.send(endpoint, convertedExchange); return convertedExchange; } /** * Sends an exchange to an endpoint using a supplied * * @param endpoint the endpoint to send the exchange to * @param processor the transformer used to populate the new exchange * {@link Processor} to populate the exchange */ public E send(Endpoint<E> endpoint, Processor processor) { return producerCache.send(endpoint, processor); } /** * Sends an exchange to an endpoint using a supplied * * @param endpoint the endpoint to send the exchange to * @param processor the transformer used to populate the new exchange * {@link Processor} to populate the exchange. The callback * will be called when the exchange is completed. */ public E send(Endpoint<E> endpoint, Processor processor, AsyncCallback callback) { return producerCache.send(endpoint, processor, callback); } /** * Sends an exchange to an endpoint using a supplied * * @param endpoint the endpoint to send the exchange to * @param pattern the message {@link ExchangePattern} such as * {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut} * @param processor the transformer used to populate the new exchange * {@link Processor} to populate the exchange */ public E send(Endpoint<E> endpoint, ExchangePattern pattern, Processor processor) { return producerCache.send(endpoint, pattern, processor); } /** * Send the body to an endpoint with the given {@link ExchangePattern} * returning any result output body * * @param endpoint * @param body = the payload * @param pattern the message {@link ExchangePattern} such as * {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut} * @return the result */ public Object sendBody(Endpoint<E> endpoint, ExchangePattern pattern, Object body) { E result = send(endpoint, pattern, createSetBodyProcessor(body)); return extractResultBody(result); } /** * Send the body to an endpoint returning any result output body * * @param endpoint * @param body = the payload * @return the result */ public Object sendBody(Endpoint<E> endpoint, Object body) { E result = send(endpoint, createSetBodyProcessor(body)); return extractResultBody(result); } /** * Send the body to an endpoint * * @param endpointUri * @param body = the payload * @return the result */ public Object sendBody(String endpointUri, Object body) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return sendBody(endpoint, body); } /** * Send the body to an endpoint * * @param endpointUri * @param pattern the message {@link ExchangePattern} such as * {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut} * @param body = the payload * @return the result */ public Object sendBody(String endpointUri, ExchangePattern pattern, Object body) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return sendBody(endpoint, pattern, body); } /** * Sends the body to an endpoint with a specified header and header value * * @param endpointUri the endpoint URI to send to * @param body the payload send * @param header the header name * @param headerValue the header value * @return the result */ public Object sendBodyAndHeader(String endpointUri, final Object body, final String header, final Object headerValue) { return sendBodyAndHeader(resolveMandatoryEndpoint(endpointUri), body, header, headerValue); } /** * Sends the body to an endpoint with a specified header and header value * * @param endpoint the Endpoint to send to * @param body the payload send * @param header the header name * @param headerValue the header value * @return the result */ public Object sendBodyAndHeader(Endpoint endpoint, final Object body, final String header, final Object headerValue) { E result = send(endpoint, createBodyAndHeaderProcessor(body, header, headerValue)); return extractResultBody(result); } /** * Sends the body to an endpoint with a specified header and header value * * @param endpoint the Endpoint to send to * @param pattern the message {@link ExchangePattern} such as * {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut} * @param body the payload send * @param header the header name * @param headerValue the header value * @return the result */ public Object sendBodyAndHeader(Endpoint endpoint, ExchangePattern pattern, final Object body, final String header, final Object headerValue) { E result = send(endpoint, pattern, createBodyAndHeaderProcessor(body, header, headerValue)); return extractResultBody(result); } /** * Sends the body to an endpoint with a specified header and header value * * @param endpoint the Endpoint URI to send to * @param pattern the message {@link ExchangePattern} such as * {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut} * @param body the payload send * @param header the header name * @param headerValue the header value * @return the result */ public Object sendBodyAndHeader(String endpoint, ExchangePattern pattern, final Object body, final String header, final Object headerValue) { E result = send(endpoint, pattern, createBodyAndHeaderProcessor(body, header, headerValue)); return extractResultBody(result); } /** * Sends the body to an endpoint with the specified headers and header * values * * @param endpointUri the endpoint URI to send to * @param body the payload send * @return the result */ public Object sendBodyAndHeaders(String endpointUri, final Object body, final Map<String, Object> headers) { return sendBodyAndHeaders(resolveMandatoryEndpoint(endpointUri), body, headers); } /** * Sends the body to an endpoint with the specified headers and header * values * * @param endpoint the endpoint URI to send to * @param body the payload send * @return the result */ public Object sendBodyAndHeaders(Endpoint endpoint, final Object body, final Map<String, Object> headers) { E result = send(endpoint, new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); for (Map.Entry<String, Object> header : headers.entrySet()) { in.setHeader(header.getKey(), header.getValue()); } in.setBody(body); } }); return extractResultBody(result); } // Methods using an InOut ExchangePattern // ----------------------------------------------------------------------- /** * Send the body to an endpoint returning any result output body * Uses an {@link ExchangePattern#InOut} message exchange pattern * * @param endpoint * @param processor the processor which will populate the exchange before sending * @return the result */ public E request(Endpoint<E> endpoint, Processor processor) { return send(endpoint, ExchangePattern.InOut, processor); } /** * Send the body to an endpoint returning any result output body * Uses an {@link ExchangePattern#InOut} message exchange pattern * * @param endpoint * @param body = the payload * @return the result */ public Object requestBody(Endpoint<E> endpoint, Object body) { return sendBody(endpoint, ExchangePattern.InOut, body); } /** * Send the body to an endpoint returning any result output body * Uses an {@link ExchangePattern#InOut} message exchange pattern * * @param endpoint * @param body = the payload * @param header * @param headerValue * @return the result */ public Object requestBodyAndHeader(Endpoint<E> endpoint, Object body, String header, Object headerValue) { return sendBodyAndHeader(endpoint, ExchangePattern.InOut, body, header, headerValue); } /** * Send the body to an endpoint returning any result output body * Uses an {@link ExchangePattern#InOut} message exchange pattern * * @param endpoint * @param processor the processor which will populate the exchange before sending * @return the result */ public E request(String endpoint, Processor processor) { return send(endpoint, ExchangePattern.InOut, processor); } /** * Send the body to an endpoint returning any result output body * Uses an {@link ExchangePattern#InOut} message exchange pattern * * @param endpoint * @param body = the payload * @return the result */ public Object requestBody(String endpoint, Object body) { return sendBody(endpoint, ExchangePattern.InOut, body); } /** * Send the body to an endpoint returning any result output body * Uses an {@link ExchangePattern#InOut} message exchange pattern * * @param endpoint * @param body = the payload * @param header * @param headerValue * @return the result */ public Object requestBodyAndHeader(String endpoint, Object body, String header, Object headerValue) { return sendBodyAndHeader(endpoint, ExchangePattern.InOut, body, header, headerValue); } // Methods using the default endpoint // ----------------------------------------------------------------------- /** * Sends the body to the default endpoint and returns the result content * * @param body the body to send * @return the returned message body */ public Object sendBody(Object body) { return sendBody(getMandatoryDefaultEndpoint(), body); } /** * Sends the exchange to the default endpoint * * @param exchange the exchange to send */ public E send(E exchange) { return send(getMandatoryDefaultEndpoint(), exchange); } /** * Sends an exchange to the default endpoint using a supplied * * @param processor the transformer used to populate the new exchange * {@link Processor} to populate the exchange */ public E send(Processor processor) { return send(getMandatoryDefaultEndpoint(), processor); } /** * Sends an {@link ExchangePattern#InOnly} exchange to the default endpoint using the supplied body, header and header value * @param body the message body * @param header the message header * @param headerValue the message header value */ public Object sendBodyAndHeader(Object body, String header, Object headerValue) { return sendBodyAndHeader(getMandatoryDefaultEndpoint(), body, header, headerValue); } /** * Sends an {@link ExchangePattern#InOnly} exchange to the default endpoint * @param body the message body * @param headers a map with header values */ public Object sendBodyAndHeaders(Object body, Map<String, Object> headers) { return sendBodyAndHeaders(getMandatoryDefaultEndpoint(), body, headers); } // Properties // ----------------------------------------------------------------------- public Producer<E> getProducer(Endpoint<E> endpoint) { return producerCache.getProducer(endpoint); } public CamelContext getContext() { return context; } public Endpoint<E> getDefaultEndpoint() { return defaultEndpoint; } public void setDefaultEndpoint(Endpoint<E> defaultEndpoint) { this.defaultEndpoint = defaultEndpoint; } /** * Sets the default endpoint to use if none is specified */ public void setDefaultEndpointUri(String endpointUri) { setDefaultEndpoint(getContext().getEndpoint(endpointUri)); } public boolean isUseEndpointCache() { return useEndpointCache; } public void setUseEndpointCache(boolean useEndpointCache) { this.useEndpointCache = useEndpointCache; } public <T extends Endpoint<?>> T getResolvedEndpoint(String endpointUri, Class<T> expectedClass) { Endpoint<?> e = null; synchronized (endpointCache) { e = endpointCache.get(endpointUri); } if (e != null && expectedClass.isAssignableFrom(e.getClass())) { return expectedClass.asSubclass(expectedClass).cast(e); } return null; } // Implementation methods // ----------------------------------------------------------------------- protected Processor createBodyAndHeaderProcessor(final Object body, final String header, final Object headerValue) { return new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setHeader(header, headerValue); in.setBody(body); } }; } protected Processor createSetBodyProcessor(final Object body) { return new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setBody(body); } }; } protected Endpoint resolveMandatoryEndpoint(String endpointUri) { Endpoint endpoint = null; if (isUseEndpointCache()) { synchronized (endpointCache) { endpoint = endpointCache.get(endpointUri); if (endpoint == null) { endpoint = context.getEndpoint(endpointUri); if (endpoint != null) { endpointCache.put(endpointUri, endpoint); } } } } else { endpoint = context.getEndpoint(endpointUri); } if (endpoint == null) { throw new NoSuchEndpointException(endpointUri); } return endpoint; } protected Endpoint<E> getMandatoryDefaultEndpoint() { Endpoint<E> answer = getDefaultEndpoint(); ObjectHelper.notNull(answer, "defaultEndpoint"); return answer; } protected void doStart() throws Exception { producerCache.start(); } protected void doStop() throws Exception { producerCache.stop(); } protected Object extractResultBody(E result) { Object answer = null; if (result != null) { Message out = result.getOut(false); if (out != null) { answer = out.getBody(); } else { answer = result.getIn().getBody(); } } return answer; } }
camel-core/src/main/java/org/apache/camel/CamelTemplate.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel; import java.util.HashMap; import java.util.Map; import org.apache.camel.impl.ServiceSupport; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.ProducerCache; /** * A client helper object (named like Spring's TransactionTemplate & JmsTemplate * et al) for working with Camel and sending {@link Message} instances in an * {@link Exchange} to an {@link Endpoint}. * * @version $Revision$ */ public class CamelTemplate<E extends Exchange> extends ServiceSupport implements ProducerTemplate<E> { private CamelContext context; private ProducerCache<E> producerCache = new ProducerCache<E>(); private boolean useEndpointCache = true; private Map<String, Endpoint<E>> endpointCache = new HashMap<String, Endpoint<E>>(); private Endpoint<E> defaultEndpoint; public CamelTemplate(CamelContext context) { this.context = context; } public CamelTemplate(CamelContext context, Endpoint defaultEndpoint) { this(context); this.defaultEndpoint = defaultEndpoint; } /** * Sends the exchange to the given endpoint * * @param endpointUri the endpoint URI to send the exchange to * @param exchange the exchange to send */ public E send(String endpointUri, E exchange) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return send(endpoint, exchange); } /** * Sends an exchange to an endpoint using a supplied * * @param endpointUri the endpoint URI to send the exchange to * @param processor the transformer used to populate the new exchange * {@link Processor} to populate the exchange */ public E send(String endpointUri, Processor processor) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return send(endpoint, processor); } /** * Sends an exchange to an endpoint using a supplied * * @param endpointUri the endpoint URI to send the exchange to * @param processor the transformer used to populate the new exchange * {@link Processor} to populate the exchange. The callback * will be called when the exchange is completed. */ public E send(String endpointUri, Processor processor, AsyncCallback callback) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return send(endpoint, processor, callback); } /** * Sends an exchange to an endpoint using a supplied * * @param endpointUri the endpoint URI to send the exchange to * @param pattern the message {@link ExchangePattern} such as * {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut} * @param processor the transformer used to populate the new exchange * {@link Processor} to populate the exchange */ public E send(String endpointUri, ExchangePattern pattern, Processor processor) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return send(endpoint, pattern, processor); } /** * Sends the exchange to the given endpoint * * @param endpoint the endpoint to send the exchange to * @param exchange the exchange to send */ public E send(Endpoint<E> endpoint, E exchange) { //E convertedExchange = endpoint.createExchange(exchange); E convertedExchange = exchange; producerCache.send(endpoint, convertedExchange); return convertedExchange; } /** * Sends an exchange to an endpoint using a supplied * * @param endpoint the endpoint to send the exchange to * @param processor the transformer used to populate the new exchange * {@link Processor} to populate the exchange */ public E send(Endpoint<E> endpoint, Processor processor) { return producerCache.send(endpoint, processor); } /** * Sends an exchange to an endpoint using a supplied * * @param endpoint the endpoint to send the exchange to * @param processor the transformer used to populate the new exchange * {@link Processor} to populate the exchange. The callback * will be called when the exchange is completed. */ public E send(Endpoint<E> endpoint, Processor processor, AsyncCallback callback) { return producerCache.send(endpoint, processor, callback); } /** * Sends an exchange to an endpoint using a supplied * * @param endpoint the endpoint to send the exchange to * @param pattern the message {@link ExchangePattern} such as * {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut} * @param processor the transformer used to populate the new exchange * {@link Processor} to populate the exchange */ public E send(Endpoint<E> endpoint, ExchangePattern pattern, Processor processor) { return producerCache.send(endpoint, pattern, processor); } /** * Send the body to an endpoint with the given {@link ExchangePattern} * returning any result output body * * @param endpoint * @param body = the payload * @param pattern the message {@link ExchangePattern} such as * {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut} * @return the result */ public Object sendBody(Endpoint<E> endpoint, ExchangePattern pattern, Object body) { E result = send(endpoint, pattern, createSetBodyProcessor(body)); return extractResultBody(result); } /** * Send the body to an endpoint returning any result output body * * @param endpoint * @param body = the payload * @return the result */ public Object sendBody(Endpoint<E> endpoint, Object body) { E result = send(endpoint, createSetBodyProcessor(body)); return extractResultBody(result); } /** * Send the body to an endpoint * * @param endpointUri * @param body = the payload * @return the result */ public Object sendBody(String endpointUri, Object body) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return sendBody(endpoint, body); } /** * Send the body to an endpoint * * @param endpointUri * @param pattern the message {@link ExchangePattern} such as * {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut} * @param body = the payload * @return the result */ public Object sendBody(String endpointUri, ExchangePattern pattern, Object body) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return sendBody(endpoint, pattern, body); } /** * Sends the body to an endpoint with a specified header and header value * * @param endpointUri the endpoint URI to send to * @param body the payload send * @param header the header name * @param headerValue the header value * @return the result */ public Object sendBodyAndHeader(String endpointUri, final Object body, final String header, final Object headerValue) { return sendBodyAndHeader(resolveMandatoryEndpoint(endpointUri), body, header, headerValue); } /** * Sends the body to an endpoint with a specified header and header value * * @param endpoint the Endpoint to send to * @param body the payload send * @param header the header name * @param headerValue the header value * @return the result */ public Object sendBodyAndHeader(Endpoint endpoint, final Object body, final String header, final Object headerValue) { E result = send(endpoint, createBodyAndHeaderProcessor(body, header, headerValue)); return extractResultBody(result); } /** * Sends the body to an endpoint with a specified header and header value * * @param endpoint the Endpoint to send to * @param pattern the message {@link ExchangePattern} such as * {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut} * @param body the payload send * @param header the header name * @param headerValue the header value * @return the result */ public Object sendBodyAndHeader(Endpoint endpoint, ExchangePattern pattern, final Object body, final String header, final Object headerValue) { E result = send(endpoint, pattern, createBodyAndHeaderProcessor(body, header, headerValue)); return extractResultBody(result); } /** * Sends the body to an endpoint with a specified header and header value * * @param endpoint the Endpoint URI to send to * @param pattern the message {@link ExchangePattern} such as * {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut} * @param body the payload send * @param header the header name * @param headerValue the header value * @return the result */ public Object sendBodyAndHeader(String endpoint, ExchangePattern pattern, final Object body, final String header, final Object headerValue) { E result = send(endpoint, pattern, createBodyAndHeaderProcessor(body, header, headerValue)); return extractResultBody(result); } /** * Sends the body to an endpoint with the specified headers and header * values * * @param endpointUri the endpoint URI to send to * @param body the payload send * @return the result */ public Object sendBodyAndHeaders(String endpointUri, final Object body, final Map<String, Object> headers) { return sendBodyAndHeaders(resolveMandatoryEndpoint(endpointUri), body, headers); } /** * Sends the body to an endpoint with the specified headers and header * values * * @param endpoint the endpoint URI to send to * @param body the payload send * @return the result */ public Object sendBodyAndHeaders(Endpoint endpoint, final Object body, final Map<String, Object> headers) { E result = send(endpoint, new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); for (Map.Entry<String, Object> header : headers.entrySet()) { in.setHeader(header.getKey(), header.getValue()); } in.setBody(body); } }); return extractResultBody(result); } // Methods using an InOut ExchangePattern // ----------------------------------------------------------------------- /** * Send the body to an endpoint returning any result output body * * @param endpoint * @param processor the processor which will populate the exchange before sending * @return the result */ public E request(Endpoint<E> endpoint, Processor processor) { return send(endpoint, ExchangePattern.InOut, processor); } /** * Send the body to an endpoint returning any result output body * * @param endpoint * @param body = the payload * @return the result */ public Object requestBody(Endpoint<E> endpoint, Object body) { return sendBody(endpoint, ExchangePattern.InOut, body); } /** * Send the body to an endpoint returning any result output body * * @param endpoint * @param body = the payload * @param header * @param headerValue * @return the result */ public Object requestBodyAndHeader(Endpoint<E> endpoint, Object body, String header, Object headerValue) { return sendBodyAndHeader(endpoint, ExchangePattern.InOut, body, header, headerValue); } /** * Send the body to an endpoint returning any result output body * * @param endpoint * @param processor the processor which will populate the exchange before sending * @return the result */ public E request(String endpoint, Processor processor) { return send(endpoint, ExchangePattern.InOut, processor); } /** * Send the body to an endpoint returning any result output body * * @param endpoint * @param body = the payload * @return the result */ public Object requestBody(String endpoint, Object body) { return sendBody(endpoint, ExchangePattern.InOut, body); } /** * Send the body to an endpoint returning any result output body * * @param endpoint * @param body = the payload * @param header * @param headerValue * @return the result */ public Object requestBodyAndHeader(String endpoint, Object body, String header, Object headerValue) { return sendBodyAndHeader(endpoint, ExchangePattern.InOut, body, header, headerValue); } // Methods using the default endpoint // ----------------------------------------------------------------------- /** * Sends the body to the default endpoint and returns the result content * * @param body the body to send * @return the returned message body */ public Object sendBody(Object body) { return sendBody(getMandatoryDefaultEndpoint(), body); } /** * Sends the exchange to the default endpoint * * @param exchange the exchange to send */ public E send(E exchange) { return send(getMandatoryDefaultEndpoint(), exchange); } /** * Sends an exchange to the default endpoint using a supplied * * @param processor the transformer used to populate the new exchange * {@link Processor} to populate the exchange */ public E send(Processor processor) { return send(getMandatoryDefaultEndpoint(), processor); } public Object sendBodyAndHeader(Object body, String header, Object headerValue) { return sendBodyAndHeader(getMandatoryDefaultEndpoint(), body, header, headerValue); } public Object sendBodyAndHeaders(Object body, Map<String, Object> headers) { return sendBodyAndHeaders(getMandatoryDefaultEndpoint(), body, headers); } // Properties // ----------------------------------------------------------------------- public Producer<E> getProducer(Endpoint<E> endpoint) { return producerCache.getProducer(endpoint); } public CamelContext getContext() { return context; } public Endpoint<E> getDefaultEndpoint() { return defaultEndpoint; } public void setDefaultEndpoint(Endpoint<E> defaultEndpoint) { this.defaultEndpoint = defaultEndpoint; } /** * Sets the default endpoint to use if none is specified */ public void setDefaultEndpointUri(String endpointUri) { setDefaultEndpoint(getContext().getEndpoint(endpointUri)); } public boolean isUseEndpointCache() { return useEndpointCache; } public void setUseEndpointCache(boolean useEndpointCache) { this.useEndpointCache = useEndpointCache; } public <T extends Endpoint<?>> T getResolvedEndpoint(String endpointUri, Class<T> expectedClass) { Endpoint<?> e = null; synchronized (endpointCache) { e = endpointCache.get(endpointUri); } if (e != null && expectedClass.isAssignableFrom(e.getClass())) { return expectedClass.asSubclass(expectedClass).cast(e); } return null; } // Implementation methods // ----------------------------------------------------------------------- protected Processor createBodyAndHeaderProcessor(final Object body, final String header, final Object headerValue) { return new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setHeader(header, headerValue); in.setBody(body); } }; } protected Processor createSetBodyProcessor(final Object body) { return new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setBody(body); } }; } protected Endpoint resolveMandatoryEndpoint(String endpointUri) { Endpoint endpoint = null; if (isUseEndpointCache()) { synchronized (endpointCache) { endpoint = endpointCache.get(endpointUri); if (endpoint == null) { endpoint = context.getEndpoint(endpointUri); if (endpoint != null) { endpointCache.put(endpointUri, endpoint); } } } } else { endpoint = context.getEndpoint(endpointUri); } if (endpoint == null) { throw new NoSuchEndpointException(endpointUri); } return endpoint; } protected Endpoint<E> getMandatoryDefaultEndpoint() { Endpoint<E> answer = getDefaultEndpoint(); ObjectHelper.notNull(answer, "defaultEndpoint"); return answer; } protected void doStart() throws Exception { producerCache.start(); } protected void doStop() throws Exception { producerCache.stop(); } protected Object extractResultBody(E result) { Object answer = null; if (result != null) { Message out = result.getOut(false); if (out != null) { answer = out.getBody(); } else { answer = result.getIn().getBody(); } } return answer; } }
Adding a remark about the MEP being used to javadocs git-svn-id: e3ccc80b644512be24afa6caf639b2d1f1969354@658174 13f79535-47bb-0310-9956-ffa450edef68
camel-core/src/main/java/org/apache/camel/CamelTemplate.java
Adding a remark about the MEP being used to javadocs
Java
apache-2.0
6f66aa0eeaf280eeb837cbd85786b3233d940638
0
chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.broker; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import javax.jms.DeliveryMode; import javax.jms.JMSException; import junit.framework.Test; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.command.ConnectionInfo; import org.apache.activemq.command.ConsumerInfo; import org.apache.activemq.command.DestinationInfo; import org.apache.activemq.command.LocalTransactionId; import org.apache.activemq.command.Message; import org.apache.activemq.command.MessageAck; import org.apache.activemq.command.ProducerInfo; import org.apache.activemq.command.SessionInfo; public class BrokerTest extends BrokerTestSupport { public ActiveMQDestination destination; public int deliveryMode; public int prefetch; public byte destinationType; public boolean durableConsumer; public void initCombosForTestQueueOnlyOnceDeliveryWith2Consumers() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testQueueOnlyOnceDeliveryWith2Consumers() throws Exception { ActiveMQDestination destination = new ActiveMQQueue("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(1); connection1.send(consumerInfo1); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); consumerInfo2.setPrefetchSize(1); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.send(consumerInfo2); // Send the messages connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); for (int i = 0; i < 2; i++) { Message m1 = receiveMessage(connection1); Message m2 = receiveMessage(connection2); assertNotNull("m1 is null for index: " + i, m1); assertNotNull("m2 is null for index: " + i, m2); assertNotSame(m1.getMessageId(), m2.getMessageId()); connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); connection2.send(createAck(consumerInfo2, m2, 1, MessageAck.STANDARD_ACK_TYPE)); } assertNoMessagesLeft(connection1); assertNoMessagesLeft(connection2); } public void initCombosForTestQueueBrowserWith2Consumers() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testQueueBrowserWith2Consumers() throws Exception { ActiveMQDestination destination = new ActiveMQQueue("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(10); connection1.request(consumerInfo1); // Send the messages connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); // Setup a second connection with a queue browser. StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); consumerInfo2.setPrefetchSize(1); consumerInfo2.setBrowser(true); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.request(consumerInfo2); List<Message> messages = new ArrayList<Message>(); for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull("m1 is null for index: " + i, m1); messages.add(m1); } for (int i = 0; i < 4; i++) { Message m1 = messages.get(i); Message m2 = receiveMessage(connection2); assertNotNull("m2 is null for index: " + i, m2); assertEquals(m1.getMessageId(), m2.getMessageId()); connection2.send(createAck(consumerInfo2, m2, 1, MessageAck.DELIVERED_ACK_TYPE)); } assertNoMessagesLeft(connection1); assertNoMessagesLeft(connection2); } public void initCombosForTestConsumerPrefetchAndStandardAck() { addCombinationValues("deliveryMode", new Object[] { // Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testConsumerPrefetchAndStandardAck() throws Exception { // Start a producer and consumer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); consumerInfo.setPrefetchSize(1); connection.send(consumerInfo); // Send 3 messages to the broker. connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); // Make sure only 1 message was delivered. Message m1 = receiveMessage(connection); assertNotNull(m1); assertNoMessagesLeft(connection); // Acknowledge the first message. This should cause the next message to // get dispatched. connection.send(createAck(consumerInfo, m1, 1, MessageAck.STANDARD_ACK_TYPE)); Message m2 = receiveMessage(connection); assertNotNull(m2); connection.send(createAck(consumerInfo, m2, 1, MessageAck.STANDARD_ACK_TYPE)); Message m3 = receiveMessage(connection); assertNotNull(m3); connection.send(createAck(consumerInfo, m3, 1, MessageAck.STANDARD_ACK_TYPE)); connection.send(closeConnectionInfo(connectionInfo)); } public void initCombosForTestTransactedAckWithPrefetchOfOne() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testTransactedAckWithPrefetchOfOne() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); destination = createDestinationInfo(connection1, connectionInfo1, destinationType); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(1); connection1.send(consumerInfo1); // Send the messages for (int i = 0; i < 4; i++) { Message message = createMessage(producerInfo1, destination, deliveryMode); connection1.send(message); } // Begin the transaction. LocalTransactionId txid = createLocalTransaction(sessionInfo1); connection1.send(createBeginTransaction(connectionInfo1, txid)); // Now get the messages. for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); MessageAck ack = createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE); ack.setTransactionId(txid); connection1.send(ack); } // Commit the transaction. connection1.send(createCommitTransaction1Phase(connectionInfo1, txid)); assertNoMessagesLeft(connection1); } public void initCombosForTestTransactedSend() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testTransactedSend() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); destination = createDestinationInfo(connection1, connectionInfo1, destinationType); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); // Begin the transaction. LocalTransactionId txid = createLocalTransaction(sessionInfo1); connection1.send(createBeginTransaction(connectionInfo1, txid)); // Send the messages for (int i = 0; i < 4; i++) { Message message = createMessage(producerInfo1, destination, deliveryMode); message.setTransactionId(txid); connection1.send(message); } // The point of this test is that message should not be delivered until // send is committed. assertNull(receiveMessage(connection1)); // Commit the transaction. connection1.send(createCommitTransaction1Phase(connectionInfo1, txid)); // Now get the messages. for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); } assertNoMessagesLeft(connection1); } public void initCombosForTestQueueTransactedAck() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); } public void testQueueTransactedAck() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); destination = createDestinationInfo(connection1, connectionInfo1, destinationType); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); // Send the messages for (int i = 0; i < 4; i++) { Message message = createMessage(producerInfo1, destination, deliveryMode); connection1.send(message); } // Begin the transaction. LocalTransactionId txid = createLocalTransaction(sessionInfo1); connection1.send(createBeginTransaction(connectionInfo1, txid)); // Acknowledge the first 2 messages. for (int i = 0; i < 2; i++) { Message m1 = receiveMessage(connection1); assertNotNull("m1 is null for index: " + i, m1); MessageAck ack = createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE); ack.setTransactionId(txid); connection1.request(ack); } // Commit the transaction. connection1.send(createCommitTransaction1Phase(connectionInfo1, txid)); // The queue should now only have the remaining 2 messages assertEquals(2, countMessagesInQueue(connection1, connectionInfo1, destination)); } public void initCombosForTestConsumerCloseCausesRedelivery() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST")}); } public void testConsumerCloseCausesRedelivery() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(100); connection1.request(consumerInfo1); // Send the messages connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); // Receive the messages. for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull("m1 is null for index: " + i, m1); assertFalse(m1.isRedelivered()); } // Close the consumer without acking.. this should cause re-delivery of // the messages. connection1.send(consumerInfo1.createRemoveCommand()); // Create another consumer that should get the messages again. ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo1, destination); consumerInfo2.setPrefetchSize(100); connection1.request(consumerInfo2); // Receive the messages. for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull("m1 is null for index: " + i, m1); assertTrue(m1.isRedelivered()); } assertNoMessagesLeft(connection1); } public void testTopicDurableSubscriptionCanBeRestored() throws Exception { ActiveMQDestination destination = new ActiveMQTopic("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); connectionInfo1.setClientId("clientid1"); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(100); consumerInfo1.setSubscriptionName("test"); connection1.send(consumerInfo1); // Send the messages connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); // Get the messages Message m = null; for (int i = 0; i < 2; i++) { m = receiveMessage(connection1); assertNotNull(m); } // Ack the last message. connection1.send(createAck(consumerInfo1, m, 2, MessageAck.STANDARD_ACK_TYPE)); // Close the connection. connection1.request(closeConnectionInfo(connectionInfo1)); connection1.stop(); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); connectionInfo2.setClientId("clientid1"); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); consumerInfo2.setPrefetchSize(100); consumerInfo2.setSubscriptionName("test"); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.send(consumerInfo2); // Get the rest of the messages for (int i = 0; i < 2; i++) { Message m1 = receiveMessage(connection2); assertNotNull("m1 is null for index: " + i, m1); } assertNoMessagesLeft(connection2); } public void initCombosForTestGroupedMessagesDeliveredToOnlyOneConsumer() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testGroupedMessagesDeliveredToOnlyOneConsumer() throws Exception { ActiveMQDestination destination = new ActiveMQQueue("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(1); connection1.send(consumerInfo1); // Send the messages. for (int i = 0; i < 4; i++) { Message message = createMessage(producerInfo, destination, deliveryMode); message.setGroupID("TEST-GROUP"); message.setGroupSequence(i + 1); connection1.request(message); } // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); connection2.send(connectionInfo2); connection2.send(sessionInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); consumerInfo2.setPrefetchSize(1); connection2.send(consumerInfo2); // All the messages should have been sent down connection 1.. just get // the first 3 for (int i = 0; i < 3; i++) { Message m1 = receiveMessage(connection1); assertNotNull("m1 is null for index: " + i, m1); connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); } // Close the first consumer. connection1.send(closeConsumerInfo(consumerInfo1)); // The last messages should now go the the second consumer. for (int i = 0; i < 1; i++) { Message m1 = receiveMessage(connection2); assertNotNull("m1 is null for index: " + i, m1); connection2.send(createAck(consumerInfo2, m1, 1, MessageAck.STANDARD_ACK_TYPE)); } assertNoMessagesLeft(connection2); } public void initCombosForTestTopicConsumerOnlySeeMessagesAfterCreation() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("durableConsumer", new Object[] {Boolean.TRUE, Boolean.FALSE}); } public void testTopicConsumerOnlySeeMessagesAfterCreation() throws Exception { ActiveMQDestination destination = new ActiveMQTopic("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); connectionInfo1.setClientId("A"); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); // Send the 1st message connection1.send(createMessage(producerInfo1, destination, deliveryMode)); // Create the durable subscription. ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); if (durableConsumer) { consumerInfo1.setSubscriptionName("test"); } consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); Message m = createMessage(producerInfo1, destination, deliveryMode); connection1.send(m); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); // Subscription should skip over the first message Message m2 = receiveMessage(connection1); assertNotNull(m2); assertEquals(m.getMessageId(), m2.getMessageId()); m2 = receiveMessage(connection1); assertNotNull(m2); assertNoMessagesLeft(connection1); } public void initCombosForTestTopicRetroactiveConsumerSeeMessagesBeforeCreation() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("durableConsumer", new Object[] {Boolean.TRUE, Boolean.FALSE}); } public void testTopicRetroactiveConsumerSeeMessagesBeforeCreation() throws Exception { ActiveMQDestination destination = new ActiveMQTopic("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); connectionInfo1.setClientId("A"); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); // Send the messages Message m = createMessage(producerInfo1, destination, deliveryMode); connection1.send(m); // Create the durable subscription. ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); if (durableConsumer) { consumerInfo1.setSubscriptionName("test"); } consumerInfo1.setPrefetchSize(100); consumerInfo1.setRetroactive(true); connection1.send(consumerInfo1); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); // the behavior is VERY dependent on the recovery policy used. // But the default broker settings try to make it as consistent as // possible // Subscription should see all messages sent. Message m2 = receiveMessage(connection1); assertNotNull(m2); assertEquals(m.getMessageId(), m2.getMessageId()); for (int i = 0; i < 2; i++) { m2 = receiveMessage(connection1); assertNotNull(m2); } assertNoMessagesLeft(connection1); } // // TODO: need to reimplement this since we don't fail when we send to a // non-existant // destination. But if we can access the Region directly then we should be // able to // check that if the destination was removed. // // public void initCombosForTestTempDestinationsRemovedOnConnectionClose() { // addCombinationValues( "deliveryMode", new Object[]{ // Integer.valueOf(DeliveryMode.NON_PERSISTENT), // Integer.valueOf(DeliveryMode.PERSISTENT)} ); // addCombinationValues( "destinationType", new Object[]{ // Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), // Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)} ); // } // // public void testTempDestinationsRemovedOnConnectionClose() throws // Exception { // // // Setup a first connection // StubConnection connection1 = createConnection(); // ConnectionInfo connectionInfo1 = createConnectionInfo(); // SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); // ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); // connection1.send(connectionInfo1); // connection1.send(sessionInfo1); // connection1.send(producerInfo1); // // destination = createDestinationInfo(connection1, connectionInfo1, // destinationType); // // StubConnection connection2 = createConnection(); // ConnectionInfo connectionInfo2 = createConnectionInfo(); // SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); // ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); // connection2.send(connectionInfo2); // connection2.send(sessionInfo2); // connection2.send(producerInfo2); // // // Send from connection2 to connection1's temp destination. Should // succeed. // connection2.send(createMessage(producerInfo2, destination, // deliveryMode)); // // // Close connection 1 // connection1.request(closeConnectionInfo(connectionInfo1)); // // try { // // Send from connection2 to connection1's temp destination. Should not // succeed. // connection2.request(createMessage(producerInfo2, destination, // deliveryMode)); // fail("Expected JMSException."); // } catch ( JMSException success ) { // } // // } // public void initCombosForTestTempDestinationsAreNotAutoCreated() { // addCombinationValues( "deliveryMode", new Object[]{ // Integer.valueOf(DeliveryMode.NON_PERSISTENT), // Integer.valueOf(DeliveryMode.PERSISTENT)} ); // addCombinationValues( "destinationType", new Object[]{ // Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), // Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)} ); // } // // // We create temp destination on demand now so this test case is no longer // valid. // // public void testTempDestinationsAreNotAutoCreated() throws Exception { // // // Setup a first connection // StubConnection connection1 = createConnection(); // ConnectionInfo connectionInfo1 = createConnectionInfo(); // SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); // ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); // connection1.send(connectionInfo1); // connection1.send(sessionInfo1); // connection1.send(producerInfo1); // // destination = // ActiveMQDestination.createDestination(connectionInfo1.getConnectionId()+":1", // destinationType); // // // Should not be able to send to a non-existant temp destination. // try { // connection1.request(createMessage(producerInfo1, destination, // deliveryMode)); // fail("Expected JMSException."); // } catch ( JMSException success ) { // } // // } public void initCombosForTestTempDestinationsOnlyAllowsLocalConsumers() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testTempDestinationsOnlyAllowsLocalConsumers() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); DestinationInfo destinationInfo = createTempDestinationInfo(connectionInfo1, destinationType); connection1.request(destinationInfo); destination = destinationInfo.getDestination(); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); connection2.send(connectionInfo2); connection2.send(sessionInfo2); // Only consumers local to the temp destination should be allowed to // subscribe. try { ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); connection2.request(consumerInfo2); fail("Expected JMSException."); } catch (JMSException success) { } // This should succeed since it's local. ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); connection1.send(consumerInfo1); } public void initCombosForTestExclusiveQueueDeliversToOnlyOneConsumer() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testExclusiveQueueDeliversToOnlyOneConsumer() throws Exception { ActiveMQDestination destination = new ActiveMQQueue("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(1); consumerInfo1.setExclusive(true); connection1.send(consumerInfo1); // Send a message.. this should make consumer 1 the exclusive owner. connection1.request(createMessage(producerInfo, destination, deliveryMode)); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); consumerInfo2.setPrefetchSize(1); consumerInfo2.setExclusive(true); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.request(consumerInfo2); // Second message should go to consumer 1 even though consumer 2 is // ready // for dispatch. connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); // Acknowledge the first 2 messages for (int i = 0; i < 2; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); } // Close the first consumer. connection1.send(closeConsumerInfo(consumerInfo1)); // The last two messages should now go the the second consumer. connection1.send(createMessage(producerInfo, destination, deliveryMode)); for (int i = 0; i < 2; i++) { Message m1 = receiveMessage(connection2); assertNotNull(m1); connection2.send(createAck(consumerInfo2, m1, 1, MessageAck.STANDARD_ACK_TYPE)); } assertNoMessagesLeft(connection2); } public void initCombosForTestWildcardConsume() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); } public void testWildcardConsume() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); // setup the wildcard consumer. ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("WILD.*.TEST", destinationType); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, compositeDestination); consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); // These two message should NOT match the wild card. connection1.send(createMessage(producerInfo1, ActiveMQDestination.createDestination("WILD.CARD", destinationType), deliveryMode)); connection1.send(createMessage(producerInfo1, ActiveMQDestination.createDestination("WILD.TEST", destinationType), deliveryMode)); // These two message should match the wild card. ActiveMQDestination d1 = ActiveMQDestination.createDestination("WILD.CARD.TEST", destinationType); connection1.send(createMessage(producerInfo1, d1, deliveryMode)); ActiveMQDestination d2 = ActiveMQDestination.createDestination("WILD.FOO.TEST", destinationType); connection1.send(createMessage(producerInfo1, d2, deliveryMode)); Message m = receiveMessage(connection1); assertNotNull(m); //assertEquals(d1, m.getDestination()); m = receiveMessage(connection1); //assertNotNull(m); assertEquals(d2, m.getDestination()); assertNoMessagesLeft(connection1); connection1.send(closeConnectionInfo(connectionInfo1)); } public void initCombosForTestCompositeConsume() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); } public void testCompositeConsume() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); // setup the composite consumer. ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("A,B", destinationType); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, compositeDestination); consumerInfo1.setRetroactive(true); consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); // Publish to the two destinations ActiveMQDestination destinationA = ActiveMQDestination.createDestination("A", destinationType); ActiveMQDestination destinationB = ActiveMQDestination.createDestination("B", destinationType); // Send a message to each destination . connection1.send(createMessage(producerInfo1, destinationA, deliveryMode)); connection1.send(createMessage(producerInfo1, destinationB, deliveryMode)); // The consumer should get both messages. for (int i = 0; i < 2; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); } assertNoMessagesLeft(connection1); connection1.send(closeConnectionInfo(connectionInfo1)); } public void initCombosForTestCompositeSend() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); } public void testCompositeSend() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); ActiveMQDestination destinationA = ActiveMQDestination.createDestination("A", destinationType); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destinationA); consumerInfo1.setRetroactive(true); consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); connection2.send(connectionInfo2); connection2.send(sessionInfo2); ActiveMQDestination destinationB = ActiveMQDestination.createDestination("B", destinationType); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destinationB); consumerInfo2.setRetroactive(true); consumerInfo2.setPrefetchSize(100); connection2.send(consumerInfo2); // Send the messages to the composite destination. ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("A,B", destinationType); for (int i = 0; i < 4; i++) { connection1.send(createMessage(producerInfo1, compositeDestination, deliveryMode)); } // The messages should have been delivered to both the A and B // destination. for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); Message m2 = receiveMessage(connection2); assertNotNull(m1); assertNotNull(m2); assertEquals(m1.getMessageId(), m2.getMessageId()); assertEquals(compositeDestination, m1.getOriginalDestination()); assertEquals(compositeDestination, m2.getOriginalDestination()); connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); connection2.send(createAck(consumerInfo2, m2, 1, MessageAck.STANDARD_ACK_TYPE)); } assertNoMessagesLeft(connection1); assertNoMessagesLeft(connection2); connection1.send(closeConnectionInfo(connectionInfo1)); connection2.send(closeConnectionInfo(connectionInfo2)); } public void initCombosForTestConnectionCloseCascades() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST"), new ActiveMQQueue("TEST")}); } public void testConnectionCloseCascades() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(100); consumerInfo1.setNoLocal(true); connection1.request(consumerInfo1); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.send(producerInfo2); // Send the messages connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); } // Close the connection, this should in turn close the consumer. connection1.request(closeConnectionInfo(connectionInfo1)); // Send another message, connection1 should not get the message. connection2.send(createMessage(producerInfo2, destination, deliveryMode)); assertNull(connection1.getDispatchQueue().poll(maxWait, TimeUnit.MILLISECONDS)); } public void initCombosForTestSessionCloseCascades() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST"), new ActiveMQQueue("TEST")}); } public void testSessionCloseCascades() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(100); consumerInfo1.setNoLocal(true); connection1.request(consumerInfo1); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.send(producerInfo2); // Send the messages connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); } // Close the session, this should in turn close the consumer. connection1.request(closeSessionInfo(sessionInfo1)); // Send another message, connection1 should not get the message. connection2.send(createMessage(producerInfo2, destination, deliveryMode)); assertNull(connection1.getDispatchQueue().poll(maxWait, TimeUnit.MILLISECONDS)); } public void initCombosForTestConsumerClose() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST"), new ActiveMQQueue("TEST")}); } public void testConsumerClose() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(100); consumerInfo1.setNoLocal(true); connection1.request(consumerInfo1); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.send(producerInfo2); // Send the messages connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); } // Close the consumer. connection1.request(closeConsumerInfo(consumerInfo1)); // Send another message, connection1 should not get the message. connection2.send(createMessage(producerInfo2, destination, deliveryMode)); assertNull(connection1.getDispatchQueue().poll(maxWait, TimeUnit.MILLISECONDS)); } public void initCombosForTestTopicNoLocal() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testTopicNoLocal() throws Exception { ActiveMQDestination destination = new ActiveMQTopic("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setRetroactive(true); consumerInfo1.setPrefetchSize(100); consumerInfo1.setNoLocal(true); connection1.send(consumerInfo1); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.send(producerInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); consumerInfo2.setRetroactive(true); consumerInfo2.setPrefetchSize(100); consumerInfo2.setNoLocal(true); connection2.send(consumerInfo2); // Send the messages connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); // The 2nd connection should get the messages. for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection2); assertNotNull(m1); } // Send a message with the 2nd connection Message message = createMessage(producerInfo2, destination, deliveryMode); connection2.send(message); // The first connection should not see the initial 4 local messages sent // but should // see the messages from connection 2. Message m = receiveMessage(connection1); assertNotNull(m); assertEquals(message.getMessageId(), m.getMessageId()); assertNoMessagesLeft(connection1); assertNoMessagesLeft(connection2); } public void initCombosForTopicDispatchIsBroadcast() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testTopicDispatchIsBroadcast() throws Exception { ActiveMQDestination destination = new ActiveMQTopic("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setRetroactive(true); consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); consumerInfo2.setRetroactive(true); consumerInfo2.setPrefetchSize(100); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.send(consumerInfo2); // Send the messages connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); // Get the messages for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); m1 = receiveMessage(connection2); assertNotNull(m1); } } public void initCombosForTestQueueDispatchedAreRedeliveredOnConsumerClose() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); } public void testQueueDispatchedAreRedeliveredOnConsumerClose() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo); destination = createDestinationInfo(connection1, connectionInfo1, destinationType); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); // Send the messages connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); // Get the messages for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); assertFalse(m1.isRedelivered()); } // Close the consumer without sending any ACKS. connection1.send(closeConsumerInfo(consumerInfo1)); // Drain any in flight messages.. while (connection1.getDispatchQueue().poll(0, TimeUnit.MILLISECONDS) != null) { } // Add the second consumer ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo1, destination); consumerInfo2.setPrefetchSize(100); connection1.send(consumerInfo2); // Make sure the messages were re delivered to the 2nd consumer. for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); assertTrue(m1.isRedelivered()); } } public void initCombosForTestQueueBrowseMessages() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); } public void testQueueBrowseMessages() throws Exception { // Start a producer and consumer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); // Use selector to skip first message. ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); consumerInfo.setBrowser(true); connection.send(consumerInfo); for (int i = 0; i < 4; i++) { Message m = receiveMessage(connection); assertNotNull(m); connection.send(createAck(consumerInfo, m, 1, MessageAck.DELIVERED_ACK_TYPE)); } assertNoMessagesLeft(connection); } public void initCombosForTestQueueSendThenAddConsumer() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); } public void testQueueSendThenAddConsumer() throws Exception { // Start a producer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); // Send a message to the broker. connection.send(createMessage(producerInfo, destination, deliveryMode)); // Start the consumer ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); connection.send(consumerInfo); // Make sure the message was delivered. Message m = receiveMessage(connection); assertNotNull(m); } public void initCombosForTestQueueAckRemovesMessage() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); } public void testQueueAckRemovesMessage() throws Exception { // Start a producer and consumer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); Message message1 = createMessage(producerInfo, destination, deliveryMode); Message message2 = createMessage(producerInfo, destination, deliveryMode); connection.send(message1); connection.send(message2); // Make sure the message was delivered. ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); connection.request(consumerInfo); Message m = receiveMessage(connection); assertNotNull(m); assertEquals(m.getMessageId(), message1.getMessageId()); assertTrue(countMessagesInQueue(connection, connectionInfo, destination) == 2); connection.send(createAck(consumerInfo, m, 1, MessageAck.DELIVERED_ACK_TYPE)); assertTrue(countMessagesInQueue(connection, connectionInfo, destination) == 2); connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); assertTrue(countMessagesInQueue(connection, connectionInfo, destination) == 1); } public void initCombosForTestSelectorSkipsMessages() { addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST_TOPIC"), new ActiveMQQueue("TEST_QUEUE")}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testSelectorSkipsMessages() throws Exception { // Start a producer and consumer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); consumerInfo.setSelector("JMSType='last'"); connection.send(consumerInfo); Message message1 = createMessage(producerInfo, destination, deliveryMode); message1.setType("first"); Message message2 = createMessage(producerInfo, destination, deliveryMode); message2.setType("last"); connection.send(message1); connection.send(message2); // Use selector to skip first message. Message m = receiveMessage(connection); assertNotNull(m); assertEquals(m.getMessageId(), message2.getMessageId()); connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); connection.send(closeConsumerInfo(consumerInfo)); assertNoMessagesLeft(connection); } public void initCombosForTestAddConsumerThenSend() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testAddConsumerThenSend() throws Exception { // Start a producer and consumer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); connection.send(consumerInfo); connection.send(createMessage(producerInfo, destination, deliveryMode)); // Make sure the message was delivered. Message m = receiveMessage(connection); assertNotNull(m); } public void initCombosForTestConsumerPrefetchAtOne() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testConsumerPrefetchAtOne() throws Exception { // Start a producer and consumer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); consumerInfo.setPrefetchSize(1); connection.send(consumerInfo); // Send 2 messages to the broker. connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); // Make sure only 1 message was delivered. Message m = receiveMessage(connection); assertNotNull(m); assertNoMessagesLeft(connection); } public void initCombosForTestConsumerPrefetchAtTwo() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testConsumerPrefetchAtTwo() throws Exception { // Start a producer and consumer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); consumerInfo.setPrefetchSize(2); connection.send(consumerInfo); // Send 3 messages to the broker. connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); // Make sure only 1 message was delivered. Message m = receiveMessage(connection); assertNotNull(m); m = receiveMessage(connection); assertNotNull(m); assertNoMessagesLeft(connection); } public void initCombosForTestConsumerPrefetchAndDeliveredAck() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testConsumerPrefetchAndDeliveredAck() throws Exception { // Start a producer and consumer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); consumerInfo.setPrefetchSize(1); connection.send(consumerInfo); // Send 3 messages to the broker. connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); // Make sure only 1 message was delivered. Message m1 = receiveMessage(connection); assertNotNull(m1); assertNoMessagesLeft(connection); // Acknowledge the first message. This should cause the next message to // get dispatched. connection.send(createAck(consumerInfo, m1, 1, MessageAck.DELIVERED_ACK_TYPE)); Message m2 = receiveMessage(connection); assertNotNull(m2); connection.send(createAck(consumerInfo, m2, 1, MessageAck.DELIVERED_ACK_TYPE)); Message m3 = receiveMessage(connection); assertNotNull(m3); connection.send(createAck(consumerInfo, m3, 1, MessageAck.DELIVERED_ACK_TYPE)); } public static Test suite() { return suite(BrokerTest.class); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } }
activemq-core/src/test/java/org/apache/activemq/broker/BrokerTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.broker; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import javax.jms.DeliveryMode; import javax.jms.JMSException; import junit.framework.Test; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.command.ConnectionInfo; import org.apache.activemq.command.ConsumerInfo; import org.apache.activemq.command.DestinationInfo; import org.apache.activemq.command.LocalTransactionId; import org.apache.activemq.command.Message; import org.apache.activemq.command.MessageAck; import org.apache.activemq.command.ProducerInfo; import org.apache.activemq.command.SessionInfo; public class BrokerTest extends BrokerTestSupport { public ActiveMQDestination destination; public int deliveryMode; public int prefetch; public byte destinationType; public boolean durableConsumer; public void initCombosForTestQueueOnlyOnceDeliveryWith2Consumers() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testQueueOnlyOnceDeliveryWith2Consumers() throws Exception { ActiveMQDestination destination = new ActiveMQQueue("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(1); connection1.send(consumerInfo1); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); consumerInfo2.setPrefetchSize(1); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.send(consumerInfo2); // Send the messages connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); for (int i = 0; i < 2; i++) { Message m1 = receiveMessage(connection1); Message m2 = receiveMessage(connection2); assertNotNull("m1 is null for index: " + i, m1); assertNotNull("m2 is null for index: " + i, m2); assertNotSame(m1.getMessageId(), m2.getMessageId()); connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); connection2.send(createAck(consumerInfo2, m2, 1, MessageAck.STANDARD_ACK_TYPE)); } assertNoMessagesLeft(connection1); assertNoMessagesLeft(connection2); } public void initCombosForTestQueueBrowserWith2Consumers() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testQueueBrowserWith2Consumers() throws Exception { ActiveMQDestination destination = new ActiveMQQueue("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(10); connection1.request(consumerInfo1); // Send the messages connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); // Setup a second connection with a queue browser. StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); consumerInfo2.setPrefetchSize(1); consumerInfo2.setBrowser(true); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.request(consumerInfo2); List<Message> messages = new ArrayList<Message>(); for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull("m1 is null for index: " + i, m1); messages.add(m1); } for (int i = 0; i < 4; i++) { Message m1 = messages.get(i); Message m2 = receiveMessage(connection2); assertNotNull("m2 is null for index: " + i, m2); assertEquals(m1.getMessageId(), m2.getMessageId()); connection2.send(createAck(consumerInfo2, m2, 1, MessageAck.DELIVERED_ACK_TYPE)); } assertNoMessagesLeft(connection1); assertNoMessagesLeft(connection2); } public void initCombosForTestConsumerPrefetchAndStandardAck() { addCombinationValues("deliveryMode", new Object[] { // Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testConsumerPrefetchAndStandardAck() throws Exception { // Start a producer and consumer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); consumerInfo.setPrefetchSize(1); connection.send(consumerInfo); // Send 3 messages to the broker. connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); // Make sure only 1 message was delivered. Message m1 = receiveMessage(connection); assertNotNull(m1); assertNoMessagesLeft(connection); // Acknowledge the first message. This should cause the next message to // get dispatched. connection.send(createAck(consumerInfo, m1, 1, MessageAck.STANDARD_ACK_TYPE)); Message m2 = receiveMessage(connection); assertNotNull(m2); connection.send(createAck(consumerInfo, m2, 1, MessageAck.STANDARD_ACK_TYPE)); Message m3 = receiveMessage(connection); assertNotNull(m3); connection.send(createAck(consumerInfo, m3, 1, MessageAck.STANDARD_ACK_TYPE)); connection.send(closeConnectionInfo(connectionInfo)); } public void initCombosForTestTransactedAckWithPrefetchOfOne() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testTransactedAckWithPrefetchOfOne() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); destination = createDestinationInfo(connection1, connectionInfo1, destinationType); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(1); connection1.send(consumerInfo1); // Send the messages for (int i = 0; i < 4; i++) { Message message = createMessage(producerInfo1, destination, deliveryMode); connection1.send(message); } // Begin the transaction. LocalTransactionId txid = createLocalTransaction(sessionInfo1); connection1.send(createBeginTransaction(connectionInfo1, txid)); // Now get the messages. for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); MessageAck ack = createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE); ack.setTransactionId(txid); connection1.send(ack); } // Commit the transaction. connection1.send(createCommitTransaction1Phase(connectionInfo1, txid)); assertNoMessagesLeft(connection1); } public void initCombosForTestTransactedSend() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testTransactedSend() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); destination = createDestinationInfo(connection1, connectionInfo1, destinationType); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); // Begin the transaction. LocalTransactionId txid = createLocalTransaction(sessionInfo1); connection1.send(createBeginTransaction(connectionInfo1, txid)); // Send the messages for (int i = 0; i < 4; i++) { Message message = createMessage(producerInfo1, destination, deliveryMode); message.setTransactionId(txid); connection1.send(message); } // The point of this test is that message should not be delivered until // send is committed. assertNull(receiveMessage(connection1)); // Commit the transaction. connection1.send(createCommitTransaction1Phase(connectionInfo1, txid)); // Now get the messages. for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); } assertNoMessagesLeft(connection1); } public void initCombosForTestQueueTransactedAck() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); } public void testQueueTransactedAck() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); destination = createDestinationInfo(connection1, connectionInfo1, destinationType); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); // Send the messages for (int i = 0; i < 4; i++) { Message message = createMessage(producerInfo1, destination, deliveryMode); connection1.send(message); } // Begin the transaction. LocalTransactionId txid = createLocalTransaction(sessionInfo1); connection1.send(createBeginTransaction(connectionInfo1, txid)); // Acknowledge the first 2 messages. for (int i = 0; i < 2; i++) { Message m1 = receiveMessage(connection1); assertNotNull("m1 is null for index: " + i, m1); MessageAck ack = createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE); ack.setTransactionId(txid); connection1.request(ack); } // Commit the transaction. connection1.send(createCommitTransaction1Phase(connectionInfo1, txid)); // The queue should now only have the remaining 2 messages assertEquals(2, countMessagesInQueue(connection1, connectionInfo1, destination)); } public void initCombosForTestConsumerCloseCausesRedelivery() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST")}); } public void testConsumerCloseCausesRedelivery() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(100); connection1.request(consumerInfo1); // Send the messages connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); // Receive the messages. for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull("m1 is null for index: " + i, m1); assertFalse(m1.isRedelivered()); } // Close the consumer without acking.. this should cause re-delivery of // the messages. connection1.send(consumerInfo1.createRemoveCommand()); // Create another consumer that should get the messages again. ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo1, destination); consumerInfo2.setPrefetchSize(100); connection1.request(consumerInfo2); // Receive the messages. for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull("m1 is null for index: " + i, m1); assertTrue(m1.isRedelivered()); } assertNoMessagesLeft(connection1); } public void testTopicDurableSubscriptionCanBeRestored() throws Exception { ActiveMQDestination destination = new ActiveMQTopic("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); connectionInfo1.setClientId("clientid1"); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(100); consumerInfo1.setSubscriptionName("test"); connection1.send(consumerInfo1); // Send the messages connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); // Get the messages Message m = null; for (int i = 0; i < 2; i++) { m = receiveMessage(connection1); assertNotNull(m); } // Ack the last message. connection1.send(createAck(consumerInfo1, m, 2, MessageAck.STANDARD_ACK_TYPE)); // Close the connection. connection1.request(closeConnectionInfo(connectionInfo1)); connection1.stop(); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); connectionInfo2.setClientId("clientid1"); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); consumerInfo2.setPrefetchSize(100); consumerInfo2.setSubscriptionName("test"); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.send(consumerInfo2); // Get the rest of the messages for (int i = 0; i < 2; i++) { Message m1 = receiveMessage(connection2); assertNotNull("m1 is null for index: " + i, m1); } assertNoMessagesLeft(connection2); } public void initCombosForTestGroupedMessagesDeliveredToOnlyOneConsumer() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testGroupedMessagesDeliveredToOnlyOneConsumer() throws Exception { ActiveMQDestination destination = new ActiveMQQueue("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(1); connection1.send(consumerInfo1); // Send the messages. for (int i = 0; i < 4; i++) { Message message = createMessage(producerInfo, destination, deliveryMode); message.setGroupID("TEST-GROUP"); message.setGroupSequence(i + 1); connection1.request(message); } // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); connection2.send(connectionInfo2); connection2.send(sessionInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); consumerInfo2.setPrefetchSize(1); connection2.send(consumerInfo2); // All the messages should have been sent down connection 1.. just get // the first 3 for (int i = 0; i < 3; i++) { Message m1 = receiveMessage(connection1); assertNotNull("m1 is null for index: " + i, m1); connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); } // Close the first consumer. connection1.send(closeConsumerInfo(consumerInfo1)); // The last messages should now go the the second consumer. for (int i = 0; i < 1; i++) { Message m1 = receiveMessage(connection2); assertNotNull("m1 is null for index: " + i, m1); connection2.send(createAck(consumerInfo2, m1, 1, MessageAck.STANDARD_ACK_TYPE)); } assertNoMessagesLeft(connection2); } public void initCombosForTestTopicConsumerOnlySeeMessagesAfterCreation() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("durableConsumer", new Object[] {Boolean.TRUE, Boolean.FALSE}); } public void testTopicConsumerOnlySeeMessagesAfterCreation() throws Exception { ActiveMQDestination destination = new ActiveMQTopic("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); connectionInfo1.setClientId("A"); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); // Send the 1st message connection1.send(createMessage(producerInfo1, destination, deliveryMode)); // Create the durable subscription. ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); if (durableConsumer) { consumerInfo1.setSubscriptionName("test"); } consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); Message m = createMessage(producerInfo1, destination, deliveryMode); connection1.send(m); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); // Subscription should skip over the first message Message m2 = receiveMessage(connection1); assertNotNull(m2); assertEquals(m.getMessageId(), m2.getMessageId()); m2 = receiveMessage(connection1); assertNotNull(m2); assertNoMessagesLeft(connection1); } public void initCombosForTestTopicRetroactiveConsumerSeeMessagesBeforeCreation() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("durableConsumer", new Object[] {Boolean.TRUE, Boolean.FALSE}); } public void testTopicRetroactiveConsumerSeeMessagesBeforeCreation() throws Exception { ActiveMQDestination destination = new ActiveMQTopic("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); connectionInfo1.setClientId("A"); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); // Send the messages Message m = createMessage(producerInfo1, destination, deliveryMode); connection1.send(m); // Create the durable subscription. ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); if (durableConsumer) { consumerInfo1.setSubscriptionName("test"); } consumerInfo1.setPrefetchSize(100); consumerInfo1.setRetroactive(true); connection1.send(consumerInfo1); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); // the behavior is VERY dependent on the recovery policy used. // But the default broker settings try to make it as consistent as // possible // Subscription should see all messages sent. Message m2 = receiveMessage(connection1); assertNotNull(m2); assertEquals(m.getMessageId(), m2.getMessageId()); for (int i = 0; i < 2; i++) { m2 = receiveMessage(connection1); assertNotNull(m2); } assertNoMessagesLeft(connection1); } // // TODO: need to reimplement this since we don't fail when we send to a // non-existant // destination. But if we can access the Region directly then we should be // able to // check that if the destination was removed. // // public void initCombosForTestTempDestinationsRemovedOnConnectionClose() { // addCombinationValues( "deliveryMode", new Object[]{ // Integer.valueOf(DeliveryMode.NON_PERSISTENT), // Integer.valueOf(DeliveryMode.PERSISTENT)} ); // addCombinationValues( "destinationType", new Object[]{ // Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), // Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)} ); // } // // public void testTempDestinationsRemovedOnConnectionClose() throws // Exception { // // // Setup a first connection // StubConnection connection1 = createConnection(); // ConnectionInfo connectionInfo1 = createConnectionInfo(); // SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); // ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); // connection1.send(connectionInfo1); // connection1.send(sessionInfo1); // connection1.send(producerInfo1); // // destination = createDestinationInfo(connection1, connectionInfo1, // destinationType); // // StubConnection connection2 = createConnection(); // ConnectionInfo connectionInfo2 = createConnectionInfo(); // SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); // ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); // connection2.send(connectionInfo2); // connection2.send(sessionInfo2); // connection2.send(producerInfo2); // // // Send from connection2 to connection1's temp destination. Should // succeed. // connection2.send(createMessage(producerInfo2, destination, // deliveryMode)); // // // Close connection 1 // connection1.request(closeConnectionInfo(connectionInfo1)); // // try { // // Send from connection2 to connection1's temp destination. Should not // succeed. // connection2.request(createMessage(producerInfo2, destination, // deliveryMode)); // fail("Expected JMSException."); // } catch ( JMSException success ) { // } // // } // public void initCombosForTestTempDestinationsAreNotAutoCreated() { // addCombinationValues( "deliveryMode", new Object[]{ // Integer.valueOf(DeliveryMode.NON_PERSISTENT), // Integer.valueOf(DeliveryMode.PERSISTENT)} ); // addCombinationValues( "destinationType", new Object[]{ // Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), // Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)} ); // } // // // We create temp destination on demand now so this test case is no longer // valid. // // public void testTempDestinationsAreNotAutoCreated() throws Exception { // // // Setup a first connection // StubConnection connection1 = createConnection(); // ConnectionInfo connectionInfo1 = createConnectionInfo(); // SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); // ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); // connection1.send(connectionInfo1); // connection1.send(sessionInfo1); // connection1.send(producerInfo1); // // destination = // ActiveMQDestination.createDestination(connectionInfo1.getConnectionId()+":1", // destinationType); // // // Should not be able to send to a non-existant temp destination. // try { // connection1.request(createMessage(producerInfo1, destination, // deliveryMode)); // fail("Expected JMSException."); // } catch ( JMSException success ) { // } // // } public void initCombosForTestTempDestinationsOnlyAllowsLocalConsumers() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testTempDestinationsOnlyAllowsLocalConsumers() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); DestinationInfo destinationInfo = createTempDestinationInfo(connectionInfo1, destinationType); connection1.request(destinationInfo); destination = destinationInfo.getDestination(); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); connection2.send(connectionInfo2); connection2.send(sessionInfo2); // Only consumers local to the temp destination should be allowed to // subscribe. try { ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); connection2.request(consumerInfo2); fail("Expected JMSException."); } catch (JMSException success) { } // This should succeed since it's local. ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); connection1.send(consumerInfo1); } public void initCombosForTestExclusiveQueueDeliversToOnlyOneConsumer() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testExclusiveQueueDeliversToOnlyOneConsumer() throws Exception { ActiveMQDestination destination = new ActiveMQQueue("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(1); consumerInfo1.setExclusive(true); connection1.send(consumerInfo1); // Send a message.. this should make consumer 1 the exclusive owner. connection1.request(createMessage(producerInfo, destination, deliveryMode)); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); consumerInfo2.setPrefetchSize(1); consumerInfo2.setExclusive(true); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.request(consumerInfo2); // Second message should go to consumer 1 even though consumer 2 is // ready // for dispatch. connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); // Acknowledge the first 2 messages for (int i = 0; i < 2; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); } // Close the first consumer. connection1.send(closeConsumerInfo(consumerInfo1)); // The last two messages should now go the the second consumer. connection1.send(createMessage(producerInfo, destination, deliveryMode)); for (int i = 0; i < 2; i++) { Message m1 = receiveMessage(connection2); assertNotNull(m1); connection2.send(createAck(consumerInfo2, m1, 1, MessageAck.STANDARD_ACK_TYPE)); } assertNoMessagesLeft(connection2); } public void initCombosForTestWildcardConsume() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); } public void testWildcardConsume() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); // setup the wildcard consumer. ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("WILD.*.TEST", destinationType); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, compositeDestination); consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); // These two message should NOT match the wild card. connection1.send(createMessage(producerInfo1, ActiveMQDestination.createDestination("WILD.CARD", destinationType), deliveryMode)); connection1.send(createMessage(producerInfo1, ActiveMQDestination.createDestination("WILD.TEST", destinationType), deliveryMode)); // These two message should match the wild card. ActiveMQDestination d1 = ActiveMQDestination.createDestination("WILD.CARD.TEST", destinationType); connection1.send(createMessage(producerInfo1, d1, deliveryMode)); ActiveMQDestination d2 = ActiveMQDestination.createDestination("WILD.FOO.TEST", destinationType); connection1.send(createMessage(producerInfo1, d2, deliveryMode)); Message m = receiveMessage(connection1); assertNotNull(m); assertEquals(d1, m.getDestination()); m = receiveMessage(connection1); assertNotNull(m); assertEquals(d2, m.getDestination()); assertNoMessagesLeft(connection1); connection1.send(closeConnectionInfo(connectionInfo1)); } public void initCombosForTestCompositeConsume() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); } public void testCompositeConsume() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); // setup the composite consumer. ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("A,B", destinationType); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, compositeDestination); consumerInfo1.setRetroactive(true); consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); // Publish to the two destinations ActiveMQDestination destinationA = ActiveMQDestination.createDestination("A", destinationType); ActiveMQDestination destinationB = ActiveMQDestination.createDestination("B", destinationType); // Send a message to each destination . connection1.send(createMessage(producerInfo1, destinationA, deliveryMode)); connection1.send(createMessage(producerInfo1, destinationB, deliveryMode)); // The consumer should get both messages. for (int i = 0; i < 2; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); } assertNoMessagesLeft(connection1); connection1.send(closeConnectionInfo(connectionInfo1)); } public void initCombosForTestCompositeSend() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); } public void testCompositeSend() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); ActiveMQDestination destinationA = ActiveMQDestination.createDestination("A", destinationType); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destinationA); consumerInfo1.setRetroactive(true); consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); connection2.send(connectionInfo2); connection2.send(sessionInfo2); ActiveMQDestination destinationB = ActiveMQDestination.createDestination("B", destinationType); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destinationB); consumerInfo2.setRetroactive(true); consumerInfo2.setPrefetchSize(100); connection2.send(consumerInfo2); // Send the messages to the composite destination. ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("A,B", destinationType); for (int i = 0; i < 4; i++) { connection1.send(createMessage(producerInfo1, compositeDestination, deliveryMode)); } // The messages should have been delivered to both the A and B // destination. for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); Message m2 = receiveMessage(connection2); assertNotNull(m1); assertNotNull(m2); assertEquals(m1.getMessageId(), m2.getMessageId()); assertEquals(compositeDestination, m1.getOriginalDestination()); assertEquals(compositeDestination, m2.getOriginalDestination()); connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); connection2.send(createAck(consumerInfo2, m2, 1, MessageAck.STANDARD_ACK_TYPE)); } assertNoMessagesLeft(connection1); assertNoMessagesLeft(connection2); connection1.send(closeConnectionInfo(connectionInfo1)); connection2.send(closeConnectionInfo(connectionInfo2)); } public void initCombosForTestConnectionCloseCascades() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST"), new ActiveMQQueue("TEST")}); } public void testConnectionCloseCascades() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(100); consumerInfo1.setNoLocal(true); connection1.request(consumerInfo1); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.send(producerInfo2); // Send the messages connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); } // Close the connection, this should in turn close the consumer. connection1.request(closeConnectionInfo(connectionInfo1)); // Send another message, connection1 should not get the message. connection2.send(createMessage(producerInfo2, destination, deliveryMode)); assertNull(connection1.getDispatchQueue().poll(maxWait, TimeUnit.MILLISECONDS)); } public void initCombosForTestSessionCloseCascades() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST"), new ActiveMQQueue("TEST")}); } public void testSessionCloseCascades() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(100); consumerInfo1.setNoLocal(true); connection1.request(consumerInfo1); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.send(producerInfo2); // Send the messages connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); } // Close the session, this should in turn close the consumer. connection1.request(closeSessionInfo(sessionInfo1)); // Send another message, connection1 should not get the message. connection2.send(createMessage(producerInfo2, destination, deliveryMode)); assertNull(connection1.getDispatchQueue().poll(maxWait, TimeUnit.MILLISECONDS)); } public void initCombosForTestConsumerClose() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST"), new ActiveMQQueue("TEST")}); } public void testConsumerClose() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(100); consumerInfo1.setNoLocal(true); connection1.request(consumerInfo1); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.send(producerInfo2); // Send the messages connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); connection2.send(createMessage(producerInfo2, destination, deliveryMode)); for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); } // Close the consumer. connection1.request(closeConsumerInfo(consumerInfo1)); // Send another message, connection1 should not get the message. connection2.send(createMessage(producerInfo2, destination, deliveryMode)); assertNull(connection1.getDispatchQueue().poll(maxWait, TimeUnit.MILLISECONDS)); } public void initCombosForTestTopicNoLocal() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testTopicNoLocal() throws Exception { ActiveMQDestination destination = new ActiveMQTopic("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setRetroactive(true); consumerInfo1.setPrefetchSize(100); consumerInfo1.setNoLocal(true); connection1.send(consumerInfo1); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.send(producerInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); consumerInfo2.setRetroactive(true); consumerInfo2.setPrefetchSize(100); consumerInfo2.setNoLocal(true); connection2.send(consumerInfo2); // Send the messages connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); // The 2nd connection should get the messages. for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection2); assertNotNull(m1); } // Send a message with the 2nd connection Message message = createMessage(producerInfo2, destination, deliveryMode); connection2.send(message); // The first connection should not see the initial 4 local messages sent // but should // see the messages from connection 2. Message m = receiveMessage(connection1); assertNotNull(m); assertEquals(message.getMessageId(), m.getMessageId()); assertNoMessagesLeft(connection1); assertNoMessagesLeft(connection2); } public void initCombosForTopicDispatchIsBroadcast() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testTopicDispatchIsBroadcast() throws Exception { ActiveMQDestination destination = new ActiveMQTopic("TEST"); // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setRetroactive(true); consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); // Setup a second connection StubConnection connection2 = createConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); consumerInfo2.setRetroactive(true); consumerInfo2.setPrefetchSize(100); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.send(consumerInfo2); // Send the messages connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); connection1.send(createMessage(producerInfo1, destination, deliveryMode)); // Get the messages for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); m1 = receiveMessage(connection2); assertNotNull(m1); } } public void initCombosForTestQueueDispatchedAreRedeliveredOnConsumerClose() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); } public void testQueueDispatchedAreRedeliveredOnConsumerClose() throws Exception { // Setup a first connection StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.send(producerInfo); destination = createDestinationInfo(connection1, connectionInfo1, destinationType); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); // Send the messages connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); connection1.send(createMessage(producerInfo, destination, deliveryMode)); // Get the messages for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); assertFalse(m1.isRedelivered()); } // Close the consumer without sending any ACKS. connection1.send(closeConsumerInfo(consumerInfo1)); // Drain any in flight messages.. while (connection1.getDispatchQueue().poll(0, TimeUnit.MILLISECONDS) != null) { } // Add the second consumer ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo1, destination); consumerInfo2.setPrefetchSize(100); connection1.send(consumerInfo2); // Make sure the messages were re delivered to the 2nd consumer. for (int i = 0; i < 4; i++) { Message m1 = receiveMessage(connection1); assertNotNull(m1); assertTrue(m1.isRedelivered()); } } public void initCombosForTestQueueBrowseMessages() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); } public void testQueueBrowseMessages() throws Exception { // Start a producer and consumer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); // Use selector to skip first message. ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); consumerInfo.setBrowser(true); connection.send(consumerInfo); for (int i = 0; i < 4; i++) { Message m = receiveMessage(connection); assertNotNull(m); connection.send(createAck(consumerInfo, m, 1, MessageAck.DELIVERED_ACK_TYPE)); } assertNoMessagesLeft(connection); } public void initCombosForTestQueueSendThenAddConsumer() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); } public void testQueueSendThenAddConsumer() throws Exception { // Start a producer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); // Send a message to the broker. connection.send(createMessage(producerInfo, destination, deliveryMode)); // Start the consumer ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); connection.send(consumerInfo); // Make sure the message was delivered. Message m = receiveMessage(connection); assertNotNull(m); } public void initCombosForTestQueueAckRemovesMessage() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE)}); } public void testQueueAckRemovesMessage() throws Exception { // Start a producer and consumer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); Message message1 = createMessage(producerInfo, destination, deliveryMode); Message message2 = createMessage(producerInfo, destination, deliveryMode); connection.send(message1); connection.send(message2); // Make sure the message was delivered. ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); connection.request(consumerInfo); Message m = receiveMessage(connection); assertNotNull(m); assertEquals(m.getMessageId(), message1.getMessageId()); assertTrue(countMessagesInQueue(connection, connectionInfo, destination) == 2); connection.send(createAck(consumerInfo, m, 1, MessageAck.DELIVERED_ACK_TYPE)); assertTrue(countMessagesInQueue(connection, connectionInfo, destination) == 2); connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); assertTrue(countMessagesInQueue(connection, connectionInfo, destination) == 1); } public void initCombosForTestSelectorSkipsMessages() { addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST_TOPIC"), new ActiveMQQueue("TEST_QUEUE")}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testSelectorSkipsMessages() throws Exception { // Start a producer and consumer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); consumerInfo.setSelector("JMSType='last'"); connection.send(consumerInfo); Message message1 = createMessage(producerInfo, destination, deliveryMode); message1.setType("first"); Message message2 = createMessage(producerInfo, destination, deliveryMode); message2.setType("last"); connection.send(message1); connection.send(message2); // Use selector to skip first message. Message m = receiveMessage(connection); assertNotNull(m); assertEquals(m.getMessageId(), message2.getMessageId()); connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); connection.send(closeConsumerInfo(consumerInfo)); assertNoMessagesLeft(connection); } public void initCombosForTestAddConsumerThenSend() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testAddConsumerThenSend() throws Exception { // Start a producer and consumer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); connection.send(consumerInfo); connection.send(createMessage(producerInfo, destination, deliveryMode)); // Make sure the message was delivered. Message m = receiveMessage(connection); assertNotNull(m); } public void initCombosForTestConsumerPrefetchAtOne() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testConsumerPrefetchAtOne() throws Exception { // Start a producer and consumer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); consumerInfo.setPrefetchSize(1); connection.send(consumerInfo); // Send 2 messages to the broker. connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); // Make sure only 1 message was delivered. Message m = receiveMessage(connection); assertNotNull(m); assertNoMessagesLeft(connection); } public void initCombosForTestConsumerPrefetchAtTwo() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testConsumerPrefetchAtTwo() throws Exception { // Start a producer and consumer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); consumerInfo.setPrefetchSize(2); connection.send(consumerInfo); // Send 3 messages to the broker. connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); // Make sure only 1 message was delivered. Message m = receiveMessage(connection); assertNotNull(m); m = receiveMessage(connection); assertNotNull(m); assertNoMessagesLeft(connection); } public void initCombosForTestConsumerPrefetchAndDeliveredAck() { addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); } public void testConsumerPrefetchAndDeliveredAck() throws Exception { // Start a producer and consumer StubConnection connection = createConnection(); ConnectionInfo connectionInfo = createConnectionInfo(); SessionInfo sessionInfo = createSessionInfo(connectionInfo); ProducerInfo producerInfo = createProducerInfo(sessionInfo); connection.send(connectionInfo); connection.send(sessionInfo); connection.send(producerInfo); destination = createDestinationInfo(connection, connectionInfo, destinationType); ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); consumerInfo.setPrefetchSize(1); connection.send(consumerInfo); // Send 3 messages to the broker. connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); connection.send(createMessage(producerInfo, destination, deliveryMode)); // Make sure only 1 message was delivered. Message m1 = receiveMessage(connection); assertNotNull(m1); assertNoMessagesLeft(connection); // Acknowledge the first message. This should cause the next message to // get dispatched. connection.send(createAck(consumerInfo, m1, 1, MessageAck.DELIVERED_ACK_TYPE)); Message m2 = receiveMessage(connection); assertNotNull(m2); connection.send(createAck(consumerInfo, m2, 1, MessageAck.DELIVERED_ACK_TYPE)); Message m3 = receiveMessage(connection); assertNotNull(m3); connection.send(createAck(consumerInfo, m3, 1, MessageAck.DELIVERED_ACK_TYPE)); } public static Test suite() { return suite(BrokerTest.class); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } }
can't determine order messages will arrive in for separate queues git-svn-id: d2a93f579bd4835921162e9a69396c846e49961c@619390 13f79535-47bb-0310-9956-ffa450edef68
activemq-core/src/test/java/org/apache/activemq/broker/BrokerTest.java
can't determine order messages will arrive in for separate queues
Java
apache-2.0
c44795462a1434bc211faf5ef54c3bf3b79ea11f
0
phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida
package ca.corefacility.bioinformatics.irida.web.controller.test.unit.samples; import java.util.HashSet; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.springframework.ui.ModelMap; import ca.corefacility.bioinformatics.irida.model.joins.Join; import ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectSampleJoin; import ca.corefacility.bioinformatics.irida.model.project.Project; import ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField; import ca.corefacility.bioinformatics.irida.model.sample.Sample; import ca.corefacility.bioinformatics.irida.model.sample.metadata.MetadataEntry; import ca.corefacility.bioinformatics.irida.service.ProjectService; import ca.corefacility.bioinformatics.irida.service.sample.MetadataTemplateService; import ca.corefacility.bioinformatics.irida.service.sample.SampleService; import ca.corefacility.bioinformatics.irida.web.assembler.resource.ResourceCollection; import ca.corefacility.bioinformatics.irida.web.assembler.resource.sample.SampleMetadataResponse; import ca.corefacility.bioinformatics.irida.web.controller.api.RESTGenericController; import ca.corefacility.bioinformatics.irida.web.controller.api.samples.RESTSampleMetadataController; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; public class RESTSampleMetadataControllerTest { private RESTSampleMetadataController metadataController; private SampleService sampleService; private MetadataTemplateService metadataTemplateService; private ProjectService projectService; @Before public void setUp() { sampleService = mock(SampleService.class); metadataTemplateService = mock(MetadataTemplateService.class); projectService = mock(ProjectService.class); metadataController = new RESTSampleMetadataController(sampleService, metadataTemplateService, projectService); } @Test public void testReadProjectSampleMetadata() { Sample s1 = new Sample("s1"); s1.setId(1L); Sample s2 = new Sample("s2"); s2.setId(2L); Project p1 = new Project("p1"); p1.setId(3L); MetadataTemplateField f1 = new MetadataTemplateField("f1", "text"); MetadataEntry entry1 = new MetadataEntry("val1", "text", f1); MetadataEntry entry2 = new MetadataEntry("val2", "text", f1); List<Join<Project, Sample>> projectSampleJoins = Lists.newArrayList(new ProjectSampleJoin(p1, s1, true), new ProjectSampleJoin(p1, s2, true)); when(projectService.read(p1.getId())).thenReturn(p1); when(sampleService.getSamplesForProject(p1)).thenReturn(projectSampleJoins); when(sampleService.getMetadataForSample(s1)).thenReturn(Sets.newHashSet(entry1)); when(sampleService.getMetadataForSample(s2)).thenReturn(Sets.newHashSet(entry2)); ModelMap modelMap = metadataController.getProjectSampleMetadata(p1.getId()); ResourceCollection<SampleMetadataResponse> responses = (ResourceCollection) modelMap.get( RESTGenericController.RESOURCE_NAME); assertEquals(2, responses.size()); for (SampleMetadataResponse response : responses) { assertEquals(1, response.getMetadata() .size()); assertTrue(response.getMetadata() .keySet() .contains(f1)); } verify(projectService).read(p1.getId()); verify(sampleService).getSamplesForProject(p1); verify(sampleService).getMetadataForSample(s1); verify(sampleService).getMetadataForSample(s2); } @Test public void testGetSampleMetadata() { Sample s1 = new Sample("s1"); s1.setId(1L); MetadataTemplateField f1 = new MetadataTemplateField("f1", "text"); MetadataEntry entry1 = new MetadataEntry("val1", "text", f1); when(sampleService.read(s1.getId())).thenReturn(s1); when(sampleService.getMetadataForSample(s1)).thenReturn(Sets.newHashSet(entry1)); ModelMap sampleMetadata = metadataController.getSampleMetadata(s1.getId()); SampleMetadataResponse response = (SampleMetadataResponse) sampleMetadata.get( RESTGenericController.RESOURCE_NAME); verify(sampleService).getMetadataForSample(s1); Map<MetadataTemplateField, MetadataEntry> metadata = response.getMetadata(); assertTrue(metadata.containsKey(f1)); } @Test public void testAddSampleMetadata() { Sample s1 = new Sample("s1"); s1.setId(1L); MetadataTemplateField f1 = new MetadataTemplateField("f1", "text"); MetadataEntry entry1 = new MetadataEntry("val1", "text", f1); MetadataEntry entry2 = new MetadataEntry("val2", "text", f1); ImmutableMap<String, MetadataEntry> updateMap = ImmutableMap.of(f1.getLabel(), entry2); HashSet<MetadataEntry> originalSet = Sets.newHashSet(entry1); HashSet<MetadataEntry> newSet = Sets.newHashSet(entry2); when(sampleService.read(s1.getId())).thenReturn(s1); when(sampleService.getMetadataForSample(s1)).thenReturn(originalSet); when(metadataTemplateService.convertMetadataStringsToSet(updateMap)).thenReturn(newSet); metadataController.addSampleMetadata(s1.getId(), updateMap); verify(sampleService).mergeSampleMetadata(s1, newSet); } @Test public void testSaveSampleMetadata() { Sample s1 = new Sample("s1"); s1.setId(1L); MetadataTemplateField f1 = new MetadataTemplateField("f1", "text"); MetadataEntry entry1 = new MetadataEntry("val1", "text", f1); MetadataEntry entry2 = new MetadataEntry("val2", "text", f1); ImmutableMap<String, MetadataEntry> updateMap = ImmutableMap.of(f1.getLabel(), entry2); HashSet<MetadataEntry> originalSet = Sets.newHashSet(entry1); HashSet<MetadataEntry> newSet = Sets.newHashSet(entry2); when(sampleService.read(s1.getId())).thenReturn(s1); when(sampleService.getMetadataForSample(s1)).thenReturn(originalSet); when(metadataTemplateService.convertMetadataStringsToSet(updateMap)).thenReturn(newSet); metadataController.saveSampleMetadata(s1.getId(), updateMap); verify(sampleService).updateSampleMetadata(s1, newSet); } }
src/test/java/ca/corefacility/bioinformatics/irida/web/controller/test/unit/samples/RESTSampleMetadataControllerTest.java
package ca.corefacility.bioinformatics.irida.web.controller.test.unit.samples; import java.util.List; import org.junit.Before; import org.junit.Test; import org.springframework.ui.ModelMap; import ca.corefacility.bioinformatics.irida.model.joins.Join; import ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectSampleJoin; import ca.corefacility.bioinformatics.irida.model.project.Project; import ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField; import ca.corefacility.bioinformatics.irida.model.sample.Sample; import ca.corefacility.bioinformatics.irida.model.sample.metadata.MetadataEntry; import ca.corefacility.bioinformatics.irida.service.ProjectService; import ca.corefacility.bioinformatics.irida.service.sample.MetadataTemplateService; import ca.corefacility.bioinformatics.irida.service.sample.SampleService; import ca.corefacility.bioinformatics.irida.web.assembler.resource.ResourceCollection; import ca.corefacility.bioinformatics.irida.web.assembler.resource.sample.SampleMetadataResponse; import ca.corefacility.bioinformatics.irida.web.controller.api.RESTGenericController; import ca.corefacility.bioinformatics.irida.web.controller.api.samples.RESTSampleMetadataController; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; public class RESTSampleMetadataControllerTest { private RESTSampleMetadataController metadataController; private SampleService sampleService; private MetadataTemplateService metadataTemplateService; private ProjectService projectService; @Before public void setUp() { sampleService = mock(SampleService.class); metadataTemplateService = mock(MetadataTemplateService.class); projectService = mock(ProjectService.class); metadataController = new RESTSampleMetadataController(sampleService, metadataTemplateService, projectService); } @Test public void testReadProjectSampleMetadata() { Sample s1 = new Sample("s1"); s1.setId(1L); Sample s2 = new Sample("s2"); s2.setId(2L); Project p1 = new Project("p1"); p1.setId(3L); MetadataTemplateField f1 = new MetadataTemplateField("f1", "text"); MetadataEntry entry1 = new MetadataEntry("val1", "text", f1); MetadataEntry entry2 = new MetadataEntry("val1", "text", f1); List<Join<Project, Sample>> projectSampleJoins = Lists.newArrayList(new ProjectSampleJoin(p1, s1, true), new ProjectSampleJoin(p1, s2, true)); when(projectService.read(p1.getId())).thenReturn(p1); when(sampleService.getSamplesForProject(p1)).thenReturn(projectSampleJoins); when(sampleService.getMetadataForSample(s1)).thenReturn(Sets.newHashSet(entry1)); when(sampleService.getMetadataForSample(s2)).thenReturn(Sets.newHashSet(entry2)); ModelMap modelMap = metadataController.getProjectSampleMetadata(p1.getId()); ResourceCollection<SampleMetadataResponse> responses = (ResourceCollection) modelMap.get( RESTGenericController.RESOURCE_NAME); assertEquals(2, responses.size()); for (SampleMetadataResponse response : responses) { assertEquals(1, response.getMetadata() .size()); assertTrue(response.getMetadata() .keySet() .contains(f1)); } verify(projectService).read(p1.getId()); verify(sampleService).getSamplesForProject(p1); verify(sampleService).getMetadataForSample(s1); verify(sampleService).getMetadataForSample(s2); } }
added basic unit tests for all metada methods
src/test/java/ca/corefacility/bioinformatics/irida/web/controller/test/unit/samples/RESTSampleMetadataControllerTest.java
added basic unit tests for all metada methods
Java
apache-2.0
c4d91c9f2092659e7fb2b0ed0dc0191641be2508
0
rrenomeron/cas,GIP-RECIA/cas,petracvv/cas,doodelicious/cas,William-Hill-Online/cas,Unicon/cas,William-Hill-Online/cas,dodok1/cas,tduehr/cas,petracvv/cas,dodok1/cas,petracvv/cas,GIP-RECIA/cas,frett/cas,pmarasse/cas,pmarasse/cas,tduehr/cas,doodelicious/cas,dodok1/cas,prigaux/cas,pmarasse/cas,GIP-RECIA/cas,pmarasse/cas,doodelicious/cas,doodelicious/cas,William-Hill-Online/cas,robertoschwald/cas,tduehr/cas,prigaux/cas,rrenomeron/cas,Unicon/cas,frett/cas,rrenomeron/cas,frett/cas,robertoschwald/cas,prigaux/cas,frett/cas,dodok1/cas,Unicon/cas,Unicon/cas,William-Hill-Online/cas,prigaux/cas,robertoschwald/cas,tduehr/cas,Unicon/cas,rrenomeron/cas,petracvv/cas,robertoschwald/cas,GIP-RECIA/cas,rrenomeron/cas,GIP-RECIA/cas
package org.apereo.cas.configuration.support; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; import java.security.Security; import java.util.HashMap; import java.util.Map; /** * This is {@link CasConfigurationJasyptDecryptor}. * * @author Misagh Moayyed * @since 5.1.0 */ public class CasConfigurationJasyptDecryptor { private static final Logger LOGGER = LoggerFactory.getLogger(CasConfigurationJasyptDecryptor.class); private static final String ENCRYPTED_VALUE_PREFIX = "{cipher}"; private enum JasyptEncryptionParameters { ALGORITHM("cas.standalone.config.security.alg", "PBEWithMD5AndTripleDES"), PROVIDER("cas.standalone.config.security.provider", null), ITERATIONS("cas.standalone.config.security.iteration", null), PASSWORD("cas.standalone.config.security.psw", null); private String name; private String defaultValue; JasyptEncryptionParameters(final String name, final String defaultValue) { this.name = name; this.defaultValue = defaultValue; } public String getName() { return name; } public String getDefaultValue() { return defaultValue; } } private final StandardPBEStringEncryptor decryptor; public CasConfigurationJasyptDecryptor(final Environment environment) { this.decryptor = new StandardPBEStringEncryptor(); final String alg = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.ALGORITHM); if (StringUtils.isNotBlank(alg)) { LOGGER.debug("Configured decryptor algorithm", alg); decryptor.setAlgorithm(alg); } final String psw = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.PASSWORD); if (StringUtils.isNotBlank(psw)) { LOGGER.debug("Configured decryptor password"); decryptor.setPassword(psw); } final String pName = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.PROVIDER); if (StringUtils.isNotBlank(pName)) { LOGGER.debug("Configured decryptor provider"); if (StringUtils.equals(pName, BouncyCastleProvider.PROVIDER_NAME)) { Security.addProvider(new BouncyCastleProvider()); } this.decryptor.setProviderName(pName); } final String iter = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.ITERATIONS); if (StringUtils.isNotBlank(iter) && NumberUtils.isCreatable(iter)) { LOGGER.debug("Configured decryptor iterations"); decryptor.setKeyObtentionIterations(Integer.valueOf(iter)); } } private String getJasyptParamFromEnv(final Environment environment, final JasyptEncryptionParameters param) { return environment.getProperty(param.getName(), param.getDefaultValue()); } /** * Decrypt map. * * @param settings the settings * @return the map */ public Map<Object, Object> decrypt(final Map<Object, Object> settings) { final Map<Object, Object> decrypted = new HashMap<>(); settings.entrySet() .forEach(entry -> { final String stringValue = getStringPropertyValue(entry.getValue()); if (StringUtils.isNotBlank(stringValue) && stringValue.startsWith(ENCRYPTED_VALUE_PREFIX)) { try { if (!this.decryptor.isInitialized()) { this.decryptor.initialize(); } final String encValue = stringValue.substring(ENCRYPTED_VALUE_PREFIX.length()); LOGGER.debug("Decrypting property [{}]...", entry.getKey()); final String value = this.decryptor.decrypt(encValue); decrypted.put(entry.getKey(), value); } catch (final Exception e) { LOGGER.error("Could not decrypt property [{}]. Setting will be ignored by CAS", entry.getKey(), e); } } else { decrypted.put(entry.getKey(), entry.getValue()); } }); return decrypted; } /** * Retrieves the {@link String} of an {@link Object}. * * @param propertyValue The property value to cast * @return A {@link String} representing the property value or {@code null} if it is not a {@link String} */ private String getStringPropertyValue(final Object propertyValue) { return propertyValue instanceof String ? propertyValue.toString() : null; } }
core/cas-server-core-configuration/src/main/java/org/apereo/cas/configuration/support/CasConfigurationJasyptDecryptor.java
package org.apereo.cas.configuration.support; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; import java.security.Security; import java.util.HashMap; import java.util.Map; /** * This is {@link CasConfigurationJasyptDecryptor}. * * @author Misagh Moayyed * @since 5.1.0 */ public class CasConfigurationJasyptDecryptor { private static final Logger LOGGER = LoggerFactory.getLogger(CasConfigurationJasyptDecryptor.class); private static final String ENCRYPTED_VALUE_PREFIX = "{cipher}"; private enum JasyptEncryptionParameters { ALGORITHM("cas.standalone.config.security.alg", "PBEWithMD5AndTripleDES"), PROVIDER("cas.standalone.config.security.provider", null), ITERATIONS("cas.standalone.config.security.iteration", null), PASSWORD("cas.standalone.config.security.psw", null); private String name; private String defaultValue; JasyptEncryptionParameters(final String name, final String defaultValue) { this.name = name; this.defaultValue = defaultValue; } public String getName() { return name; } public String getDefaultValue() { return defaultValue; } } private final StandardPBEStringEncryptor decryptor; public CasConfigurationJasyptDecryptor(final Environment environment) { this.decryptor = new StandardPBEStringEncryptor(); final String alg = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.ALGORITHM); if (StringUtils.isNotBlank(alg)) { LOGGER.debug("Configured decryptor algorithm", alg); decryptor.setAlgorithm(alg); } final String psw = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.PASSWORD); if (StringUtils.isNotBlank(psw)) { LOGGER.debug("Configured decryptor password"); decryptor.setPassword(psw); } final String pName = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.PROVIDER); if (StringUtils.isNotBlank(pName)) { LOGGER.debug("Configured decryptor provider"); if (StringUtils.equals(pName, BouncyCastleProvider.PROVIDER_NAME)) { Security.addProvider(new BouncyCastleProvider()); } this.decryptor.setProviderName(pName); } final String iter = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.ITERATIONS); if (StringUtils.isNotBlank(iter) && NumberUtils.isCreatable(iter)) { LOGGER.debug("Configured decryptor iterations"); decryptor.setKeyObtentionIterations(Integer.valueOf(iter)); } } private String getJasyptParamFromEnv(final Environment environment, final JasyptEncryptionParameters param) { return environment.getProperty(param.getName(), param.getDefaultValue()); } /** * Decrypt map. * * @param settings the settings * @return the map */ public Map<Object, Object> decrypt(final Map<Object, Object> settings) { final Map<Object, Object> decrypted = new HashMap<>(); settings.entrySet() .forEach(entry -> { String stringValue = getStringPropertyValue(entry.getValue()); if (stringValue != null && stringValue.startsWith(ENCRYPTED_VALUE_PREFIX)) { try { if (!this.decryptor.isInitialized()) { this.decryptor.initialize(); } final String encValue = stringValue.substring(ENCRYPTED_VALUE_PREFIX.length()); LOGGER.debug("Decrypting property [{}]...", entry.getKey()); final String value = this.decryptor.decrypt(encValue); decrypted.put(entry.getKey(), value); } catch (final Exception e) { LOGGER.error("Could not decrypt property [{}]. Setting will be ignored by CAS", entry.getKey(), e); } } else { decrypted.put(entry.getKey(), entry.getValue()); } }); return decrypted; } /** * Retrieves the {@link String} of an {@link Object} * * @param propertyValue The property value to cast * @return A {@link String} representing the property value or {@code null} if it is not a {@link String} */ private String getStringPropertyValue(final Object propertyValue) { return propertyValue instanceof String ? (String) propertyValue : null; } }
Fix check style issues
core/cas-server-core-configuration/src/main/java/org/apereo/cas/configuration/support/CasConfigurationJasyptDecryptor.java
Fix check style issues
Java
apache-2.0
4f45cc6b6db9ccfde8f64be7ce612247637a459b
0
jasperstein/modeshape,okulikov/modeshape,elvisisking/modeshape,sandk07/modeshape,stemig62/modeshape,jasperstein/modeshape,sandk07/modeshape,phantomjinx/modeshape,sandk07/modeshape,hchiorean/modeshape,ModeShape/modeshape,sandk07/modeshape,Teiid-Designer/modeshape,sandk07/modeshape,weebl2000/modeshape,okulikov/modeshape,ModeShape/modeshape,rhauch/modeshape,pleacu/modeshape,pleacu/modeshape,RobSis/modeshape,elvisisking/modeshape,ModeShape/modeshape,rhauch/modeshape,data-experts/modeshape,phantomjinx/modeshape,data-experts/modeshape,hchiorean/modeshape,vhalbert/modeshape,pleacu/modeshape,stemig62/modeshape,vhalbert/modeshape,elvisisking/modeshape,RobSis/modeshape,jasperstein/modeshape,vhalbert/modeshape,mdrillin/modeshape,Teiid-Designer/modeshape,rhauch/modeshape,stemig62/modeshape,RobSis/modeshape,vhalbert/modeshape,mdrillin/modeshape,stemig62/modeshape,elvisisking/modeshape,Teiid-Designer/modeshape,okulikov/modeshape,elvisisking/modeshape,data-experts/modeshape,Teiid-Designer/modeshape,data-experts/modeshape,RobSis/modeshape,weebl2000/modeshape,rhauch/modeshape,hchiorean/modeshape,sandk07/modeshape,vhalbert/modeshape,data-experts/modeshape,jasperstein/modeshape,weebl2000/modeshape,jasperstein/modeshape,mdrillin/modeshape,mdrillin/modeshape,weebl2000/modeshape,pleacu/modeshape,phantomjinx/modeshape,weebl2000/modeshape,phantomjinx/modeshape,ModeShape/modeshape,elvisisking/modeshape,weebl2000/modeshape,phantomjinx/modeshape,vhalbert/modeshape,Teiid-Designer/modeshape,okulikov/modeshape,Teiid-Designer/modeshape,stemig62/modeshape,data-experts/modeshape,hchiorean/modeshape,mdrillin/modeshape,phantomjinx/modeshape,pleacu/modeshape,RobSis/modeshape,ModeShape/modeshape,rhauch/modeshape,pleacu/modeshape,stemig62/modeshape,ModeShape/modeshape,mdrillin/modeshape,hchiorean/modeshape,jasperstein/modeshape,RobSis/modeshape,okulikov/modeshape,okulikov/modeshape
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.example.dna.sequencers; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; import javax.jcr.Credentials; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.Property; import javax.jcr.PropertyIterator; import javax.jcr.Repository; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.SimpleCredentials; import javax.jcr.Value; import javax.jcr.observation.Event; import org.apache.jackrabbit.api.JackrabbitNodeTypeManager; import org.apache.jackrabbit.core.TransientRepository; import org.jboss.dna.common.SystemFailureException; import org.jboss.dna.repository.observation.ObservationService; import org.jboss.dna.repository.sequencers.SequencerConfig; import org.jboss.dna.repository.sequencers.SequencingService; import org.jboss.dna.repository.util.ExecutionContext; import org.jboss.dna.repository.util.JcrTools; import org.jboss.dna.repository.util.SessionFactory; import org.jboss.dna.repository.util.SimpleExecutionContext; import org.jboss.dna.repository.util.SimpleSessionFactory; /** * @author Randall Hauch */ public class SequencingClient { public static final String DEFAULT_JACKRABBIT_CONFIG_PATH = "jackrabbitConfig.xml"; public static final String DEFAULT_WORKING_DIRECTORY = "repositoryData"; public static final String DEFAULT_REPOSITORY_NAME = "repo"; public static final String DEFAULT_WORKSPACE_NAME = "default"; public static final String DEFAULT_USERNAME = "jsmith"; public static final char[] DEFAULT_PASSWORD = "secret".toCharArray(); public static void main( String[] args ) throws Exception { SequencingClient client = new SequencingClient(); client.setRepositoryInformation(DEFAULT_REPOSITORY_NAME, DEFAULT_WORKSPACE_NAME, DEFAULT_USERNAME, DEFAULT_PASSWORD); client.setUserInterface(new ConsoleInput(client)); } private String repositoryName; private String workspaceName; private String username; private char[] password; private String jackrabbitConfigPath; private String workingDirectory; private Session keepAliveSession; private Repository repository; private SequencingService sequencingService; private ObservationService observationService; private UserInterface userInterface; private ExecutionContext executionContext; public SequencingClient() { setJackrabbitConfigPath(DEFAULT_JACKRABBIT_CONFIG_PATH); setWorkingDirectory(DEFAULT_WORKING_DIRECTORY); setRepositoryInformation(DEFAULT_REPOSITORY_NAME, DEFAULT_WORKSPACE_NAME, DEFAULT_USERNAME, DEFAULT_PASSWORD); } protected void setWorkingDirectory( String workingDirectoryPath ) { this.workingDirectory = workingDirectoryPath != null ? workingDirectoryPath : DEFAULT_WORKING_DIRECTORY; } protected void setJackrabbitConfigPath( String jackrabbitConfigPath ) { this.jackrabbitConfigPath = jackrabbitConfigPath != null ? jackrabbitConfigPath : DEFAULT_JACKRABBIT_CONFIG_PATH; } protected void setRepositoryInformation( String repositoryName, String workspaceName, String username, char[] password ) { if (this.repository != null) { throw new IllegalArgumentException("Unable to set repository information when repository is already running"); } this.repositoryName = repositoryName != null ? repositoryName : DEFAULT_REPOSITORY_NAME; this.workspaceName = workspaceName != null ? workspaceName : DEFAULT_WORKSPACE_NAME; this.username = username; this.password = password; } /** * Set the user interface that this client should use. * @param userInterface */ public void setUserInterface( UserInterface userInterface ) { this.userInterface = userInterface; } /** * Start up the JCR repository. This method only operates using the JCR API and Jackrabbit-specific API. * @throws Exception */ public void startRepository() throws Exception { if (this.repository == null) { try { // Load the Jackrabbit configuration ... File configFile = new File(this.jackrabbitConfigPath); if (!configFile.exists()) { throw new SystemFailureException("The Jackrabbit configuration file cannot be found at " + configFile.getAbsoluteFile()); } if (!configFile.canRead()) { throw new SystemFailureException("Unable to read the Jackrabbit configuration file at " + configFile.getAbsoluteFile()); } String pathToConfig = configFile.getAbsolutePath(); // Find the directory where the Jackrabbit repository data will be stored ... File workingDirectory = new File(this.workingDirectory); if (workingDirectory.exists()) { if (!workingDirectory.isDirectory()) { throw new SystemFailureException("Unable to create working directory at " + workingDirectory.getAbsolutePath()); } } String workingDirectoryPath = workingDirectory.getAbsolutePath(); // Get the Jackrabbit custom node definition (CND) file ... URL cndFile = Thread.currentThread().getContextClassLoader().getResource("jackrabbitNodeTypes.cnd"); // Create the Jackrabbit repository instance and establish a session to keep the repository alive ... this.repository = new TransientRepository(pathToConfig, workingDirectoryPath); if (this.username != null) { Credentials credentials = new SimpleCredentials(this.username, this.password); this.keepAliveSession = this.repository.login(credentials, this.workspaceName); } else { this.keepAliveSession = this.repository.login(); } try { // Register the node types (only valid the first time) ... JackrabbitNodeTypeManager mgr = (JackrabbitNodeTypeManager)this.keepAliveSession.getWorkspace().getNodeTypeManager(); mgr.registerNodeTypes(cndFile.openStream(), JackrabbitNodeTypeManager.TEXT_X_JCR_CND); } catch (RepositoryException e) { if (!e.getMessage().contains("already exists")) throw e; } } catch (Exception e) { this.repository = null; this.keepAliveSession = null; throw e; } } } /** * Shutdown the repository. This method only uses the JCR API. * @throws Exception */ public void shutdownRepository() throws Exception { if (this.repository != null) { try { this.keepAliveSession.logout(); } finally { this.repository = null; this.keepAliveSession = null; } } } /** * Start the DNA services. * @throws Exception */ public void startDnaServices() throws Exception { if (this.repository == null) { this.startRepository(); } if (this.sequencingService == null) { // Create an execution context for the sequencing service. This execution context provides an environment // for the DNA services which knows about the JCR repositories, workspaces, and credentials used to // establish sessions to these workspaces. This example uses the SimpleExecutionContext, but there is // implementation for use with JCR repositories registered in JNDI. SimpleSessionFactory sessionFactory = new SimpleSessionFactory(); sessionFactory.registerRepository(this.repositoryName, this.repository); if (this.username != null) { Credentials credentials = new SimpleCredentials(this.username, this.password); sessionFactory.registerCredentials(this.repositoryName + "/" + this.workspaceName, credentials); } this.executionContext = new SimpleExecutionContext(sessionFactory); // Create the sequencing service, passing in the execution context ... this.sequencingService = new SequencingService(); this.sequencingService.setExecutionContext(executionContext); // Configure the sequencers. In this example, we only use a single sequencer that processes image files. // So create a configuration. Note that the sequencing service expects the class to be on the thread's current context // classloader, or if that's null the classloader that loaded the SequencingService class. // // Part of the configuration includes telling DNA which JCR paths should be processed by the sequencer. // These path expressions tell the service that this sequencer should be invoked on the "jcr:data" property // on the "jcr:content" child node of any node uploaded to the repository whose name ends with one of the // supported extensions, and the sequencer should place the generated output metadata in a node with the same name as // the file but immediately below the "/images" node. Path expressions can be fairly complex, and can even // specify that the generated information be placed in a different repository. // // Sequencer configurations can be added before or after the service is started, but here we do it before the service // is running. String name = "Image Sequencer"; String desc = "Sequences image files to extract the characteristics of the image"; String classname = "org.jboss.dna.sequencer.images.ImageMetadataSequencer"; String[] classpath = null; // Use the current classpath String[] pathExpressions = {"//(*.(jpg|jpeg|gif|bmp|pcx|png|iff|ras|pbm|pgm|ppm|psd))[*]/jcr:content[@jcr:data] => /images/$1"}; SequencerConfig imageSequencerConfig = new SequencerConfig(name, desc, classname, classpath, pathExpressions); this.sequencingService.addSequencer(imageSequencerConfig); // Use the DNA observation service to listen to the JCR repository (or multiple ones), and // then register the sequencing service as a listener to this observation service... this.observationService = new ObservationService(this.executionContext.getSessionFactory()); this.observationService.getAdministrator().start(); this.observationService.addListener(this.sequencingService); this.observationService.monitor(this.repositoryName + "/" + this.workspaceName, Event.NODE_ADDED | Event.PROPERTY_ADDED | Event.PROPERTY_CHANGED); } // Start up the sequencing service ... this.sequencingService.getAdministrator().start(); } /** * Shut down the DNA services. * @throws Exception */ public void shutdownDnaServices() throws Exception { if (this.sequencingService == null) return; // Shut down the service and wait until it's all shut down ... this.sequencingService.getAdministrator().shutdown(); this.sequencingService.getAdministrator().awaitTermination(5, TimeUnit.SECONDS); // Shut down the observation service ... this.observationService.getAdministrator().shutdown(); this.observationService.getAdministrator().awaitTermination(5, TimeUnit.SECONDS); } /** * Get the sequencing statistics. * @return the statistics; never null */ public SequencingService.Statistics getStatistics() { return this.sequencingService.getStatistics(); } /** * Prompt the user interface for the file to upload into the JCR repository, then upload it using the JCR API. * @throws Exception */ public void uploadFile() throws Exception { URL url = this.userInterface.getFileToUpload(); // Grab the last segment of the URL path, using it as the filename String filename = url.getPath().replaceAll("([^/]*/)*", ""); String nodePath = this.userInterface.getRepositoryPath("/a/b/" + filename); String mimeType = getMimeType(url); // Now use the JCR API to upload the file ... Session session = createSession(); JcrTools tools = this.executionContext.getTools(); try { // Create the node at the supplied path ... Node node = tools.findOrCreateNode(session, nodePath, "nt:folder", "nt:file"); // Upload the file to that node ... Node contentNode = tools.findOrCreateChild(session, node, "jcr:content", "nt:resource"); contentNode.setProperty("jcr:mimeType", mimeType); contentNode.setProperty("jcr:lastModified", Calendar.getInstance()); contentNode.setProperty("jcr:data", url.openStream()); // Save the session ... session.save(); } finally { session.logout(); } } /** * Perform a search of the repository for all image metadata automatically created by the image sequencer. * @throws Exception */ public void search() throws Exception { // Use JCR to search the repository for image metadata ... List<ImageInfo> images = new ArrayList<ImageInfo>(); Session session = createSession(); try { // Find the image node ... Node root = session.getRootNode(); if (root.hasNode("images")) { Node imagesNode = root.getNode("images"); // Iterate over each child ... for (NodeIterator iter = imagesNode.getNodes(); iter.hasNext();) { Node imageNode = iter.nextNode(); String nodePath = imageNode.getPath(); String nodeName = imageNode.getName(); if (imageNode.hasNode("image:metadata")) { imageNode = imageNode.getNode("image:metadata"); // Create a Properties object containing the properties for this node; ignore any children ... Properties props = new Properties(); for (PropertyIterator propertyIter = imageNode.getProperties(); propertyIter.hasNext();) { Property property = propertyIter.nextProperty(); String name = property.getName(); String stringValue = null; if (property.getDefinition().isMultiple()) { StringBuilder sb = new StringBuilder(); boolean first = true; for (Value value : property.getValues()) { if (!first) { sb.append(", "); first = false; } sb.append(value.getString()); } stringValue = sb.toString(); } else { stringValue = property.getValue().getString(); } props.put(name, stringValue); } // Create the image information object, and add it to the collection ... ImageInfo info = new ImageInfo(nodePath, nodeName, props); images.add(info); } } } } finally { session.logout(); } // Display the search results ... this.userInterface.displaySearchResults(images); } /** * Utility method to create a new JCR session from the execution context's {@link SessionFactory}. * @return the session * @throws RepositoryException */ protected Session createSession() throws RepositoryException { return this.executionContext.getSessionFactory().createSession(this.repositoryName + "/" + this.workspaceName); } protected String getMimeType( URL file ) { String filename = file.getPath().toLowerCase(); if (filename.endsWith(".gif")) return "image/gif"; if (filename.endsWith(".png")) return "image/png"; if (filename.endsWith(".pict")) return "image/x-pict"; if (filename.endsWith(".bmp")) return "image/bmp"; if (filename.endsWith(".jpg")) return "image/jpeg"; if (filename.endsWith(".jpe")) return "image/jpeg"; if (filename.endsWith(".jpeg")) return "image/jpeg"; if (filename.endsWith(".ras")) return "image/x-cmu-raster"; throw new SystemFailureException("Unknown mime type for " + file); } }
docs/examples/gettingstarted/sequencers/src/main/java/org/jboss/example/dna/sequencers/SequencingClient.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.example.dna.sequencers; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; import javax.jcr.Credentials; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.Property; import javax.jcr.PropertyIterator; import javax.jcr.Repository; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.SimpleCredentials; import javax.jcr.Value; import javax.jcr.observation.Event; import org.apache.jackrabbit.api.JackrabbitNodeTypeManager; import org.apache.jackrabbit.core.TransientRepository; import org.jboss.dna.common.SystemFailureException; import org.jboss.dna.repository.observation.ObservationService; import org.jboss.dna.repository.sequencers.SequencerConfig; import org.jboss.dna.repository.sequencers.SequencingService; import org.jboss.dna.repository.util.ExecutionContext; import org.jboss.dna.repository.util.JcrTools; import org.jboss.dna.repository.util.SessionFactory; import org.jboss.dna.repository.util.SimpleExecutionContext; /** * @author Randall Hauch */ public class SequencingClient { public static final String DEFAULT_JACKRABBIT_CONFIG_PATH = "jackrabbitConfig.xml"; public static final String DEFAULT_WORKING_DIRECTORY = "repositoryData"; public static final String DEFAULT_REPOSITORY_NAME = "repo"; public static final String DEFAULT_WORKSPACE_NAME = "default"; public static final String DEFAULT_USERNAME = "jsmith"; public static final char[] DEFAULT_PASSWORD = "secret".toCharArray(); public static void main( String[] args ) throws Exception { SequencingClient client = new SequencingClient(); client.setRepositoryInformation(DEFAULT_REPOSITORY_NAME, DEFAULT_WORKSPACE_NAME, "jsmith", "secret".toCharArray()); client.setUserInterface(new ConsoleInput(client)); } private String repositoryName; private String workspaceName; private String username; private char[] password; private String jackrabbitConfigPath; private String workingDirectory; private Session keepAliveSession; private Repository repository; private SequencingService sequencingService; private ObservationService observationService; private UserInterface userInterface; private ExecutionContext executionContext; public SequencingClient() { setJackrabbitConfigPath(DEFAULT_JACKRABBIT_CONFIG_PATH); setWorkingDirectory(DEFAULT_WORKING_DIRECTORY); setRepositoryInformation(DEFAULT_REPOSITORY_NAME, DEFAULT_WORKSPACE_NAME, DEFAULT_USERNAME, DEFAULT_PASSWORD); } protected void setWorkingDirectory( String workingDirectoryPath ) { this.workingDirectory = workingDirectoryPath != null ? workingDirectoryPath : DEFAULT_WORKING_DIRECTORY; } protected void setJackrabbitConfigPath( String jackrabbitConfigPath ) { this.jackrabbitConfigPath = jackrabbitConfigPath != null ? jackrabbitConfigPath : DEFAULT_JACKRABBIT_CONFIG_PATH; } protected void setRepositoryInformation( String repositoryName, String workspaceName, String username, char[] password ) { if (this.repository != null) { throw new IllegalArgumentException("Unable to set repository information when repository is already running"); } this.repositoryName = repositoryName != null ? repositoryName : DEFAULT_REPOSITORY_NAME; this.workspaceName = workspaceName != null ? workspaceName : DEFAULT_WORKSPACE_NAME; this.username = username; this.password = password; } /** * Set the user interface that this client should use. * @param userInterface */ public void setUserInterface( UserInterface userInterface ) { this.userInterface = userInterface; } /** * Start up the JCR repository. This method only operates using the JCR API and Jackrabbit-specific API. * @throws Exception */ public void startRepository() throws Exception { if (this.repository == null) { try { // Load the Jackrabbit configuration ... File configFile = new File(this.jackrabbitConfigPath); if (!configFile.exists()) { throw new SystemFailureException("The Jackrabbit configuration file cannot be found at " + configFile.getAbsoluteFile()); } if (!configFile.canRead()) { throw new SystemFailureException("Unable to read the Jackrabbit configuration file at " + configFile.getAbsoluteFile()); } String pathToConfig = configFile.getAbsolutePath(); // Find the directory where the Jackrabbit repository data will be stored ... File workingDirectory = new File(this.workingDirectory); if (workingDirectory.exists()) { if (!workingDirectory.isDirectory()) { throw new SystemFailureException("Unable to create working directory at " + workingDirectory.getAbsolutePath()); } } String workingDirectoryPath = workingDirectory.getAbsolutePath(); // Get the Jackrabbit custom node definition (CND) file ... URL cndFile = Thread.currentThread().getContextClassLoader().getResource("jackrabbitNodeTypes.cnd"); // Create the Jackrabbit repository instance and establish a session to keep the repository alive ... this.repository = new TransientRepository(pathToConfig, workingDirectoryPath); if (this.username != null) { Credentials credentials = new SimpleCredentials(this.username, this.password); this.keepAliveSession = this.repository.login(credentials, this.workspaceName); } else { this.keepAliveSession = this.repository.login(); } try { // Register the node types (only valid the first time) ... JackrabbitNodeTypeManager mgr = (JackrabbitNodeTypeManager)this.keepAliveSession.getWorkspace().getNodeTypeManager(); mgr.registerNodeTypes(cndFile.openStream(), JackrabbitNodeTypeManager.TEXT_X_JCR_CND); } catch (RepositoryException e) { if (!e.getMessage().contains("already exists")) throw e; } } catch (Exception e) { this.repository = null; this.keepAliveSession = null; throw e; } } } /** * Shutdown the repository. This method only uses the JCR API. * @throws Exception */ public void shutdownRepository() throws Exception { if (this.repository != null) { try { this.keepAliveSession.logout(); } finally { this.repository = null; this.keepAliveSession = null; } } } /** * Start the DNA services. * @throws Exception */ public void startDnaServices() throws Exception { if (this.repository == null) { this.startRepository(); } if (this.sequencingService == null) { // Create an execution context for the sequencing service. This execution context provides an environment // for the DNA services which knows about the JCR repositories, workspaces, and credentials used to // establish sessions to these workspaces. This example uses the SimpleExecutionContext, but there is // implementation for use with JCR repositories registered in JNDI. SimpleExecutionContext executionContext = new SimpleExecutionContext(); executionContext.registerRepository(this.repositoryName, this.repository); if (this.username != null) { Credentials credentials = new SimpleCredentials(this.username, this.password); executionContext.registerCredentials(this.repositoryName + "/" + this.workspaceName, credentials); } this.executionContext = executionContext; // Create the sequencing service, passing in the execution context ... this.sequencingService = new SequencingService(); this.sequencingService.setExecutionContext(executionContext); // Configure the sequencers. In this example, we only use a single sequencer that processes image files. // So create a configuration. Note that the sequencing service expects the class to be on the thread's current context // classloader, or if that's null the classloader that loaded the SequencingService class. // // Part of the configuration includes telling DNA which JCR paths should be processed by the sequencer. // These path expressions tell the service that this sequencer should be invoked on the "jcr:data" property // on the "jcr:content" child node of any node uploaded to the repository whose name ends with one of the // supported extensions, and the sequencer should place the generated output metadata in a node with the same name as // the file but immediately below the "/images" node. Path expressions can be fairly complex, and can even // specify that the generated information be placed in a different repository. // // Sequencer configurations can be added before or after the service is started, but here we do it before the service // is running. String name = "Image Sequencer"; String desc = "Sequences image files to extract the characteristics of the image"; String classname = "org.jboss.dna.sequencer.images.ImageMetadataSequencer"; String[] classpath = null; // Use the current classpath String[] pathExpressions = {"//(*.(jpg|jpeg|gif|bmp|pcx|png|iff|ras|pbm|pgm|ppm|psd))[*]/jcr:content[@jcr:data] => /images/$1"}; SequencerConfig imageSequencerConfig = new SequencerConfig(name, desc, classname, classpath, pathExpressions); this.sequencingService.addSequencer(imageSequencerConfig); // Use the DNA observation service to listen to the JCR repository (or multiple ones), and // then register the sequencing service as a listener to this observation service... this.observationService = new ObservationService(this.executionContext.getSessionFactory()); this.observationService.getAdministrator().start(); this.observationService.addListener(this.sequencingService); this.observationService.monitor(this.repositoryName + "/" + this.workspaceName, Event.NODE_ADDED | Event.PROPERTY_ADDED | Event.PROPERTY_CHANGED); } // Start up the sequencing service ... this.sequencingService.getAdministrator().start(); } /** * Shut down the DNA services. * @throws Exception */ public void shutdownDnaServices() throws Exception { if (this.sequencingService == null) return; // Shut down the service and wait until it's all shut down ... this.sequencingService.getAdministrator().shutdown(); this.sequencingService.getAdministrator().awaitTermination(5, TimeUnit.SECONDS); // Shut down the observation service ... this.observationService.getAdministrator().shutdown(); this.observationService.getAdministrator().awaitTermination(5, TimeUnit.SECONDS); } /** * Get the sequencing statistics. * @return the statistics; never null */ public SequencingService.Statistics getStatistics() { return this.sequencingService.getStatistics(); } /** * Prompt the user interface for the file to upload into the JCR repository, then upload it using the JCR API. * @throws Exception */ public void uploadFile() throws Exception { URL url = this.userInterface.getFileToUpload(); // Grab the last segment of the URL path, using it as the filename String filename = url.getPath().replaceAll("([^/]*/)*", ""); String nodePath = this.userInterface.getRepositoryPath("/a/b/" + filename); String mimeType = getMimeType(url); // Now use the JCR API to upload the file ... Session session = createSession(); JcrTools tools = this.executionContext.getTools(); try { // Create the node at the supplied path ... Node node = tools.findOrCreateNode(session, nodePath, "nt:folder", "nt:file"); // Upload the file to that node ... Node contentNode = tools.findOrCreateChild(session, node, "jcr:content", "nt:resource"); contentNode.setProperty("jcr:mimeType", mimeType); contentNode.setProperty("jcr:lastModified", Calendar.getInstance()); contentNode.setProperty("jcr:data", url.openStream()); // Save the session ... session.save(); } finally { session.logout(); } } /** * Perform a search of the repository for all image metadata automatically created by the image sequencer. * @throws Exception */ public void search() throws Exception { // Use JCR to search the repository for image metadata ... List<ImageInfo> images = new ArrayList<ImageInfo>(); Session session = createSession(); try { // Find the image node ... Node root = session.getRootNode(); if (root.hasNode("images")) { Node imagesNode = root.getNode("images"); // Iterate over each child ... for (NodeIterator iter = imagesNode.getNodes(); iter.hasNext();) { Node imageNode = iter.nextNode(); String nodePath = imageNode.getPath(); String nodeName = imageNode.getName(); if (imageNode.hasNode("image:metadata")) { imageNode = imageNode.getNode("image:metadata"); // Create a Properties object containing the properties for this node; ignore any children ... Properties props = new Properties(); for (PropertyIterator propertyIter = imageNode.getProperties(); propertyIter.hasNext();) { Property property = propertyIter.nextProperty(); String name = property.getName(); String stringValue = null; if (property.getDefinition().isMultiple()) { StringBuilder sb = new StringBuilder(); boolean first = true; for (Value value : property.getValues()) { if (!first) { sb.append(", "); first = false; } sb.append(value.getString()); } stringValue = sb.toString(); } else { stringValue = property.getValue().getString(); } props.put(name, stringValue); } // Create the image information object, and add it to the collection ... ImageInfo info = new ImageInfo(nodePath, nodeName, props); images.add(info); } } } } finally { session.logout(); } // Display the search results ... this.userInterface.displaySearchResults(images); } /** * Utility method to create a new JCR session from the execution context's {@link SessionFactory}. * @return the session * @throws RepositoryException */ protected Session createSession() throws RepositoryException { return this.executionContext.getSessionFactory().createSession(this.repositoryName + "/" + this.workspaceName); } protected String getMimeType( URL file ) { String filename = file.getPath().toLowerCase(); if (filename.endsWith(".gif")) return "image/gif"; if (filename.endsWith(".png")) return "image/png"; if (filename.endsWith(".pict")) return "image/x-pict"; if (filename.endsWith(".bmp")) return "image/bmp"; if (filename.endsWith(".jpg")) return "image/jpeg"; if (filename.endsWith(".jpe")) return "image/jpeg"; if (filename.endsWith(".jpeg")) return "image/jpeg"; if (filename.endsWith(".ras")) return "image/x-cmu-raster"; throw new SystemFailureException("Unknown mime type for " + file); } }
Changed the example application to be more clear. git-svn-id: 3298e7a5f393115f2db4c266335bac2f742abee0@139 76366958-4244-0410-ad5e-bbfabb93f86b
docs/examples/gettingstarted/sequencers/src/main/java/org/jboss/example/dna/sequencers/SequencingClient.java
Changed the example application to be more clear.
Java
apache-2.0
883f97c3134fb8d62b60304f2f730ad5ba7f12d2
0
thomasflynn/GearVRf,Samsung/GearVRf,xcaostagit/GearVRf,Samsung/GearVRf,xcaostagit/GearVRf,NolaDonato/GearVRf,NolaDonato/GearVRf,thomasflynn/GearVRf,thomasflynn/GearVRf,xcaostagit/GearVRf,xcaostagit/GearVRf,NolaDonato/GearVRf,NolaDonato/GearVRf,thomasflynn/GearVRf,NolaDonato/GearVRf,Samsung/GearVRf,thomasflynn/GearVRf,xcaostagit/GearVRf,thomasflynn/GearVRf,Samsung/GearVRf,Samsung/GearVRf,xcaostagit/GearVRf,Samsung/GearVRf,thomasflynn/GearVRf,NolaDonato/GearVRf,NolaDonato/GearVRf,Samsung/GearVRf
/* Copyright 2015 Samsung Electronics Co., LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gearvrf; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.lang.reflect.Method; import java.nio.FloatBuffer; import java.util.HashMap; import java.util.Map; import android.os.Environment; /** * Generates a vertex and fragment shader from the sources provided. * <p> * This class allows you to define your own custom shader and introduce * it into GearVRF. * Each shader generated has a unique signature so that the same shader * will not be generated twice. For shaders derived directly from * GVRShader, the signature is the simple Java class name. * <p> * The shader also defines descriptors that define the * names and types of all the uniforms, textures and vertex attributes * used by the shader. For uniforms and attributes, each entry is a * float or integer type, an optional count and the name of the * uniform (e.g. "float3 diffuse_color, float specular_exponent, int is_enabled". * For textures, the descriptor contains the sampler type followed by the name: * (e.g. "sampler2D u_texture; samplerCube u_cubemap") * <p> * Shaders derived from GVRShader cannot have variants and they ignore * light sources in the scene. To generate a more complex shader which * has multiple variants depending on what meshes, materials and * light sources it is used with, you can derive from @{link GVRShaderTemplate} * * @see GVRShaderTemplate */ public class GVRShader { protected boolean mWriteShadersToDisk = false; protected GLSLESVersion mGLSLVersion = GLSLESVersion.V100; protected boolean mHasVariants = false; protected boolean mUsesLights = false; protected boolean mUseTransformBuffer = false; // true to use Transform UBO in GL protected String mUniformDescriptor; protected String mVertexDescriptor; protected String mTextureDescriptor; protected Map<String, String> mShaderSegments; protected static String sBonesDescriptor = "mat4 u_bone_matrix[" + GVRMesh.MAX_BONES + "]"; protected static String sTransformUBOCode = "layout (std140) uniform Transform_ubo\n{\n" + " #ifdef HAS_MULTIVIEW\n" + " mat4 u_view_[2];\n" + " mat4 u_mvp_[2];\n" + " mat4 u_mv_[2];\n" + " mat4 u_mv_it_[2];\n" + " mat4 u_view_i_[2];\n" + " #else\n" + " mat4 u_view;\n" + " mat4 u_mvp;\n" + " mat4 u_mv;\n" + " mat4 u_mv_it;\n" + " mat4 u_view_i;\n" + " #endif\n" + " mat4 u_model;\n" + " float u_right;\n" + " uint u_render_mask;\n" + "};\n"; protected static String sTransformVkUBOCode = "layout (std140, set = 0, binding = 0) uniform Transform_ubo {\n " + " mat4 u_view;\n" + " mat4 u_mvp;\n" + " mat4 u_mv;\n" + " mat4 u_mv_it;\n" + " mat4 u_model;\n" + " mat4 u_view_i;\n" + " float u_right;\n" + " uint u_render_mask;\n" + "};\n"; protected static String sTransformUniformCode = "// Transform_ubo implemented as uniforms\n" + " #ifdef HAS_MULTIVIEW\n" + " uniform mat4 u_view_[2];\n" + " uniform mat4 u_mvp_[2];\n" + " uniform mat4 u_mv_[2];\n" + " uniform mat4 u_mv_it_[2];\n" + " uniform mat4 u_view_i_[2];\n" + " #else\n" + " uniform mat4 u_view;\n" + " uniform mat4 u_mvp;\n" + " uniform mat4 u_mv;\n" + " uniform mat4 u_mv_it;\n" + " uniform mat4 u_view_i;\n" + " #endif\n" + " uniform mat4 u_model;\n" + " uniform float u_right;\n" + " uniform uint u_render_mask;\n"; /** * Construct a shader using GLSL version 100. * To make a shader for another version use the other form of the constructor. * * @param uniformDescriptor string describing uniform names and types * e.g. "float4 diffuse_color, float4 specular_color, float specular_exponent" * @param textureDescriptor string describing texture names and types * e.g. "sampler2D diffuseTexture, sampler2D specularTexture" * @param vertexDescriptor string describing vertex attributes and types * e.g. "float3 a_position, float2 a_texcoord" */ public GVRShader(String uniformDescriptor, String textureDescriptor, String vertexDescriptor) { mUniformDescriptor = uniformDescriptor; mVertexDescriptor = vertexDescriptor; mTextureDescriptor = textureDescriptor; mShaderSegments = new HashMap<String, String>(); } /** * Construct a shader using specified GLSL version * * @param uniformDescriptor string describing uniform names and types * e.g. "float4 diffuse_color, float4 specular_color, float specular_exponent" * @param textureDescriptor string describing texture names and types * e.g. "sampler2D diffuseTexture, sampler2D specularTexture" * @param vertexDescriptor string describing vertex attributes and types * e.g. "float3 a_position, float2 a_texcoord" * string describing uniform names and types * @param glslVersion * GLSL version (e.g. GLSLESVersion.V300) */ public GVRShader(String uniformDescriptor, String textureDescriptor, String vertexDescriptor, GLSLESVersion glslVersion) { mUniformDescriptor = uniformDescriptor; mVertexDescriptor = vertexDescriptor; mTextureDescriptor = textureDescriptor; mShaderSegments = new HashMap<String, String>(); mGLSLVersion = glslVersion; } /** * Check if this shader template generates variants. * * If a shader template generates variants, the specific vertex and * fragment shader to use cannot be determined until * the mesh, the material and lights are known. If the shader * template only makes a single shader, the vertex and fragment * shader programs can be generated immediately. * * @return true if this template generates variants, * false if only a single shader can be generated. * @see GVRRenderData */ public boolean hasVariants() { return mHasVariants; } /** * Check if this shader template uses light sources. * * If a shader template uses light sources, the specific vertex * and fragment shader to use cannot be generated until all * light sources are known. If the shader ignores lighting, * it will not need to be regenerated if lights are added * or removed from the scene. * @see GVRShader#hasVariants() */ public boolean usesLights() { return mUsesLights; } /** * Get the string describing the shader uniforms. * * Each uniform is a fixed number of integer or float values. It is * described with the type ("int" or "float") immediately followed by the * size (a small integer) a space and then the name of uniform in the shader * (e.g. "int enabled, float3 color") Spaces, commas, and other punctuation * are ignored. * * @return String with descriptor. * {@link GVRLight#getUniformDescriptor()} } */ public String getUniformDescriptor() { return mUniformDescriptor; } /** * Get the string describing the vertex attributes used by this shader. * * Each vertex attribute represents a channel of float or int vectors. * It is described with the type ("int" or "float") immediately followed by the * size (a small integer) a space and then the name of the vertex attribute in the shader * (e.g. "float3 a_position, float23 a_texcoord") Spaces, commas, and other punctuation * are ignored. * * @return String with uniform descriptor. * {@link GVRLight#getVertexDescriptor()} } */ public String getVertexDescriptor() { return mVertexDescriptor; } /** * Get the string describing the textures used by this shader. * * A texture is described with the sampler type (e.g. "sampler2D" or "samplerCube") * a space and then the name of the sampler in the shader. * (e.g. "sampler2D u_texture") Spaces, commas, and other punctuation are ignored. * * @return String with uniform descriptor. */ public String getTextureDescriptor() { return mTextureDescriptor; } /** * Create a unique signature for this shader. * The signature for simple shaders is just the class name. * For the more complex shaders generated by GVRShaderTemplate * the signature includes information about the vertex attributes, * uniforms, textures and lights used by the shader variant. * * @param defined * names to be defined for this shader * @return string signature for shader * @see GVRShaderTemplate */ public String generateSignature(HashMap<String, Integer> defined, GVRLight[] lightlist) { return getClass().getSimpleName(); } /** * Sets the default values for material data used by the shader. * Subclasses can override this function to provide values for * uniforms used by the material that are required by this shader. * This function is called whenever a GVRMaterial is created * that uses this shader class. * * @param material the material whose values should be set * @see GVRMaterial */ protected void setMaterialDefaults(GVRShaderData material) { } private int addShader(GVRShaderManager shaderManager, String signature, GVRShaderData material) { GVRContext ctx = shaderManager.getGVRContext(); StringBuilder vertexShaderSource = new StringBuilder(); StringBuilder fragmentShaderSource = new StringBuilder(); vertexShaderSource.append("#version " + mGLSLVersion.toString() + "\n"); fragmentShaderSource.append("#version " + mGLSLVersion.toString() + " \n"); String vshader = replaceTransforms(getSegment("VertexTemplate")); String fshader = replaceTransforms(getSegment("FragmentTemplate")); if (material != null) { String mtlLayout = material.makeShaderLayout(); vshader = vshader.replace("@MATERIAL_UNIFORMS", mtlLayout); fshader = fshader.replace("@MATERIAL_UNIFORMS", mtlLayout); if(fshader.contains("Material_ubo") || vshader.contains("Material_ubo")) material.useGpuBuffer(true); else material.useGpuBuffer(false); } vshader = vshader.replace("@BONES_UNIFORMS", GVRShaderManager.makeLayout(sBonesDescriptor, "Bones_ubo", true)); vertexShaderSource.append(vshader); fragmentShaderSource.append(fshader); String frag = fragmentShaderSource.toString(); String vert = vertexShaderSource.toString(); int nativeShader = shaderManager.addShader(signature, mUniformDescriptor, mTextureDescriptor, mVertexDescriptor, vert, frag); bindCalcMatrixMethod(shaderManager, nativeShader); if (mWriteShadersToDisk) { writeShader(ctx, "V-" + signature + ".glsl", vert); writeShader(ctx, "F-" + signature + ".glsl", frag); } return nativeShader; } /** * Select the specific vertex and fragment shader to use. * * The shader template is used to generate the sources for the vertex and * fragment shader based on the vertex, material and light properties. This * function may compile the shader if it does not already exist. * * @param context * GVRContext * @param rdata * renderable entity with mesh and rendering options * @param scene * list of light sources */ public int bindShader(GVRContext context, IRenderable rdata, GVRScene scene, boolean isMultiview) { String signature = getClass().getSimpleName(); GVRShaderManager shaderManager = context.getShaderManager(); GVRMaterial mtl = rdata.getMaterial(); synchronized (shaderManager) { int nativeShader = shaderManager.getShader(signature); if (nativeShader == 0) { nativeShader = addShader(shaderManager, signature, mtl); } if (nativeShader > 0) { rdata.setShader(nativeShader, isMultiview); } return nativeShader; } } /** * Select the specific vertex and fragment shader to use with this material. * * The shader template is used to generate the sources for the vertex and * fragment shader based on the material properties only. * It will ignore the mesh attributes and all lights. * * @param context * GVRContext * @param material * material to use with the shader * @return ID of vertex/fragment shader set */ public int bindShader(GVRContext context, GVRShaderData material, String vertexDesc) { String signature = getClass().getSimpleName(); GVRShaderManager shaderManager = context.getShaderManager(); synchronized (shaderManager) { int nativeShader = shaderManager.getShader(signature); if (nativeShader == 0) { nativeShader = addShader(shaderManager, signature, material); } return nativeShader; } } /** * Replaces @MATRIX_UNIFORMS in shader source with the * proper transform uniform declarations. * @param code shader source code * @return shader source with transform uniform declarations added */ protected String replaceTransforms(String code) { if (isVulkanInstance()) return code.replace("@MATRIX_UNIFORMS", sTransformVkUBOCode); if (mUseTransformBuffer) return code.replace("@MATRIX_UNIFORMS", sTransformUBOCode); return code.replace("@MATRIX_UNIFORMS", sTransformUniformCode); } /** * Get the designated shader segment. * * @param name * string name of shader segment * @return source code for segment or null if none exists. * {@link GVRShaderTemplate#setSegment(String, String)} */ protected String getSegment(String name) { return mShaderSegments.get(name); } /** * Attach a named shader segment. * * Shader segment names should start with either "Vertex" or "Fragment" to * designate which type of shader the code belongs with. Both vertex and * fragment shaders can have more than one code segment contribute to the * final shader. * * @param segmentName * name associated with shader segment * @param shaderSource * String with shader source code */ protected void setSegment(String segmentName, String shaderSource) { mShaderSegments.put(segmentName, shaderSource); if (shaderSource == null) throw new java.lang.IllegalArgumentException("Shader source is null for segment " + segmentName + " of shader"); } private boolean isImplemented(String methodName, Class<?> ...paramTypes) { try { Class<? extends Object> clazz = getClass(); String name1 = clazz.getSimpleName(); Method method = clazz.getMethod(methodName, paramTypes); Class<? extends Object> declClazz = method.getDeclaringClass(); String name2 = declClazz.getSimpleName(); return declClazz.equals(clazz); } catch (SecurityException e) { return false; } catch (NoSuchMethodException e) { return false; } } protected void bindCalcMatrixMethod(GVRShaderManager shaderManager, int nativeShader) { if (isImplemented("calcMatrix", FloatBuffer.class, FloatBuffer.class)) { NativeShaderManager.bindCalcMatrix(shaderManager.getNative(), nativeShader, getClass()); } } protected void writeShader(GVRContext context, String fileName, String sourceCode) { try { File sdCard = Environment.getExternalStorageDirectory(); File file = new File(sdCard.getAbsolutePath() + "/GearVRF/" + fileName); OutputStreamWriter stream = new FileWriter(file); stream.append(sourceCode); stream.close(); } catch (IOException ex) { org.gearvrf.utility.Log.e("GVRShaderTemplate", "Cannot write shader file " + fileName); } } public static native boolean isVulkanInstance(); public enum GLSLESVersion { V100("100 es"), V300("300 es"), V310("310 es"), V320("320 es"), VULKAN("400"); // HACK: OK with Vulkan; gl_shader.c will replace with "300 es" private GLSLESVersion(String name) { this.name = name; } private final String name; public String toString() { return name; } } }
GVRf/Framework/framework/src/main/java/org/gearvrf/GVRShader.java
/* Copyright 2015 Samsung Electronics Co., LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gearvrf; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.lang.reflect.Method; import java.nio.FloatBuffer; import java.util.HashMap; import java.util.Map; import android.os.Environment; /** * Generates a vertex and fragment shader from the sources provided. * <p> * This class allows you to define your own custom shader and introduce * it into GearVRF. * Each shader generated has a unique signature so that the same shader * will not be generated twice. For shaders derived directly from * GVRShader, the signature is the simple Java class name. * <p> * The shader also defines descriptors that define the * names and types of all the uniforms, textures and vertex attributes * used by the shader. For uniforms and attributes, each entry is a * float or integer type, an optional count and the name of the * uniform (e.g. "float3 diffuse_color, float specular_exponent, int is_enabled". * For textures, the descriptor contains the sampler type followed by the name: * (e.g. "sampler2D u_texture; samplerCube u_cubemap") * <p> * Shaders derived from GVRShader cannot have variants and they ignore * light sources in the scene. To generate a more complex shader which * has multiple variants depending on what meshes, materials and * light sources it is used with, you can derive from @{link GVRShaderTemplate} * * @see GVRShaderTemplate */ public class GVRShader { protected boolean mWriteShadersToDisk = true; protected GLSLESVersion mGLSLVersion = GLSLESVersion.V100; protected boolean mHasVariants = false; protected boolean mUsesLights = false; protected boolean mUseTransformBuffer = false; // true to use Transform UBO in GL protected String mUniformDescriptor; protected String mVertexDescriptor; protected String mTextureDescriptor; protected Map<String, String> mShaderSegments; protected static String sBonesDescriptor = "mat4 u_bone_matrix[" + GVRMesh.MAX_BONES + "]"; protected static String sTransformUBOCode = "layout (std140) uniform Transform_ubo\n{\n" + " #ifdef HAS_MULTIVIEW\n" + " mat4 u_view_[2];\n" + " mat4 u_mvp_[2];\n" + " mat4 u_mv_[2];\n" + " mat4 u_mv_it_[2];\n" + " mat4 u_view_i_[2];\n" + " #else\n" + " mat4 u_view;\n" + " mat4 u_mvp;\n" + " mat4 u_mv;\n" + " mat4 u_mv_it;\n" + " mat4 u_view_i;\n" + " #endif\n" + " mat4 u_model;\n" + " float u_right;\n" + " uint u_render_mask;\n" + "};\n"; protected static String sTransformVkUBOCode = "layout (std140, set = 0, binding = 0) uniform Transform_ubo {\n " + " mat4 u_view;\n" + " mat4 u_mvp;\n" + " mat4 u_mv;\n" + " mat4 u_mv_it;\n" + " mat4 u_model;\n" + " mat4 u_view_i;\n" + " float u_right;\n" + " uint u_render_mask;\n" + "};\n"; protected static String sTransformUniformCode = "// Transform_ubo implemented as uniforms\n" + " #ifdef HAS_MULTIVIEW\n" + " uniform mat4 u_view_[2];\n" + " uniform mat4 u_mvp_[2];\n" + " uniform mat4 u_mv_[2];\n" + " uniform mat4 u_mv_it_[2];\n" + " uniform mat4 u_view_i_[2];\n" + " #else\n" + " uniform mat4 u_view;\n" + " uniform mat4 u_mvp;\n" + " uniform mat4 u_mv;\n" + " uniform mat4 u_mv_it;\n" + " uniform mat4 u_view_i;\n" + " #endif\n" + " uniform mat4 u_model;\n" + " uniform float u_right;\n" + " uniform uint u_render_mask;\n"; /** * Construct a shader using GLSL version 100. * To make a shader for another version use the other form of the constructor. * * @param uniformDescriptor string describing uniform names and types * e.g. "float4 diffuse_color, float4 specular_color, float specular_exponent" * @param textureDescriptor string describing texture names and types * e.g. "sampler2D diffuseTexture, sampler2D specularTexture" * @param vertexDescriptor string describing vertex attributes and types * e.g. "float3 a_position, float2 a_texcoord" */ public GVRShader(String uniformDescriptor, String textureDescriptor, String vertexDescriptor) { mUniformDescriptor = uniformDescriptor; mVertexDescriptor = vertexDescriptor; mTextureDescriptor = textureDescriptor; mShaderSegments = new HashMap<String, String>(); } /** * Construct a shader using specified GLSL version * * @param uniformDescriptor string describing uniform names and types * e.g. "float4 diffuse_color, float4 specular_color, float specular_exponent" * @param textureDescriptor string describing texture names and types * e.g. "sampler2D diffuseTexture, sampler2D specularTexture" * @param vertexDescriptor string describing vertex attributes and types * e.g. "float3 a_position, float2 a_texcoord" * string describing uniform names and types * @param glslVersion * GLSL version (e.g. GLSLESVersion.V300) */ public GVRShader(String uniformDescriptor, String textureDescriptor, String vertexDescriptor, GLSLESVersion glslVersion) { mUniformDescriptor = uniformDescriptor; mVertexDescriptor = vertexDescriptor; mTextureDescriptor = textureDescriptor; mShaderSegments = new HashMap<String, String>(); mGLSLVersion = glslVersion; } /** * Check if this shader template generates variants. * * If a shader template generates variants, the specific vertex and * fragment shader to use cannot be determined until * the mesh, the material and lights are known. If the shader * template only makes a single shader, the vertex and fragment * shader programs can be generated immediately. * * @return true if this template generates variants, * false if only a single shader can be generated. * @see GVRRenderData */ public boolean hasVariants() { return mHasVariants; } /** * Check if this shader template uses light sources. * * If a shader template uses light sources, the specific vertex * and fragment shader to use cannot be generated until all * light sources are known. If the shader ignores lighting, * it will not need to be regenerated if lights are added * or removed from the scene. * @see GVRShader#hasVariants() */ public boolean usesLights() { return mUsesLights; } /** * Get the string describing the shader uniforms. * * Each uniform is a fixed number of integer or float values. It is * described with the type ("int" or "float") immediately followed by the * size (a small integer) a space and then the name of uniform in the shader * (e.g. "int enabled, float3 color") Spaces, commas, and other punctuation * are ignored. * * @return String with descriptor. * {@link GVRLight#getUniformDescriptor()} } */ public String getUniformDescriptor() { return mUniformDescriptor; } /** * Get the string describing the vertex attributes used by this shader. * * Each vertex attribute represents a channel of float or int vectors. * It is described with the type ("int" or "float") immediately followed by the * size (a small integer) a space and then the name of the vertex attribute in the shader * (e.g. "float3 a_position, float23 a_texcoord") Spaces, commas, and other punctuation * are ignored. * * @return String with uniform descriptor. * {@link GVRLight#getVertexDescriptor()} } */ public String getVertexDescriptor() { return mVertexDescriptor; } /** * Get the string describing the textures used by this shader. * * A texture is described with the sampler type (e.g. "sampler2D" or "samplerCube") * a space and then the name of the sampler in the shader. * (e.g. "sampler2D u_texture") Spaces, commas, and other punctuation are ignored. * * @return String with uniform descriptor. */ public String getTextureDescriptor() { return mTextureDescriptor; } /** * Create a unique signature for this shader. * The signature for simple shaders is just the class name. * For the more complex shaders generated by GVRShaderTemplate * the signature includes information about the vertex attributes, * uniforms, textures and lights used by the shader variant. * * @param defined * names to be defined for this shader * @return string signature for shader * @see GVRShaderTemplate */ public String generateSignature(HashMap<String, Integer> defined, GVRLight[] lightlist) { return getClass().getSimpleName(); } /** * Sets the default values for material data used by the shader. * Subclasses can override this function to provide values for * uniforms used by the material that are required by this shader. * This function is called whenever a GVRMaterial is created * that uses this shader class. * * @param material the material whose values should be set * @see GVRMaterial */ protected void setMaterialDefaults(GVRShaderData material) { } private int addShader(GVRShaderManager shaderManager, String signature, GVRShaderData material) { GVRContext ctx = shaderManager.getGVRContext(); StringBuilder vertexShaderSource = new StringBuilder(); StringBuilder fragmentShaderSource = new StringBuilder(); vertexShaderSource.append("#version " + mGLSLVersion.toString() + "\n"); fragmentShaderSource.append("#version " + mGLSLVersion.toString() + " \n"); String vshader = replaceTransforms(getSegment("VertexTemplate")); String fshader = replaceTransforms(getSegment("FragmentTemplate")); if (material != null) { String mtlLayout = material.makeShaderLayout(); vshader = vshader.replace("@MATERIAL_UNIFORMS", mtlLayout); fshader = fshader.replace("@MATERIAL_UNIFORMS", mtlLayout); if(fshader.contains("Material_ubo") || vshader.contains("Material_ubo")) material.useGpuBuffer(true); else material.useGpuBuffer(false); } vshader = vshader.replace("@BONES_UNIFORMS", GVRShaderManager.makeLayout(sBonesDescriptor, "Bones_ubo", true)); vertexShaderSource.append(vshader); fragmentShaderSource.append(fshader); String frag = fragmentShaderSource.toString(); String vert = vertexShaderSource.toString(); int nativeShader = shaderManager.addShader(signature, mUniformDescriptor, mTextureDescriptor, mVertexDescriptor, vert, frag); bindCalcMatrixMethod(shaderManager, nativeShader); if (mWriteShadersToDisk) { writeShader(ctx, "V-" + signature + ".glsl", vert); writeShader(ctx, "F-" + signature + ".glsl", frag); } return nativeShader; } /** * Select the specific vertex and fragment shader to use. * * The shader template is used to generate the sources for the vertex and * fragment shader based on the vertex, material and light properties. This * function may compile the shader if it does not already exist. * * @param context * GVRContext * @param rdata * renderable entity with mesh and rendering options * @param scene * list of light sources */ public int bindShader(GVRContext context, IRenderable rdata, GVRScene scene, boolean isMultiview) { String signature = getClass().getSimpleName(); GVRShaderManager shaderManager = context.getShaderManager(); GVRMaterial mtl = rdata.getMaterial(); synchronized (shaderManager) { int nativeShader = shaderManager.getShader(signature); if (nativeShader == 0) { nativeShader = addShader(shaderManager, signature, mtl); } if (nativeShader > 0) { rdata.setShader(nativeShader, isMultiview); } return nativeShader; } } /** * Select the specific vertex and fragment shader to use with this material. * * The shader template is used to generate the sources for the vertex and * fragment shader based on the material properties only. * It will ignore the mesh attributes and all lights. * * @param context * GVRContext * @param material * material to use with the shader * @return ID of vertex/fragment shader set */ public int bindShader(GVRContext context, GVRShaderData material, String vertexDesc) { String signature = getClass().getSimpleName(); GVRShaderManager shaderManager = context.getShaderManager(); synchronized (shaderManager) { int nativeShader = shaderManager.getShader(signature); if (nativeShader == 0) { nativeShader = addShader(shaderManager, signature, material); } return nativeShader; } } /** * Replaces @MATRIX_UNIFORMS in shader source with the * proper transform uniform declarations. * @param code shader source code * @return shader source with transform uniform declarations added */ protected String replaceTransforms(String code) { if (isVulkanInstance()) return code.replace("@MATRIX_UNIFORMS", sTransformVkUBOCode); if (mUseTransformBuffer) return code.replace("@MATRIX_UNIFORMS", sTransformUBOCode); return code.replace("@MATRIX_UNIFORMS", sTransformUniformCode); } /** * Get the designated shader segment. * * @param name * string name of shader segment * @return source code for segment or null if none exists. * {@link GVRShaderTemplate#setSegment(String, String)} */ protected String getSegment(String name) { return mShaderSegments.get(name); } /** * Attach a named shader segment. * * Shader segment names should start with either "Vertex" or "Fragment" to * designate which type of shader the code belongs with. Both vertex and * fragment shaders can have more than one code segment contribute to the * final shader. * * @param segmentName * name associated with shader segment * @param shaderSource * String with shader source code */ protected void setSegment(String segmentName, String shaderSource) { mShaderSegments.put(segmentName, shaderSource); if (shaderSource == null) throw new java.lang.IllegalArgumentException("Shader source is null for segment " + segmentName + " of shader"); } private boolean isImplemented(String methodName, Class<?> ...paramTypes) { try { Class<? extends Object> clazz = getClass(); String name1 = clazz.getSimpleName(); Method method = clazz.getMethod(methodName, paramTypes); Class<? extends Object> declClazz = method.getDeclaringClass(); String name2 = declClazz.getSimpleName(); return declClazz.equals(clazz); } catch (SecurityException e) { return false; } catch (NoSuchMethodException e) { return false; } } protected void bindCalcMatrixMethod(GVRShaderManager shaderManager, int nativeShader) { if (isImplemented("calcMatrix", FloatBuffer.class, FloatBuffer.class)) { NativeShaderManager.bindCalcMatrix(shaderManager.getNative(), nativeShader, getClass()); } } protected void writeShader(GVRContext context, String fileName, String sourceCode) { try { File sdCard = Environment.getExternalStorageDirectory(); File file = new File(sdCard.getAbsolutePath() + "/GearVRF/" + fileName); OutputStreamWriter stream = new FileWriter(file); stream.append(sourceCode); stream.close(); } catch (IOException ex) { org.gearvrf.utility.Log.e("GVRShaderTemplate", "Cannot write shader file " + fileName); } } public static native boolean isVulkanInstance(); public enum GLSLESVersion { V100("100 es"), V300("300 es"), V310("310 es"), V320("320 es"), VULKAN("400"); // HACK: OK with Vulkan; gl_shader.c will replace with "300 es" private GLSLESVersion(String name) { this.name = name; } private final String name; public String toString() { return name; } } }
Disable writing shaders to the sdcard
GVRf/Framework/framework/src/main/java/org/gearvrf/GVRShader.java
Disable writing shaders to the sdcard
Java
apache-2.0
f1f5b49528f4a2bcdff3a984a4296dd3c9cf3846
0
ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma
/* * The Gemma project * * Copyright (c) 2007 University of British Columbia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package ubic.gemma.web.controller.javaspaces.gigaspaces; import java.util.concurrent.FutureTask; import javax.servlet.http.HttpServletRequest; import net.jini.core.lease.Lease; import net.jini.space.JavaSpace; import org.acegisecurity.context.SecurityContext; import org.acegisecurity.context.SecurityContextHolder; import org.springframework.context.ApplicationContext; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView; import org.springmodules.javaspaces.gigaspaces.GigaSpacesTemplate; import ubic.gemma.util.javaspaces.GemmaSpacesProgressEntry; import ubic.gemma.util.javaspaces.JavaSpacesJobObserver; import ubic.gemma.util.javaspaces.gigaspaces.GemmaSpacesEnum; import ubic.gemma.util.javaspaces.gigaspaces.GigaSpacesUtil; import ubic.gemma.web.controller.BackgroundControllerJob; import ubic.gemma.web.controller.BackgroundProcessingFormController; import ubic.gemma.web.controller.TaskRunningService; import ubic.gemma.web.util.MessageUtil; import com.j_spaces.core.client.NotifyModifiers; /** * Controllers requiring the capability to submit jobs to a compute server should extend this controller. * * @author keshav * @version $Id$ */ public abstract class AbstractGigaSpacesFormController extends BackgroundProcessingFormController { private GigaSpacesUtil gigaSpacesUtil = null; protected ApplicationContext updatedContext = null; /** * Runs the job in a {@link JavaSpace}. * * @param jobId * @param securityContext * @param request * @param command * @param messenger * @return BackgroundControllerJob<ModelAndView> */ abstract protected BackgroundControllerJob<ModelAndView> getSpaceRunner( String jobId, SecurityContext securityContext, HttpServletRequest request, Object command, MessageUtil messenger ); /** * Controllers extending this class must implement this method. The implementation should call * injectGigaspacesUtil(GigaSpacesUtil gigaSpacesUtil) to "inject" a spring loaded GigaSpacesUtil into this abstract * class. * * @param gigaSpacesUtil */ abstract protected void setGigaSpacesUtil( GigaSpacesUtil gigaSpacesUtil ); /** * @return ApplicationContext */ public ApplicationContext addGigaspacesToApplicationContext() { if ( gigaSpacesUtil == null ) gigaSpacesUtil = new GigaSpacesUtil(); return gigaSpacesUtil.addGigaspacesToApplicationContext( GemmaSpacesEnum.DEFAULT_SPACE.getSpaceUrl() ); } /** * Starts the job on a compute server resource if the spaces is running and the task can be services. If the * taskName is null and the gigaspaces beans have not been loaded, the job WILL be run in the webapp (as opposed to * on the compute server). * * @param command * @param request * @param spaceUrl * @param taskName * @return {@link ModelAndView} */ protected synchronized ModelAndView startJob( Object command, HttpServletRequest request, String spaceUrl, String taskName ) { /* * all new threads need this to acccess protected resources (like services) */ SecurityContext context = SecurityContextHolder.getContext(); String taskId = TaskRunningService.generateTaskId(); updatedContext = addGigaspacesToApplicationContext(); BackgroundControllerJob<ModelAndView> job = null; if ( updatedContext.containsBean( "gigaspacesTemplate" ) ) { if ( !gigaSpacesUtil.canServiceTask( taskName, spaceUrl ) ) { // TODO Add sending of email to user. // User user = SecurityUtil.getUserFromUserDetails( ( UserDetails ) SecurityContextHolder.getContext() // .getAuthentication().getPrincipal() ); // this.sendEmail( user, "Cannot service task " + taskName + " on the compute server at this time.", // "http://www.bioinformatics.ubc.ca/Gemma/" ); this.saveMessage( request, "No workers are registered to service task " + taskName.getClass().getSimpleName() + " on the compute server at this time." ); return new ModelAndView( new RedirectView( "/Gemma/loadExpressionExperiment.html" ) ); } /* register this "spaces client" to receive notifications */ JavaSpacesJobObserver javaSpacesJobObserver = new JavaSpacesJobObserver( taskId ); GigaSpacesTemplate template = ( GigaSpacesTemplate ) updatedContext.getBean( "gigaspacesTemplate" ); template.addNotifyDelegatorListener( javaSpacesJobObserver, new GemmaSpacesProgressEntry(), null, true, Lease.FOREVER, NotifyModifiers.NOTIFY_ALL ); job = getSpaceRunner( taskId, context, request, command, this.getMessageUtil() ); } else if ( !updatedContext.containsBean( "gigaspacesTemplate" ) && taskName != null ) { this .saveMessage( request, "This task must be run on the compute server, but the space is not running. Please try again later." ); return new ModelAndView( new RedirectView( "/Gemma/loadExpressionExperiment.html" ) ); } else { job = getRunner( taskId, context, request, command, this.getMessageUtil() ); } assert taskId != null; request.getSession().setAttribute( JOB_ATTRIBUTE, taskId ); taskRunningService.submitTask( taskId, new FutureTask<ModelAndView>( job ) ); ModelAndView mnv = new ModelAndView( new RedirectView( "/Gemma/processProgress.html?taskid=" + taskId ) ); mnv.addObject( JOB_ATTRIBUTE, taskId ); return mnv; } /** * @param gigaSpacesUtil */ protected void injectGigaspacesUtil( GigaSpacesUtil gigaspacesUtil ) { this.gigaSpacesUtil = gigaspacesUtil; } }
gemma-web/src/main/java/ubic/gemma/web/controller/javaspaces/gigaspaces/AbstractGigaSpacesFormController.java
/* * The Gemma project * * Copyright (c) 2007 University of British Columbia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package ubic.gemma.web.controller.javaspaces.gigaspaces; import java.util.concurrent.FutureTask; import javax.servlet.http.HttpServletRequest; import net.jini.core.lease.Lease; import net.jini.space.JavaSpace; import org.acegisecurity.context.SecurityContext; import org.acegisecurity.context.SecurityContextHolder; import org.springframework.context.ApplicationContext; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView; import org.springmodules.javaspaces.gigaspaces.GigaSpacesTemplate; import ubic.gemma.util.javaspaces.GemmaSpacesProgressEntry; import ubic.gemma.util.javaspaces.JavaSpacesJobObserver; import ubic.gemma.util.javaspaces.gigaspaces.GemmaSpacesEnum; import ubic.gemma.util.javaspaces.gigaspaces.GigaSpacesUtil; import ubic.gemma.web.controller.BackgroundControllerJob; import ubic.gemma.web.controller.BackgroundProcessingFormController; import ubic.gemma.web.controller.TaskRunningService; import ubic.gemma.web.util.MessageUtil; import com.j_spaces.core.client.NotifyModifiers; /** * Controllers requiring the capability to submit jobs to a compute server should extend this controller. * * @author keshav * @version $Id$ */ public abstract class AbstractGigaSpacesFormController extends BackgroundProcessingFormController { private GigaSpacesUtil gigaSpacesUtil = null; protected ApplicationContext updatedContext = null; /** * Runs the job in a {@link JavaSpace}. * * @param jobId * @param securityContext * @param request * @param command * @param messenger * @return BackgroundControllerJob<ModelAndView> */ abstract protected BackgroundControllerJob<ModelAndView> getSpaceRunner( String jobId, SecurityContext securityContext, HttpServletRequest request, Object command, MessageUtil messenger ); /** * Controllers extending this class must implement this method. The implementation should call * injectGigaspacesUtil(GigaSpacesUtil gigaSpacesUtil) to "inject" a spring loaded GigaSpacesUtil into this abstract * class. * * @param gigaSpacesUtil */ abstract protected void setGigaSpacesUtil( GigaSpacesUtil gigaSpacesUtil ); /** * @return ApplicationContext */ public ApplicationContext addGigaspacesToApplicationContext() { if ( gigaSpacesUtil == null ) gigaSpacesUtil = new GigaSpacesUtil(); return gigaSpacesUtil.addGigaspacesToApplicationContext( GemmaSpacesEnum.DEFAULT_SPACE.getSpaceUrl() ); } /** * Starts the job on a compute server resource if the spaces is running and the task can be services. * * @param command * @param request * @param spaceUrl * @param task * @return ModelAndView */ protected synchronized ModelAndView startJob( Object command, HttpServletRequest request, String spaceUrl, String taskName ) { /* * all new threads need this to acccess protected resources (like services) */ SecurityContext context = SecurityContextHolder.getContext(); String taskId = TaskRunningService.generateTaskId(); updatedContext = addGigaspacesToApplicationContext(); BackgroundControllerJob<ModelAndView> job = null; if ( updatedContext.containsBean( "gigaspacesTemplate" ) ) { if ( !gigaSpacesUtil.canServiceTask( taskName, spaceUrl ) ) { // TODO Add sending of email to user. // User user = SecurityUtil.getUserFromUserDetails( ( UserDetails ) SecurityContextHolder.getContext() // .getAuthentication().getPrincipal() ); // this.sendEmail( user, "Cannot service task " + taskName + " on the compute server at this time.", // "http://www.bioinformatics.ubc.ca/Gemma/" ); this.saveMessage( request, "Cannot service task " + taskName.getClass().getSimpleName() + " on the compute server at this time." ); return new ModelAndView( new RedirectView( "/Gemma/loadExpressionExperiment.html" ) ); } /* register this "spaces client" to receive notifications */ JavaSpacesJobObserver javaSpacesJobObserver = new JavaSpacesJobObserver( taskId ); GigaSpacesTemplate template = ( GigaSpacesTemplate ) updatedContext.getBean( "gigaspacesTemplate" ); template.addNotifyDelegatorListener( javaSpacesJobObserver, new GemmaSpacesProgressEntry(), null, true, Lease.FOREVER, NotifyModifiers.NOTIFY_ALL ); job = getSpaceRunner( taskId, context, request, command, this.getMessageUtil() ); } else if ( !updatedContext.containsBean( "gigaspacesTemplate" ) && taskName != null ) { this .saveMessage( request, "This task must be run on the compute server, but the space is not running. Please try again later." ); return new ModelAndView( new RedirectView( "/Gemma/loadExpressionExperiment.html" ) ); } else { job = getRunner( taskId, context, request, command, this.getMessageUtil() ); } assert taskId != null; request.getSession().setAttribute( JOB_ATTRIBUTE, taskId ); taskRunningService.submitTask( taskId, new FutureTask<ModelAndView>( job ) ); ModelAndView mnv = new ModelAndView( new RedirectView( "/Gemma/processProgress.html?taskid=" + taskId ) ); mnv.addObject( JOB_ATTRIBUTE, taskId ); return mnv; } /** * @param gigaSpacesUtil */ protected void injectGigaspacesUtil( GigaSpacesUtil gigaspacesUtil ) { this.gigaSpacesUtil = gigaspacesUtil; } }
minor
gemma-web/src/main/java/ubic/gemma/web/controller/javaspaces/gigaspaces/AbstractGigaSpacesFormController.java
minor
Java
apache-2.0
f8695df5bd320d6e155d4e602c3a6c902b0cb062
0
Sargul/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,Sargul/dbeaver
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.generic.edit; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.ext.generic.GenericConstants; import org.jkiss.dbeaver.ext.generic.model.GenericTable; import org.jkiss.dbeaver.ext.generic.model.GenericTableColumn; import org.jkiss.dbeaver.model.DBConstants; import org.jkiss.dbeaver.model.DBPDataKind; import org.jkiss.dbeaver.model.edit.DBECommandContext; import org.jkiss.dbeaver.model.impl.DBSObjectCache; import org.jkiss.dbeaver.model.impl.edit.DBECommandAbstract; import org.jkiss.dbeaver.model.impl.sql.edit.struct.SQLTableColumnManager; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSDataType; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.utils.CommonUtils; import java.sql.Types; /** * Generic table column manager */ public class GenericTableColumnManager extends SQLTableColumnManager<GenericTableColumn, GenericTable> { @Nullable @Override public DBSObjectCache<? extends DBSObject, GenericTableColumn> getObjectsCache(GenericTableColumn object) { return object.getParentObject().getContainer().getTableCache().getChildrenCache(object.getParentObject()); } @Override protected GenericTableColumn createDatabaseObject(DBRProgressMonitor monitor, DBECommandContext context, GenericTable parent, Object copyFrom) { DBSDataType columnType = findBestDataType(parent.getDataSource(), DBConstants.DEFAULT_DATATYPE_NAMES); final GenericTableColumn column = new GenericTableColumn(parent); column.setName(getNewColumnName(monitor, context, parent)); column.setTypeName(columnType == null ? "INTEGER" : columnType.getName()); column.setMaxLength(columnType != null && columnType.getDataKind() == DBPDataKind.STRING ? 100 : 0); column.setValueType(columnType == null ? Types.INTEGER : columnType.getTypeID()); column.setOrdinalPosition(-1); return column; } @Override public StringBuilder getNestedDeclaration(GenericTable owner, DBECommandAbstract<GenericTableColumn> command) { StringBuilder decl = super.getNestedDeclaration(owner, command); final GenericTableColumn column = command.getObject(); if (column.isAutoIncrement()) { final String autoIncrementClause = column.getDataSource().getMetaModel().getAutoIncrementClause(column); if (autoIncrementClause != null && !autoIncrementClause.isEmpty()) { decl.append(" ").append(autoIncrementClause); //$NON-NLS-1$ } } return decl; } @Override protected ColumnModifier[] getSupportedModifiers(GenericTableColumn column) { // According to SQL92 DEFAULT comes before constraints return new ColumnModifier[] {DataTypeModifier, DefaultModifier, NotNullModifier}; } @Override protected long getDDLFeatures(GenericTableColumn object) { long features = 0; Object shortDrop = object.getDataSource().getContainer().getDriver().getDriverParameter(GenericConstants.PARAM_DDL_DROP_COLUMN_SHORT); if (shortDrop != null && CommonUtils.toBoolean(shortDrop)) { features |= DDL_FEATURE_OMIT_COLUMN_CLAUSE_IN_DROP; } return features; } }
plugins/org.jkiss.dbeaver.ext.generic/src/org/jkiss/dbeaver/ext/generic/edit/GenericTableColumnManager.java
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.generic.edit; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.ext.generic.GenericConstants; import org.jkiss.dbeaver.ext.generic.model.GenericTable; import org.jkiss.dbeaver.ext.generic.model.GenericTableColumn; import org.jkiss.dbeaver.model.DBConstants; import org.jkiss.dbeaver.model.DBPDataKind; import org.jkiss.dbeaver.model.edit.DBECommandContext; import org.jkiss.dbeaver.model.impl.DBSObjectCache; import org.jkiss.dbeaver.model.impl.edit.DBECommandAbstract; import org.jkiss.dbeaver.model.impl.sql.edit.struct.SQLTableColumnManager; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSDataType; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.utils.CommonUtils; import java.sql.Types; /** * Generic table column manager */ public class GenericTableColumnManager extends SQLTableColumnManager<GenericTableColumn, GenericTable> { @Nullable @Override public DBSObjectCache<? extends DBSObject, GenericTableColumn> getObjectsCache(GenericTableColumn object) { return object.getParentObject().getContainer().getTableCache().getChildrenCache(object.getParentObject()); } @Override protected GenericTableColumn createDatabaseObject(DBRProgressMonitor monitor, DBECommandContext context, GenericTable parent, Object copyFrom) { DBSDataType columnType = findBestDataType(parent.getDataSource(), DBConstants.DEFAULT_DATATYPE_NAMES); final GenericTableColumn column = new GenericTableColumn(parent); column.setName(getNewColumnName(monitor, context, parent)); column.setTypeName(columnType == null ? "INTEGER" : columnType.getName()); column.setMaxLength(columnType != null && columnType.getDataKind() == DBPDataKind.STRING ? 100 : 0); column.setValueType(columnType == null ? Types.INTEGER : columnType.getTypeID()); column.setOrdinalPosition(-1); return column; } @Override public StringBuilder getNestedDeclaration(GenericTable owner, DBECommandAbstract<GenericTableColumn> command) { StringBuilder decl = super.getNestedDeclaration(owner, command); final GenericTableColumn column = command.getObject(); if (column.isAutoIncrement()) { final String autoIncrementClause = column.getDataSource().getMetaModel().getAutoIncrementClause(column); if (autoIncrementClause != null && !autoIncrementClause.isEmpty()) { decl.append(" ").append(autoIncrementClause); //$NON-NLS-1$ } } return decl; } @Override protected long getDDLFeatures(GenericTableColumn object) { long features = 0; Object shortDrop = object.getDataSource().getContainer().getDriver().getDriverParameter(GenericConstants.PARAM_DDL_DROP_COLUMN_SHORT); if (shortDrop != null && CommonUtils.toBoolean(shortDrop)) { features |= DDL_FEATURE_OMIT_COLUMN_CLAUSE_IN_DROP; } return features; } }
#2359 DDL fix - column DEFAULT/[NOT ]NULL order Former-commit-id: 0d559152dd965078f3e575006323bdfa93f6bd6b
plugins/org.jkiss.dbeaver.ext.generic/src/org/jkiss/dbeaver/ext/generic/edit/GenericTableColumnManager.java
#2359 DDL fix - column DEFAULT/[NOT ]NULL order
Java
apache-2.0
3c4fc70ce9e8e06f2bed2ad5b7a32843a69a904b
0
ppine7/kafka-elasticsearch-standalone-consumer,ppine7/kafka-elasticsearch-standalone-consumer,merlin-zaraza/kafka-elasticsearch-consumer,BigDataDevs/kafka-elasticsearch-consumer,reachkrishnaraj/kafka-elasticsearch-standalone-consumer,BigDataDevs/kafka-elasticsearch-consumer,dhyaneshm/kafka-elasticsearch-standalone-consumer,dhyaneshm/public-es-indexer,dhyaneshm/public-es-indexer,dhyaneshm/kafka-elasticsearch-standalone-consumer,merlin-zaraza/kafka-elasticsearch-consumer,reachkrishnaraj/kafka-elasticsearch-standalone-consumer
package org.elasticsearch.kafka.consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FailedEventsLogger { private static final Logger logger = LoggerFactory.getLogger(FailedEventsLogger.class); public static void logFailedEvent(String errorMsg, String event){ logger.error("General Error Processing Event: ERROR: {}, EVENT: {}", errorMsg, event); } public static void logFailedToPostToESEvent(String restResponse, String errorMsg){ logger.error("Error posting event to ES: REST response: {}, ERROR: {}", restResponse, errorMsg); } public static void logFailedToTransformEvent(long offset, String errorMsg, String event){ logger.error("Error transforming event: OFFSET: {}, ERROR: {}, EVENT: {}", offset, errorMsg, event); } }
src/main/java/org/elasticsearch/kafka/consumer/FailedEventsLogger.java
package org.elasticsearch.kafka.consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FailedEventsLogger { private static final Logger logger = LoggerFactory.getLogger(FailedEventsLogger.class); public static void logFailedEvent(String errorMsg, String event){ logger.error("General Error Processing Event: ERROR: {}, EVENT: {}", errorMsg, event); } public static void logFailedToPostToESEvent(String errorMsg, String event){ logger.error("Error posting event to ES: ERROR: {}, EVENT: {}", errorMsg, event); } public static void logFailedToTransformEvent(long offset, String errorMsg, String event){ logger.error("Error transforming event: ERROR: {}, OFFSET: {}, EVENT: {}", offset, errorMsg, event); } }
Fixed error messages
src/main/java/org/elasticsearch/kafka/consumer/FailedEventsLogger.java
Fixed error messages
Java
apache-2.0
13c662d1d31ce76c8563ca4ae0504baa68c7aa8b
0
symbiote-h2020/AuthenticationAuthorizationManager,symbiote-h2020/AuthenticationAuthorizationManager,symbiote-h2020/AuthenticationAuthorizationManager
package eu.h2020.symbiote.security.unit.credentialsvalidation; import com.rabbitmq.client.RpcClient; import eu.h2020.symbiote.security.AbstractAAMTestSuite; import eu.h2020.symbiote.security.commons.Certificate; import eu.h2020.symbiote.security.commons.SecurityConstants; import eu.h2020.symbiote.security.commons.Token; import eu.h2020.symbiote.security.commons.credentials.HomeCredentials; import eu.h2020.symbiote.security.commons.enums.ValidationStatus; import eu.h2020.symbiote.security.commons.exceptions.SecurityException; import eu.h2020.symbiote.security.commons.exceptions.custom.JWTCreationException; import eu.h2020.symbiote.security.commons.exceptions.custom.ValidationException; import eu.h2020.symbiote.security.commons.jwt.JWTEngine; import eu.h2020.symbiote.security.communication.payloads.Credentials; import eu.h2020.symbiote.security.communication.payloads.PlatformManagementRequest; import eu.h2020.symbiote.security.helpers.CryptoHelper; import eu.h2020.symbiote.security.repositories.UserRepository; import eu.h2020.symbiote.security.repositories.entities.Platform; import eu.h2020.symbiote.security.repositories.entities.SubjectsRevokedKeys; import eu.h2020.symbiote.security.repositories.entities.User; import eu.h2020.symbiote.security.services.helpers.TokenIssuer; import eu.h2020.symbiote.security.services.helpers.ValidationHelper; import eu.h2020.symbiote.security.utils.DummyPlatformAAM; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.context.annotation.Bean; import org.springframework.core.io.ClassPathResource; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.TestPropertySource; import org.springframework.web.client.RestTemplate; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.FileInputStream; import java.io.IOException; import java.io.StringWriter; import java.security.*; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Base64; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeoutException; import static org.junit.Assert.*; @TestPropertySource("/core.properties") @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public class CredentialsValidationInCoreAAMUnitTests extends AbstractAAMTestSuite { private static Log log = LogFactory.getLog(CredentialsValidationInCoreAAMUnitTests.class); // Leaf Certificate private static String applicationCertificatePEM = "-----BEGIN CERTIFICATE-----\n" + "MIIB6jCCAZCgAwIBAgIEWWyv1DAKBggqhkjOPQQDAjB0MRQwEgYJKoZIhvcNAQkB\n" + "FgVhQGIuYzENMAsGA1UECxMEdGVzdDENMAsGA1UEChMEdGVzdDENMAsGA1UEBxME\n" + "dGVzdDENMAsGA1UECBMEdGVzdDELMAkGA1UEBhMCUEwxEzARBgNVBAMTCnBsYXRm\n" + "b3JtLTEwHhcNMTcwNzE3MTIzODUxWhcNMTgwNzE3MTIzODUxWjCBhTEUMBIGCSqG\n" + "SIb3DQEJARYFYUBiLmMxCzAJBgNVBAYTAklUMQ0wCwYDVQQIDAR0ZXN0MQ0wCwYD\n" + "VQQHDAR0ZXN0MQ0wCwYDVQQKDAR0ZXN0MQ0wCwYDVQQLDAR0ZXN0MSQwIgYDVQQD\n" + "DBthcHBsaWNhdGlvbi1wbGF0Zm9ybS0xLTEtYzEwWTATBgcqhkjOPQIBBggqhkjO\n" + "PQMBBwNCAASGxfZa6ivSR4+BWBHRh94MNURAXBpBrZECvMH/rcgm8/aTHach6ncN\n" + "fw8VY2RNf3l/runJOQQH/3xGEisDIY7fMAoGCCqGSM49BAMCA0gAMEUCIDrJxAet\n" + "0IqR6aiJc87BS1faA8Ijl7kQnkphPOazKiXXAiEAoVHhBTNZACa4+2/0OsSg2k2P\n" + "jExF7CXu6SB/rvivAXk=\n" + "-----END CERTIFICATE-----\n"; // Intermediate Certificate (the good one) private static String rightSigningAAMCertificatePEM = "-----BEGIN CERTIFICATE-----\n" + "MIICBzCCAaqgAwIBAgIEW/ehcjAMBggqhkjOPQQDAgUAMEkxDTALBgNVBAcTBHRl\n" + "c3QxDTALBgNVBAoTBHRlc3QxDTALBgNVBAsTBHRlc3QxGjAYBgNVBAMMEVN5bWJJ\n" + "b1RlX0NvcmVfQUFNMB4XDTE3MDYxMzEwMjkxOVoXDTI3MDYxMTEwMjkxOVowdDEU\n" + "MBIGCSqGSIb3DQEJARYFYUBiLmMxDTALBgNVBAsTBHRlc3QxDTALBgNVBAoTBHRl\n" + "c3QxDTALBgNVBAcTBHRlc3QxDTALBgNVBAgTBHRlc3QxCzAJBgNVBAYTAlBMMRMw\n" + "EQYDVQQDEwpwbGF0Zm9ybS0xMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7eSa\n" + "IbqcQJsiQdfEzOZFnfUPejSJJCoTxI+vafbKWrrVRQSdKw0vV/Rddgu5IxVNqdWK\n" + "lkwirWlMZXLRGqfwh6NTMFEwHwYDVR0jBBgwFoAUNiFCbRtr/vdc4oaiASrBxosU\n" + "uZQwDwYDVR0TBAgwBgEB/wIBADAdBgNVHQ4EFgQUdxSdPTW56zEh0Wuqfx26J4ve\n" + "QWwwDAYIKoZIzj0EAwIFAANJADBGAiEAv/MmIW8g5I6dVOjoRins750rxnt9OcpP\n" + "VvOHShi5YqYCIQDRvpwyWySQ0U0LKjzob/GwqeYJ+6el8x1xbpJhs0Uweg==\n" + "-----END CERTIFICATE-----\n"; // Intermediate Certificate (the bad one) private static String wrongSigningAAMCertificatePEM = "-----BEGIN CERTIFICATE-----\n" + "MIIBrTCCAVOgAwIBAgIEWT/PizAKBggqhkjOPQQDAjBJMQ0wCwYDVQQHEwR0ZXN0\n" + "MQ0wCwYDVQQKEwR0ZXN0MQ0wCwYDVQQLEwR0ZXN0MRowGAYDVQQDDBFTeW1iSW9U\n" + "ZV9Db3JlX0FBTTAeFw0xNzA2MTMxMTQyMjVaFw0yNzA2MTMxMTQyMjVaMHQxFDAS\n" + "BgkqhkiG9w0BCQEWBWFAYi5jMQ0wCwYDVQQLEwR0ZXN0MQ0wCwYDVQQKEwR0ZXN0\n" + "MQ0wCwYDVQQHEwR0ZXN0MQ0wCwYDVQQIEwR0ZXN0MQswCQYDVQQGEwJQTDETMBEG\n" + "A1UEAxMKcGxhdGZvcm0tMTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABMaODIy1\n" + "sOOJdmd7stBIja4eGn9eKUEU/LVwocfiu6EW1pnZraI1Uqpu7t9CNjsFxWi/jDVg\n" + "kViBAy/bg9kzocMwCgYIKoZIzj0EAwIDSAAwRQIhAIBz2MJoERVLmYxs7P0B5dCn\n" + "yqWmjrYhosEiCUoVxIQVAiAwhZdM0XAeGGfTP2WsXGKFtcw/nL/gzvYSjAAGbkyx\n" + "sw==\n" + "-----END CERTIFICATE-----\n"; private final String preferredPlatformId = "preferredPlatformId"; private final String platformInstanceFriendlyName = "friendlyPlatformName"; private final String platformInterworkingInterfaceAddress = "https://platform1.eu:8101/someFancyHiddenPath/andHiddenAgain"; private final String platformOwnerUsername = "testPlatformOwnerUsername"; private final String platformOwnerPassword = "testPlatormOwnerPassword"; @Value("${rabbit.queue.ownedplatformdetails.request}") protected String ownedPlatformDetailsRequestQueue; @Autowired protected UserRepository userRepository; @Value("${aam.environment.platformAAMSuffixAtInterWorkingInterface}") String platformAAMSuffixAtInterWorkingInterface; @Value("${aam.environment.coreInterfaceAddress:https://localhost:8443}") String coreInterfaceAddress; @Autowired private ValidationHelper validationHelper; @LocalServerPort private int port; @Autowired private TokenIssuer tokenIssuer; private RpcClient platformRegistrationOverAMQPClient; private Credentials platformOwnerUserCredentials; private PlatformManagementRequest platformRegistrationOverAMQPRequest; @Bean DummyPlatformAAM getDummyPlatformAAM() { return new DummyPlatformAAM(); } @Override @Before public void setUp() throws Exception { super.setUp(); serverAddress = "https://localhost:" + port; // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Test rest template restTemplate = new RestTemplate(); // cleanup db //userRepository.deleteAll(); revokedKeysRepository.deleteAll(); revokedTokensRepository.deleteAll(); platformRepository.deleteAll(); userKeyPair = CryptoHelper.createKeyPair(); // platform registration useful platformRegistrationOverAMQPClient = new RpcClient(rabbitManager.getConnection().createChannel(), "", platformRegistrationRequestQueue, 5000); platformOwnerUserCredentials = new Credentials(platformOwnerUsername, platformOwnerPassword); platformRegistrationOverAMQPRequest = new PlatformManagementRequest(new Credentials(AAMOwnerUsername, AAMOwnerPassword), platformOwnerUserCredentials, platformInterworkingInterfaceAddress, platformInstanceFriendlyName, preferredPlatformId); addTestUserWithClientCertificateToRepository(); } @Test public void validateValidToken() throws SecurityException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, IOException, TimeoutException { // verify that app really is in repository User user = userRepository.findOne(username); assertNotNull(user); // verify the user keys are not yet revoked assertFalse(revokedKeysRepository.exists(username)); // acquiring valid token Token homeToken = tokenIssuer.getHomeToken(user, clientId); // check if home token is valid ValidationStatus response = validationHelper.validate(homeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.VALID, response); } @Test public void validateWrongToken() throws SecurityException, CertificateException { // verify that app really is in repository User user = userRepository.findOne(username); assertNotNull(user); // verify the user keys are not yet revoked assertFalse(revokedKeysRepository.exists(username)); //check if home token is valid ValidationStatus response = validationHelper.validate("tokenString", "", "", ""); assertEquals(ValidationStatus.UNKNOWN, response); } @Test public void validateExpiredToken() throws SecurityException, CertificateException, InterruptedException { // verify that app really is in repository User user = userRepository.findOne(username); assertNotNull(user); // verify the user keys are not yet revoked assertFalse(revokedKeysRepository.exists(username)); // acquiring valid token Token homeToken = tokenIssuer.getHomeToken(user, clientId); //Introduce latency so that JWT expires Thread.sleep(tokenValidityPeriod + 10); //check if home token is valid ValidationStatus response = validationHelper.validate(homeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.EXPIRED_TOKEN, response); } @Test public void validateAfterUnregistrationBySPK() throws SecurityException, CertificateException { // verify that app really is in repository User user = userRepository.findOne(username); assertNotNull(user); // verify the user keys are not yet revoked assertFalse(revokedKeysRepository.exists(username)); // acquiring valid token Token homeToken = tokenIssuer.getHomeToken(user, clientId); // unregister the user usersManagementService.unregister(username); //check if home token is valid ValidationStatus response = validationHelper.validate(homeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.REVOKED_SPK, response); } @Test public void validateRevokedToken() throws SecurityException, CertificateException { // verify that app really is in repository User user = userRepository.findOne(username); assertNotNull(user); // verify the user keys are not yet revoked assertFalse(revokedKeysRepository.exists(username)); // acquiring valid token Token homeToken = tokenIssuer.getHomeToken(user, clientId); // add token to revoked tokens repository revokedTokensRepository.save(homeToken); // check if home token is valid ValidationStatus response = validationHelper.validate(homeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.REVOKED_TOKEN, response); } @Test public void validateRevokedIPK() throws SecurityException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, IOException { // verify that app really is in repository User user = userRepository.findOne(username); assertNotNull(user); // verify the user keys are not yet revoked assertFalse(revokedKeysRepository.exists(username)); // acquiring valid token Token homeToken = tokenIssuer.getHomeToken(user, clientId); String issuer = JWTEngine.getClaims(homeToken.getToken()).getIssuer(); // verify the issuer keys are not yet revoked assertFalse(revokedKeysRepository.exists(issuer)); // insert CoreAAM public key into set to be revoked Certificate coreCertificate = new Certificate(certificationAuthorityHelper.getAAMCert()); Set<String> keySet = new HashSet<>(); keySet.add(Base64.getEncoder().encodeToString(coreCertificate.getX509().getPublicKey().getEncoded())); // adding key to revoked repository SubjectsRevokedKeys subjectsRevokedKeys = new SubjectsRevokedKeys(issuer, keySet); revokedKeysRepository.save(subjectsRevokedKeys); // check if home token is valid ValidationStatus response = validationHelper.validate(homeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.REVOKED_IPK, response); } @Test public void validateIssuerDiffersDeploymentIdAndRelayValidation() throws IOException, ValidationException, TimeoutException, NoSuchProviderException, KeyStoreException, CertificateException, NoSuchAlgorithmException, JWTCreationException { // issuing dummy platform token HomeCredentials homeCredentials = new HomeCredentials(null, username, clientId, null, userKeyPair.getPrivate()); String loginRequest = CryptoHelper.buildHomeTokenAcquisitionRequest(homeCredentials); ResponseEntity<String> loginResponse = restTemplate.postForEntity(serverAddress + "/test/paam" + SecurityConstants .AAM_GET_HOME_TOKEN, loginRequest, String.class); Token dummyHomeToken = new Token(loginResponse .getHeaders().get(SecurityConstants.TOKEN_HEADER_NAME).get(0)); String platformId = "platform-1"; savePlatformOwner(); // registering the platform to the Core AAM so it will be available for token revocation platformRegistrationOverAMQPRequest.setPlatformInstanceId(platformId); platformRegistrationOverAMQPRequest.setPlatformInterworkingInterfaceAddress(serverAddress + "/test"); // issue platform registration over AMQP platformRegistrationOverAMQPClient.primitiveCall(mapper.writeValueAsString (platformRegistrationOverAMQPRequest).getBytes()); //inject platform PEM Certificate to the database KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(new FileInputStream("./src/test/resources/platform_1.p12"), "1234567".toCharArray()); X509Certificate certificate = (X509Certificate) ks.getCertificate("platform-1-1-c1"); StringWriter signedCertificatePEMDataStringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(signedCertificatePEMDataStringWriter); pemWriter.writeObject(certificate); pemWriter.close(); String dummyPlatformAAMPEMCertString = signedCertificatePEMDataStringWriter.toString(); Platform dummyPlatform = platformRepository.findOne(platformId); dummyPlatform.setPlatformAAMCertificate(new Certificate(dummyPlatformAAMPEMCertString)); platformRepository.save(dummyPlatform); // check if validation will be relayed to appropriate issuer ValidationStatus response = validationHelper.validate(dummyHomeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.VALID, response); } @Test public void validateRevokedDummyCorePK() throws IOException, ValidationException, NoSuchProviderException, KeyStoreException, CertificateException, NoSuchAlgorithmException, JWTCreationException { // issuing dummy platform token HomeCredentials homeCredentials = new HomeCredentials(null, username, clientId, null, userKeyPair.getPrivate()); String loginRequest = CryptoHelper.buildHomeTokenAcquisitionRequest(homeCredentials); ResponseEntity<String> loginResponse = restTemplate.postForEntity(serverAddress + "/test/caam" + SecurityConstants .AAM_GET_HOME_TOKEN, loginRequest, String.class); Token dummyHomeToken = new Token(loginResponse .getHeaders().get(SecurityConstants.TOKEN_HEADER_NAME).get(0)); String platformId = "core-2"; //inject platform PEM Certificate to the database KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(new FileInputStream("./src/test/resources/core.p12"), "1234567".toCharArray()); X509Certificate certificate = (X509Certificate) ks.getCertificate(platformId); StringWriter signedCertificatePEMDataStringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(signedCertificatePEMDataStringWriter); pemWriter.writeObject(certificate); pemWriter.close(); String dummyPlatformAAMPEMCertString = signedCertificatePEMDataStringWriter.toString(); String issuer = JWTEngine.getClaims(dummyHomeToken.getToken()).getIssuer(); // verify the issuer keys are not yet revoked assertFalse(revokedKeysRepository.exists(issuer)); // insert DummyPlatformAAM public key into set to be revoked Set<String> keySet = new HashSet<>(); keySet.add(Base64.getEncoder().encodeToString( CryptoHelper.convertPEMToX509(dummyPlatformAAMPEMCertString).getPublicKey().getEncoded())); // adding key to revoked repository SubjectsRevokedKeys subjectsRevokedKeys = new SubjectsRevokedKeys(issuer, keySet); revokedKeysRepository.save(subjectsRevokedKeys); // check if platform token is is valid ValidationStatus response = validationHelper.validate(dummyHomeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.REVOKED_IPK, response); } @Test public void validateTokenFromDummyCoreByCore() throws IOException, ValidationException, NoSuchProviderException, KeyStoreException, CertificateException, NoSuchAlgorithmException, JWTCreationException { // issuing dummy platform token HomeCredentials homeCredentials = new HomeCredentials(null, username, clientId, null, userKeyPair.getPrivate()); String loginRequest = CryptoHelper.buildHomeTokenAcquisitionRequest(homeCredentials); ResponseEntity<String> loginResponse = restTemplate.postForEntity(serverAddress + "/test/caam" + SecurityConstants .AAM_GET_HOME_TOKEN, loginRequest, String.class); Token dummyHomeToken = new Token(loginResponse .getHeaders().get(SecurityConstants.TOKEN_HEADER_NAME).get(0)); String platformId = "core-2"; //inject platform PEM Certificate to the database KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(new FileInputStream("./src/test/resources/core.p12"), "1234567".toCharArray()); X509Certificate certificate = (X509Certificate) ks.getCertificate(platformId); StringWriter signedCertificatePEMDataStringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(signedCertificatePEMDataStringWriter); pemWriter.writeObject(certificate); pemWriter.close(); // check if platform token is valid ValidationStatus response = validationHelper.validate(dummyHomeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.INVALID_TRUST_CHAIN, response); } // test for relay @Test public void validateForeignTokenIssuerNotInAvailableAAMs() throws IOException, ValidationException, CertificateException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, JWTCreationException { // issuing dummy platform token HomeCredentials homeCredentials = new HomeCredentials(null, username, clientId, null, userKeyPair.getPrivate()); String loginRequest = CryptoHelper.buildHomeTokenAcquisitionRequest(homeCredentials); ResponseEntity<String> loginResponse = restTemplate.postForEntity(serverAddress + "/test/paam" + SecurityConstants .AAM_GET_HOME_TOKEN, loginRequest, String.class); Token dummyHomeToken = new Token(loginResponse .getHeaders().get(SecurityConstants.TOKEN_HEADER_NAME).get(0)); // check if home token is valid ValidationStatus response = validationHelper.validateRemotelyIssuedToken(dummyHomeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.INVALID_TRUST_CHAIN, response); } @Test public void validateForeignTokenRequestFails() throws IOException, ValidationException, TimeoutException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, JWTCreationException { // issuing dummy platform token HomeCredentials homeCredentials = new HomeCredentials(null, username, clientId, null, userKeyPair.getPrivate()); String loginRequest = CryptoHelper.buildHomeTokenAcquisitionRequest(homeCredentials); ResponseEntity<String> loginResponse = restTemplate.postForEntity(serverAddress + "/test/conn_err/paam" + SecurityConstants .AAM_GET_HOME_TOKEN, loginRequest, String.class); Token dummyHomeToken = new Token(loginResponse .getHeaders().get(SecurityConstants.TOKEN_HEADER_NAME).get(0)); String platformId = "testaam-connerr"; savePlatformOwner(); // registering the platform to the Core AAM so it will be available for token revocation platformRegistrationOverAMQPRequest.setPlatformInstanceId(platformId); platformRegistrationOverAMQPRequest.setPlatformInterworkingInterfaceAddress(serverAddress + "/test/conn_err"); // issue platform registration over AMQP platformRegistrationOverAMQPClient.primitiveCall(mapper.writeValueAsString (platformRegistrationOverAMQPRequest).getBytes()); //inject platform PEM Certificate to the database KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(new FileInputStream("./src/test/resources/platform_1.p12"), "1234567".toCharArray()); X509Certificate certificate = (X509Certificate) ks.getCertificate("platform-1-1-c1"); StringWriter signedCertificatePEMDataStringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(signedCertificatePEMDataStringWriter); pemWriter.writeObject(certificate); pemWriter.close(); String dummyPlatformAAMPEMCertString = signedCertificatePEMDataStringWriter.toString(); Platform dummyPlatform = platformRepository.findOne(platformId); dummyPlatform.setPlatformAAMCertificate(new Certificate(dummyPlatformAAMPEMCertString)); platformRepository.save(dummyPlatform); // check if validation will fail due to for example connection problems ValidationStatus response = validationHelper.validateRemotelyIssuedToken(dummyHomeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.WRONG_AAM, response); } @Test public void validateRemoteHomeTokenRequestInIntranetUsingProvidedCertificateSuccess() throws ValidationException, IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException { X509Certificate userCertificate = getCertificateFromTestKeystore("platform_1.p12", "userid@clientid@platform-1"); log.info("user: " + userCertificate.getSubjectDN()); log.info("user sign: " + userCertificate.getIssuerDN()); X509Certificate properAAMCert = getCertificateFromTestKeystore("platform_1.p12", "platform-1-1-c1"); log.info("proper AAM: " + properAAMCert.getSubjectDN()); log.info("proper AAM sign: " + properAAMCert.getIssuerDN()); X509Certificate wrongAAMCert = getCertificateFromTestKeystore("platform_1.p12", "platform-1-2-c1"); log.info("wrong AAM: " + wrongAAMCert.getSubjectDN()); log.info("wrong AAM sign: " + wrongAAMCert.getIssuerDN()); log.info("root CA: " + certificationAuthorityHelper.getRootCACertificate().getSubjectDN()); String testHomeToken = TokenIssuer.buildAuthorizationToken( "userId@clientId", new HashMap<>(), userCertificate.getPublicKey().getEncoded(), Token.Type.HOME, 100000l, "platform-1", properAAMCert.getPublicKey(), getPrivateKeyFromKeystore("platform_1.p12", "platform-1-1-c1") ); // valid remote home token chain assertEquals( ValidationStatus.VALID, validationHelper.validate( testHomeToken, CryptoHelper.convertX509ToPEM(userCertificate), CryptoHelper.convertX509ToPEM(properAAMCert), "") ); } @Test public void validateRemoteHomeTokenRequestInIntranetUsingProvidedCertificateISSMismatch() throws ValidationException, IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException { X509Certificate userCertificate = getCertificateFromTestKeystore("platform_1.p12", "userid@clientid@platform-1"); X509Certificate properAAMCert = getCertificateFromTestKeystore("platform_1.p12", "platform-1-1-c1"); String testHomeToken = TokenIssuer.buildAuthorizationToken( "userId@clientId", new HashMap<>(), userCertificate.getPublicKey().getEncoded(), Token.Type.HOME, 100000l, "bad_issuer", // mismatch token ISS properAAMCert.getPublicKey(), getPrivateKeyFromKeystore("platform_1.p12", "platform-1-1-c1") ); assertEquals( ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate( testHomeToken, CryptoHelper.convertX509ToPEM(userCertificate), CryptoHelper.convertX509ToPEM(properAAMCert), "") ); } @Test public void validateRemoteHomeTokenRequestInIntranetUsingProvidedCertificateIPKMismatch() throws ValidationException, IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException { X509Certificate userCertificate = getCertificateFromTestKeystore("platform_1.p12", "userid@clientid@platform-1"); X509Certificate properAAMCert = getCertificateFromTestKeystore("platform_1.p12", "platform-1-1-c1"); X509Certificate wrongAAMCert = getCertificateFromTestKeystore("platform_1.p12", "platform-1-2-c1"); String testHomeToken = TokenIssuer.buildAuthorizationToken( "userId@clientId", new HashMap<>(), userCertificate.getPublicKey().getEncoded(), Token.Type.HOME, 100000l, "platform-1", wrongAAMCert.getPublicKey(), // mismatch token IPK getPrivateKeyFromKeystore("platform_1.p12", "platform-1-2-c1") ); assertEquals( ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate( testHomeToken, CryptoHelper.convertX509ToPEM(userCertificate), CryptoHelper.convertX509ToPEM(properAAMCert), "") ); } @Test public void validateRemoteHomeTokenRequestInIntranetUsingProvidedCertificateSignatureMismatch() throws ValidationException, IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException { X509Certificate userCertificate = getCertificateFromTestKeystore("platform_1.p12", "userid@clientid@platform-1"); X509Certificate properAAMCert = getCertificateFromTestKeystore("platform_1.p12", "platform-1-1-c1"); String testHomeToken = TokenIssuer.buildAuthorizationToken( "userId@clientId", new HashMap<>(), userCertificate.getPublicKey().getEncoded(), Token.Type.HOME, 100000l, "platform-1", properAAMCert.getPublicKey(), getPrivateKeyFromKeystore("platform_1.p12", "platform-1-2-c1") // token signature mismatch ); assertEquals( ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate( testHomeToken, CryptoHelper.convertX509ToPEM(userCertificate), CryptoHelper.convertX509ToPEM(properAAMCert), "") ); } @Test public void validateRemoteHomeTokenRequestInIntranetUsingProvidedCertificateSPKMismatch() throws ValidationException, IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException { X509Certificate userCertificate = getCertificateFromTestKeystore("platform_1.p12", "userid@clientid@platform-1"); X509Certificate properAAMCert = getCertificateFromTestKeystore("platform_1.p12", "platform-1-1-c1"); String testHomeToken = TokenIssuer.buildAuthorizationToken( "userId@clientId", new HashMap<>(), properAAMCert.getPublicKey().getEncoded(), // mismatch token SPK Token.Type.HOME, 100000l, "platform-1", properAAMCert.getPublicKey(), getPrivateKeyFromKeystore("platform_1.p12", "platform-1-1-c1") ); assertEquals( ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate( testHomeToken, CryptoHelper.convertX509ToPEM(userCertificate), CryptoHelper.convertX509ToPEM(properAAMCert), "") ); } @Test public void validateRemoteHomeTokenRequestInIntranetUsingProvidedCertificateSUBMismatch() throws ValidationException, IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException { X509Certificate userCertificate = getCertificateFromTestKeystore("platform_1.p12", "userid@clientid@platform-1"); X509Certificate properAAMCert = getCertificateFromTestKeystore("platform_1.p12", "platform-1-1-c1"); String testHomeToken = TokenIssuer.buildAuthorizationToken( "bad_token_sub", // mismatch token SUB new HashMap<>(), userCertificate.getPublicKey().getEncoded(), Token.Type.HOME, 100000l, "platform-1", properAAMCert.getPublicKey(), getPrivateKeyFromKeystore("platform_1.p12", "platform-1-1-c1") ); assertEquals( ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate( testHomeToken, CryptoHelper.convertX509ToPEM(userCertificate), CryptoHelper.convertX509ToPEM(properAAMCert), "") ); } @Test public void validateRemoteHomeTokenRequestInIntranetUsingProvidedCertificateChainMismatch() throws ValidationException, IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException { X509Certificate userCertificate = getCertificateFromTestKeystore("platform_1.p12", "userid@clientid@platform-1"); X509Certificate properAAMCert = getCertificateFromTestKeystore("platform_1.p12", "platform-1-1-c1"); X509Certificate wrongAAMCert = getCertificateFromTestKeystore("platform_1.p12", "platform-1-2-c1"); String testHomeToken = TokenIssuer.buildAuthorizationToken( "userId@clientId", new HashMap<>(), userCertificate.getPublicKey().getEncoded(), Token.Type.HOME, 100000l, "platform-1", properAAMCert.getPublicKey(), getPrivateKeyFromKeystore("platform_1.p12", "platform-1-1-c1") ); assertEquals( ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate( testHomeToken, CryptoHelper.convertX509ToPEM(userCertificate), CryptoHelper.convertX509ToPEM(wrongAAMCert), "") ); } @Test public void validateRemoteHomeTokenRequestInIntranetUsingProvidedCertificateMissingChainElement() throws ValidationException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, KeyStoreException, IOException, UnrecoverableKeyException { X509Certificate userCertificate = getCertificateFromTestKeystore("platform_1.p12", "userid@clientid@platform-1"); X509Certificate properAAMCert = getCertificateFromTestKeystore("platform_1.p12", "platform-1-1-c1"); String testHomeToken = TokenIssuer.buildAuthorizationToken( "userId@clientId", new HashMap<>(), userCertificate.getPublicKey().getEncoded(), Token.Type.HOME, 100000l, "platform-1", properAAMCert.getPublicKey(), getPrivateKeyFromKeystore("platform_1.p12", "platform-1-1-c1") ); assertEquals( ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate( testHomeToken, CryptoHelper.convertX509ToPEM(userCertificate), "", "") ); assertEquals( ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate( testHomeToken, "", "", "") ); } @Test @Ignore("offline validation WIP") public void validateRemoteForeignTokenRequestInIntranetUsingProvidedCertificate() throws ValidationException { // issuing dummy platform token HomeCredentials homeCredentials = new HomeCredentials(null, username, clientId, null, userKeyPair.getPrivate()); String loginRequest = CryptoHelper.buildHomeTokenAcquisitionRequest(homeCredentials); ResponseEntity<String> loginResponse = restTemplate.postForEntity(serverAddress + "/test/conn_err/paam" + SecurityConstants .AAM_GET_HOME_TOKEN, loginRequest, String.class); Token dummyHomeToken = new Token(loginResponse .getHeaders().get(SecurityConstants.TOKEN_HEADER_NAME).get(0)); // check if validation will use certificate instead of relay for offline configured aam // TODO valid chain // assertEquals(ValidationStatus.VALID, validationHelper.validateRemotelyIssuedToken(dummyHomeToken.getToken(), applicationCertificatePEM, rightSigningAAMCertificatePEM)); // wrong chain (signing cert) assertEquals(ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate(dummyHomeToken.getToken(), applicationCertificatePEM, wrongSigningAAMCertificatePEM, "TODO")); // wrong chain (token and clientCertificate don't match) assertEquals(ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate(dummyHomeToken.getToken(), applicationCertificatePEM, rightSigningAAMCertificatePEM, "TODO")); // missing certificate triggers remote validation attempt assertEquals(ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate(dummyHomeToken.getToken(), applicationCertificatePEM, "", "TODO")); } @Test public void validateCertificateChainSuccess() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, IOException { assertTrue(validationHelper.isClientCertificateChainTrusted(rightSigningAAMCertificatePEM, applicationCertificatePEM)); } @Test public void validateCertificateChainFailure() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, IOException { assertFalse(validationHelper.isClientCertificateChainTrusted(wrongSigningAAMCertificatePEM, applicationCertificatePEM)); } private X509Certificate getCertificateFromTestKeystore(String keyStoreName, String certificateAlias) throws NoSuchProviderException, KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { KeyStore pkcs12Store = KeyStore.getInstance("PKCS12", "BC"); pkcs12Store.load(new ClassPathResource(keyStoreName).getInputStream(), KEY_STORE_PASSWORD.toCharArray()); return (X509Certificate) pkcs12Store.getCertificate(certificateAlias); } public PrivateKey getPrivateKeyFromKeystore(String keyStoreName, String certificateAlias) throws NoSuchProviderException, KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException { KeyStore pkcs12Store = KeyStore.getInstance("PKCS12", "BC"); pkcs12Store.load(new ClassPathResource(keyStoreName).getInputStream(), KEY_STORE_PASSWORD.toCharArray()); return (PrivateKey) pkcs12Store.getKey(certificateAlias, PV_KEY_PASSWORD.toCharArray()); } }
src/test/java/eu/h2020/symbiote/security/unit/credentialsvalidation/CredentialsValidationInCoreAAMUnitTests.java
package eu.h2020.symbiote.security.unit.credentialsvalidation; import com.rabbitmq.client.RpcClient; import eu.h2020.symbiote.security.AbstractAAMTestSuite; import eu.h2020.symbiote.security.commons.Certificate; import eu.h2020.symbiote.security.commons.SecurityConstants; import eu.h2020.symbiote.security.commons.Token; import eu.h2020.symbiote.security.commons.credentials.HomeCredentials; import eu.h2020.symbiote.security.commons.enums.ValidationStatus; import eu.h2020.symbiote.security.commons.exceptions.SecurityException; import eu.h2020.symbiote.security.commons.exceptions.custom.JWTCreationException; import eu.h2020.symbiote.security.commons.exceptions.custom.ValidationException; import eu.h2020.symbiote.security.commons.jwt.JWTEngine; import eu.h2020.symbiote.security.communication.payloads.Credentials; import eu.h2020.symbiote.security.communication.payloads.PlatformManagementRequest; import eu.h2020.symbiote.security.helpers.CryptoHelper; import eu.h2020.symbiote.security.repositories.UserRepository; import eu.h2020.symbiote.security.repositories.entities.Platform; import eu.h2020.symbiote.security.repositories.entities.SubjectsRevokedKeys; import eu.h2020.symbiote.security.repositories.entities.User; import eu.h2020.symbiote.security.services.helpers.TokenIssuer; import eu.h2020.symbiote.security.services.helpers.ValidationHelper; import eu.h2020.symbiote.security.utils.DummyPlatformAAM; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.context.annotation.Bean; import org.springframework.core.io.ClassPathResource; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.TestPropertySource; import org.springframework.web.client.RestTemplate; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.FileInputStream; import java.io.IOException; import java.io.StringWriter; import java.security.*; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Base64; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeoutException; import static org.junit.Assert.*; @TestPropertySource("/core.properties") @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public class CredentialsValidationInCoreAAMUnitTests extends AbstractAAMTestSuite { private static Log log = LogFactory.getLog(CredentialsValidationInCoreAAMUnitTests.class); // Leaf Certificate private static String applicationCertificatePEM = "-----BEGIN CERTIFICATE-----\n" + "MIIB6jCCAZCgAwIBAgIEWWyv1DAKBggqhkjOPQQDAjB0MRQwEgYJKoZIhvcNAQkB\n" + "FgVhQGIuYzENMAsGA1UECxMEdGVzdDENMAsGA1UEChMEdGVzdDENMAsGA1UEBxME\n" + "dGVzdDENMAsGA1UECBMEdGVzdDELMAkGA1UEBhMCUEwxEzARBgNVBAMTCnBsYXRm\n" + "b3JtLTEwHhcNMTcwNzE3MTIzODUxWhcNMTgwNzE3MTIzODUxWjCBhTEUMBIGCSqG\n" + "SIb3DQEJARYFYUBiLmMxCzAJBgNVBAYTAklUMQ0wCwYDVQQIDAR0ZXN0MQ0wCwYD\n" + "VQQHDAR0ZXN0MQ0wCwYDVQQKDAR0ZXN0MQ0wCwYDVQQLDAR0ZXN0MSQwIgYDVQQD\n" + "DBthcHBsaWNhdGlvbi1wbGF0Zm9ybS0xLTEtYzEwWTATBgcqhkjOPQIBBggqhkjO\n" + "PQMBBwNCAASGxfZa6ivSR4+BWBHRh94MNURAXBpBrZECvMH/rcgm8/aTHach6ncN\n" + "fw8VY2RNf3l/runJOQQH/3xGEisDIY7fMAoGCCqGSM49BAMCA0gAMEUCIDrJxAet\n" + "0IqR6aiJc87BS1faA8Ijl7kQnkphPOazKiXXAiEAoVHhBTNZACa4+2/0OsSg2k2P\n" + "jExF7CXu6SB/rvivAXk=\n" + "-----END CERTIFICATE-----\n"; // Intermediate Certificate (the good one) private static String rightSigningAAMCertificatePEM = "-----BEGIN CERTIFICATE-----\n" + "MIICBzCCAaqgAwIBAgIEW/ehcjAMBggqhkjOPQQDAgUAMEkxDTALBgNVBAcTBHRl\n" + "c3QxDTALBgNVBAoTBHRlc3QxDTALBgNVBAsTBHRlc3QxGjAYBgNVBAMMEVN5bWJJ\n" + "b1RlX0NvcmVfQUFNMB4XDTE3MDYxMzEwMjkxOVoXDTI3MDYxMTEwMjkxOVowdDEU\n" + "MBIGCSqGSIb3DQEJARYFYUBiLmMxDTALBgNVBAsTBHRlc3QxDTALBgNVBAoTBHRl\n" + "c3QxDTALBgNVBAcTBHRlc3QxDTALBgNVBAgTBHRlc3QxCzAJBgNVBAYTAlBMMRMw\n" + "EQYDVQQDEwpwbGF0Zm9ybS0xMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7eSa\n" + "IbqcQJsiQdfEzOZFnfUPejSJJCoTxI+vafbKWrrVRQSdKw0vV/Rddgu5IxVNqdWK\n" + "lkwirWlMZXLRGqfwh6NTMFEwHwYDVR0jBBgwFoAUNiFCbRtr/vdc4oaiASrBxosU\n" + "uZQwDwYDVR0TBAgwBgEB/wIBADAdBgNVHQ4EFgQUdxSdPTW56zEh0Wuqfx26J4ve\n" + "QWwwDAYIKoZIzj0EAwIFAANJADBGAiEAv/MmIW8g5I6dVOjoRins750rxnt9OcpP\n" + "VvOHShi5YqYCIQDRvpwyWySQ0U0LKjzob/GwqeYJ+6el8x1xbpJhs0Uweg==\n" + "-----END CERTIFICATE-----\n"; // Intermediate Certificate (the bad one) private static String wrongSigningAAMCertificatePEM = "-----BEGIN CERTIFICATE-----\n" + "MIIBrTCCAVOgAwIBAgIEWT/PizAKBggqhkjOPQQDAjBJMQ0wCwYDVQQHEwR0ZXN0\n" + "MQ0wCwYDVQQKEwR0ZXN0MQ0wCwYDVQQLEwR0ZXN0MRowGAYDVQQDDBFTeW1iSW9U\n" + "ZV9Db3JlX0FBTTAeFw0xNzA2MTMxMTQyMjVaFw0yNzA2MTMxMTQyMjVaMHQxFDAS\n" + "BgkqhkiG9w0BCQEWBWFAYi5jMQ0wCwYDVQQLEwR0ZXN0MQ0wCwYDVQQKEwR0ZXN0\n" + "MQ0wCwYDVQQHEwR0ZXN0MQ0wCwYDVQQIEwR0ZXN0MQswCQYDVQQGEwJQTDETMBEG\n" + "A1UEAxMKcGxhdGZvcm0tMTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABMaODIy1\n" + "sOOJdmd7stBIja4eGn9eKUEU/LVwocfiu6EW1pnZraI1Uqpu7t9CNjsFxWi/jDVg\n" + "kViBAy/bg9kzocMwCgYIKoZIzj0EAwIDSAAwRQIhAIBz2MJoERVLmYxs7P0B5dCn\n" + "yqWmjrYhosEiCUoVxIQVAiAwhZdM0XAeGGfTP2WsXGKFtcw/nL/gzvYSjAAGbkyx\n" + "sw==\n" + "-----END CERTIFICATE-----\n"; private final String preferredPlatformId = "preferredPlatformId"; private final String platformInstanceFriendlyName = "friendlyPlatformName"; private final String platformInterworkingInterfaceAddress = "https://platform1.eu:8101/someFancyHiddenPath/andHiddenAgain"; private final String platformOwnerUsername = "testPlatformOwnerUsername"; private final String platformOwnerPassword = "testPlatormOwnerPassword"; @Value("${rabbit.queue.ownedplatformdetails.request}") protected String ownedPlatformDetailsRequestQueue; @Autowired protected UserRepository userRepository; @Value("${aam.environment.platformAAMSuffixAtInterWorkingInterface}") String platformAAMSuffixAtInterWorkingInterface; @Value("${aam.environment.coreInterfaceAddress:https://localhost:8443}") String coreInterfaceAddress; @Autowired private ValidationHelper validationHelper; @LocalServerPort private int port; @Autowired private TokenIssuer tokenIssuer; private RpcClient platformRegistrationOverAMQPClient; private Credentials platformOwnerUserCredentials; private PlatformManagementRequest platformRegistrationOverAMQPRequest; @Bean DummyPlatformAAM getDummyPlatformAAM() { return new DummyPlatformAAM(); } @Override @Before public void setUp() throws Exception { super.setUp(); serverAddress = "https://localhost:" + port; // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Test rest template restTemplate = new RestTemplate(); // cleanup db //userRepository.deleteAll(); revokedKeysRepository.deleteAll(); revokedTokensRepository.deleteAll(); platformRepository.deleteAll(); userKeyPair = CryptoHelper.createKeyPair(); // platform registration useful platformRegistrationOverAMQPClient = new RpcClient(rabbitManager.getConnection().createChannel(), "", platformRegistrationRequestQueue, 5000); platformOwnerUserCredentials = new Credentials(platformOwnerUsername, platformOwnerPassword); platformRegistrationOverAMQPRequest = new PlatformManagementRequest(new Credentials(AAMOwnerUsername, AAMOwnerPassword), platformOwnerUserCredentials, platformInterworkingInterfaceAddress, platformInstanceFriendlyName, preferredPlatformId); addTestUserWithClientCertificateToRepository(); } @Test public void validateValidToken() throws SecurityException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, IOException, TimeoutException { // verify that app really is in repository User user = userRepository.findOne(username); assertNotNull(user); // verify the user keys are not yet revoked assertFalse(revokedKeysRepository.exists(username)); // acquiring valid token Token homeToken = tokenIssuer.getHomeToken(user, clientId); // check if home token is valid ValidationStatus response = validationHelper.validate(homeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.VALID, response); } @Test public void validateWrongToken() throws SecurityException, CertificateException { // verify that app really is in repository User user = userRepository.findOne(username); assertNotNull(user); // verify the user keys are not yet revoked assertFalse(revokedKeysRepository.exists(username)); //check if home token is valid ValidationStatus response = validationHelper.validate("tokenString", "", "", ""); assertEquals(ValidationStatus.UNKNOWN, response); } @Test public void validateExpiredToken() throws SecurityException, CertificateException, InterruptedException { // verify that app really is in repository User user = userRepository.findOne(username); assertNotNull(user); // verify the user keys are not yet revoked assertFalse(revokedKeysRepository.exists(username)); // acquiring valid token Token homeToken = tokenIssuer.getHomeToken(user, clientId); //Introduce latency so that JWT expires Thread.sleep(tokenValidityPeriod + 10); //check if home token is valid ValidationStatus response = validationHelper.validate(homeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.EXPIRED_TOKEN, response); } @Test public void validateAfterUnregistrationBySPK() throws SecurityException, CertificateException { // verify that app really is in repository User user = userRepository.findOne(username); assertNotNull(user); // verify the user keys are not yet revoked assertFalse(revokedKeysRepository.exists(username)); // acquiring valid token Token homeToken = tokenIssuer.getHomeToken(user, clientId); // unregister the user usersManagementService.unregister(username); //check if home token is valid ValidationStatus response = validationHelper.validate(homeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.REVOKED_SPK, response); } @Test public void validateRevokedToken() throws SecurityException, CertificateException { // verify that app really is in repository User user = userRepository.findOne(username); assertNotNull(user); // verify the user keys are not yet revoked assertFalse(revokedKeysRepository.exists(username)); // acquiring valid token Token homeToken = tokenIssuer.getHomeToken(user, clientId); // add token to revoked tokens repository revokedTokensRepository.save(homeToken); // check if home token is valid ValidationStatus response = validationHelper.validate(homeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.REVOKED_TOKEN, response); } @Test public void validateRevokedIPK() throws SecurityException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, IOException { // verify that app really is in repository User user = userRepository.findOne(username); assertNotNull(user); // verify the user keys are not yet revoked assertFalse(revokedKeysRepository.exists(username)); // acquiring valid token Token homeToken = tokenIssuer.getHomeToken(user, clientId); String issuer = JWTEngine.getClaims(homeToken.getToken()).getIssuer(); // verify the issuer keys are not yet revoked assertFalse(revokedKeysRepository.exists(issuer)); // insert CoreAAM public key into set to be revoked Certificate coreCertificate = new Certificate(certificationAuthorityHelper.getAAMCert()); Set<String> keySet = new HashSet<>(); keySet.add(Base64.getEncoder().encodeToString(coreCertificate.getX509().getPublicKey().getEncoded())); // adding key to revoked repository SubjectsRevokedKeys subjectsRevokedKeys = new SubjectsRevokedKeys(issuer, keySet); revokedKeysRepository.save(subjectsRevokedKeys); // check if home token is valid ValidationStatus response = validationHelper.validate(homeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.REVOKED_IPK, response); } @Test public void validateIssuerDiffersDeploymentIdAndRelayValidation() throws IOException, ValidationException, TimeoutException, NoSuchProviderException, KeyStoreException, CertificateException, NoSuchAlgorithmException, JWTCreationException { // issuing dummy platform token HomeCredentials homeCredentials = new HomeCredentials(null, username, clientId, null, userKeyPair.getPrivate()); String loginRequest = CryptoHelper.buildHomeTokenAcquisitionRequest(homeCredentials); ResponseEntity<String> loginResponse = restTemplate.postForEntity(serverAddress + "/test/paam" + SecurityConstants .AAM_GET_HOME_TOKEN, loginRequest, String.class); Token dummyHomeToken = new Token(loginResponse .getHeaders().get(SecurityConstants.TOKEN_HEADER_NAME).get(0)); String platformId = "platform-1"; savePlatformOwner(); // registering the platform to the Core AAM so it will be available for token revocation platformRegistrationOverAMQPRequest.setPlatformInstanceId(platformId); platformRegistrationOverAMQPRequest.setPlatformInterworkingInterfaceAddress(serverAddress + "/test"); // issue platform registration over AMQP platformRegistrationOverAMQPClient.primitiveCall(mapper.writeValueAsString (platformRegistrationOverAMQPRequest).getBytes()); //inject platform PEM Certificate to the database KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(new FileInputStream("./src/test/resources/platform_1.p12"), "1234567".toCharArray()); X509Certificate certificate = (X509Certificate) ks.getCertificate("platform-1-1-c1"); StringWriter signedCertificatePEMDataStringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(signedCertificatePEMDataStringWriter); pemWriter.writeObject(certificate); pemWriter.close(); String dummyPlatformAAMPEMCertString = signedCertificatePEMDataStringWriter.toString(); Platform dummyPlatform = platformRepository.findOne(platformId); dummyPlatform.setPlatformAAMCertificate(new Certificate(dummyPlatformAAMPEMCertString)); platformRepository.save(dummyPlatform); // check if validation will be relayed to appropriate issuer ValidationStatus response = validationHelper.validate(dummyHomeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.VALID, response); } @Test public void validateRevokedDummyCorePK() throws IOException, ValidationException, NoSuchProviderException, KeyStoreException, CertificateException, NoSuchAlgorithmException, JWTCreationException { // issuing dummy platform token HomeCredentials homeCredentials = new HomeCredentials(null, username, clientId, null, userKeyPair.getPrivate()); String loginRequest = CryptoHelper.buildHomeTokenAcquisitionRequest(homeCredentials); ResponseEntity<String> loginResponse = restTemplate.postForEntity(serverAddress + "/test/caam" + SecurityConstants .AAM_GET_HOME_TOKEN, loginRequest, String.class); Token dummyHomeToken = new Token(loginResponse .getHeaders().get(SecurityConstants.TOKEN_HEADER_NAME).get(0)); String platformId = "core-2"; //inject platform PEM Certificate to the database KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(new FileInputStream("./src/test/resources/core.p12"), "1234567".toCharArray()); X509Certificate certificate = (X509Certificate) ks.getCertificate(platformId); StringWriter signedCertificatePEMDataStringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(signedCertificatePEMDataStringWriter); pemWriter.writeObject(certificate); pemWriter.close(); String dummyPlatformAAMPEMCertString = signedCertificatePEMDataStringWriter.toString(); String issuer = JWTEngine.getClaims(dummyHomeToken.getToken()).getIssuer(); // verify the issuer keys are not yet revoked assertFalse(revokedKeysRepository.exists(issuer)); // insert DummyPlatformAAM public key into set to be revoked Set<String> keySet = new HashSet<>(); keySet.add(Base64.getEncoder().encodeToString( CryptoHelper.convertPEMToX509(dummyPlatformAAMPEMCertString).getPublicKey().getEncoded())); // adding key to revoked repository SubjectsRevokedKeys subjectsRevokedKeys = new SubjectsRevokedKeys(issuer, keySet); revokedKeysRepository.save(subjectsRevokedKeys); // check if platform token is is valid ValidationStatus response = validationHelper.validate(dummyHomeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.REVOKED_IPK, response); } @Test public void validateTokenFromDummyCoreByCore() throws IOException, ValidationException, NoSuchProviderException, KeyStoreException, CertificateException, NoSuchAlgorithmException, JWTCreationException { // issuing dummy platform token HomeCredentials homeCredentials = new HomeCredentials(null, username, clientId, null, userKeyPair.getPrivate()); String loginRequest = CryptoHelper.buildHomeTokenAcquisitionRequest(homeCredentials); ResponseEntity<String> loginResponse = restTemplate.postForEntity(serverAddress + "/test/caam" + SecurityConstants .AAM_GET_HOME_TOKEN, loginRequest, String.class); Token dummyHomeToken = new Token(loginResponse .getHeaders().get(SecurityConstants.TOKEN_HEADER_NAME).get(0)); String platformId = "core-2"; //inject platform PEM Certificate to the database KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(new FileInputStream("./src/test/resources/core.p12"), "1234567".toCharArray()); X509Certificate certificate = (X509Certificate) ks.getCertificate(platformId); StringWriter signedCertificatePEMDataStringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(signedCertificatePEMDataStringWriter); pemWriter.writeObject(certificate); pemWriter.close(); // check if platform token is valid ValidationStatus response = validationHelper.validate(dummyHomeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.INVALID_TRUST_CHAIN, response); } // test for relay @Test public void validateForeignTokenIssuerNotInAvailableAAMs() throws IOException, ValidationException, CertificateException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, JWTCreationException { // issuing dummy platform token HomeCredentials homeCredentials = new HomeCredentials(null, username, clientId, null, userKeyPair.getPrivate()); String loginRequest = CryptoHelper.buildHomeTokenAcquisitionRequest(homeCredentials); ResponseEntity<String> loginResponse = restTemplate.postForEntity(serverAddress + "/test/paam" + SecurityConstants .AAM_GET_HOME_TOKEN, loginRequest, String.class); Token dummyHomeToken = new Token(loginResponse .getHeaders().get(SecurityConstants.TOKEN_HEADER_NAME).get(0)); // check if home token is valid ValidationStatus response = validationHelper.validateRemotelyIssuedToken(dummyHomeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.INVALID_TRUST_CHAIN, response); } @Test public void validateForeignTokenRequestFails() throws IOException, ValidationException, TimeoutException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, JWTCreationException { // issuing dummy platform token HomeCredentials homeCredentials = new HomeCredentials(null, username, clientId, null, userKeyPair.getPrivate()); String loginRequest = CryptoHelper.buildHomeTokenAcquisitionRequest(homeCredentials); ResponseEntity<String> loginResponse = restTemplate.postForEntity(serverAddress + "/test/conn_err/paam" + SecurityConstants .AAM_GET_HOME_TOKEN, loginRequest, String.class); Token dummyHomeToken = new Token(loginResponse .getHeaders().get(SecurityConstants.TOKEN_HEADER_NAME).get(0)); String platformId = "testaam-connerr"; savePlatformOwner(); // registering the platform to the Core AAM so it will be available for token revocation platformRegistrationOverAMQPRequest.setPlatformInstanceId(platformId); platformRegistrationOverAMQPRequest.setPlatformInterworkingInterfaceAddress(serverAddress + "/test/conn_err"); // issue platform registration over AMQP platformRegistrationOverAMQPClient.primitiveCall(mapper.writeValueAsString (platformRegistrationOverAMQPRequest).getBytes()); //inject platform PEM Certificate to the database KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(new FileInputStream("./src/test/resources/platform_1.p12"), "1234567".toCharArray()); X509Certificate certificate = (X509Certificate) ks.getCertificate("platform-1-1-c1"); StringWriter signedCertificatePEMDataStringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(signedCertificatePEMDataStringWriter); pemWriter.writeObject(certificate); pemWriter.close(); String dummyPlatformAAMPEMCertString = signedCertificatePEMDataStringWriter.toString(); Platform dummyPlatform = platformRepository.findOne(platformId); dummyPlatform.setPlatformAAMCertificate(new Certificate(dummyPlatformAAMPEMCertString)); platformRepository.save(dummyPlatform); // check if validation will fail due to for example connection problems ValidationStatus response = validationHelper.validateRemotelyIssuedToken(dummyHomeToken.getToken(), "", "", ""); assertEquals(ValidationStatus.WRONG_AAM, response); } @Test public void validateRemoteHomeTokenRequestInIntranetUsingProvidedCertificateSuccess() throws ValidationException, IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException { X509Certificate userCertificate = getCertificateFromTestKeystore("platform_1.p12", "userid@clientid@platform-1"); log.info("user: " + userCertificate.getSubjectDN()); log.info("user sign: " + userCertificate.getIssuerDN()); X509Certificate properAAMCert = getCertificateFromTestKeystore("platform_1.p12", "platform-1-1-c1"); log.info("proper AAM: " + properAAMCert.getSubjectDN()); log.info("proper AAM sign: " + properAAMCert.getIssuerDN()); X509Certificate wrongAAMCert = getCertificateFromTestKeystore("platform_1.p12", "platform-1-2-c1"); log.info("wrong AAM: " + wrongAAMCert.getSubjectDN()); log.info("wrong AAM sign: " + wrongAAMCert.getIssuerDN()); log.info("root CA: " + certificationAuthorityHelper.getRootCACertificate().getSubjectDN()); String testHomeToken = TokenIssuer.buildAuthorizationToken( "userId@clientId", new HashMap<>(), userCertificate.getPublicKey().getEncoded(), Token.Type.HOME, 100000l, "platform-1", properAAMCert.getPublicKey(), getPrivateKeyFromKeystore("platform_1.p12", "platform-1-1-c1") ); // valid remote home token chain assertEquals( ValidationStatus.VALID, validationHelper.validate( testHomeToken, CryptoHelper.convertX509ToPEM(userCertificate), CryptoHelper.convertX509ToPEM(properAAMCert), "") ); } @Test @Ignore("offline validation WIP") public void validateRemoteHomeTokenRequestInIntranetUsingProvidedCertificateChainMismatch() throws ValidationException, IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException { // issuing dummy platform token HomeCredentials homeCredentials = new HomeCredentials(null, username, clientId, null, userKeyPair.getPrivate()); String loginRequest = CryptoHelper.buildHomeTokenAcquisitionRequest(homeCredentials); ResponseEntity<String> loginResponse = restTemplate.postForEntity(serverAddress + "/test/conn_err/paam" + SecurityConstants .AAM_GET_HOME_TOKEN, loginRequest, String.class); Token dummyHomeToken = new Token(loginResponse .getHeaders().get(SecurityConstants.TOKEN_HEADER_NAME).get(0)); // wrong chain (signing cert) assertEquals(ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate(dummyHomeToken.getToken(), applicationCertificatePEM, wrongSigningAAMCertificatePEM, "")); } @Test @Ignore("offline validation WIP") public void validateRemoteHomeTokenRequestInIntranetUsingProvidedCertificateTokenKeysMismatch() throws ValidationException { // issuing dummy platform token HomeCredentials homeCredentials = new HomeCredentials(null, username, clientId, null, userKeyPair.getPrivate()); String loginRequest = CryptoHelper.buildHomeTokenAcquisitionRequest(homeCredentials); ResponseEntity<String> loginResponse = restTemplate.postForEntity(serverAddress + "/test/conn_err/paam" + SecurityConstants .AAM_GET_HOME_TOKEN, loginRequest, String.class); Token dummyHomeToken = new Token(loginResponse .getHeaders().get(SecurityConstants.TOKEN_HEADER_NAME).get(0)); // todo wrong chain (token ISS & IPK against clientCertificate don't match) // todo wrong chain (token SUB & SPK against clientCertificate don't match) assertEquals(ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate(dummyHomeToken.getToken(), applicationCertificatePEM, rightSigningAAMCertificatePEM, "")); // missing certificate triggers remote validation attempt assertEquals(ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate(dummyHomeToken.getToken(), applicationCertificatePEM, "", "")); } @Test @Ignore("offline validation WIP") public void validateRemoteHomeTokenRequestInIntranetUsingProvidedCertificateMissingChainElement() throws ValidationException { // issuing dummy platform token HomeCredentials homeCredentials = new HomeCredentials(null, username, clientId, null, userKeyPair.getPrivate()); String loginRequest = CryptoHelper.buildHomeTokenAcquisitionRequest(homeCredentials); ResponseEntity<String> loginResponse = restTemplate.postForEntity(serverAddress + "/test/conn_err/paam" + SecurityConstants .AAM_GET_HOME_TOKEN, loginRequest, String.class); Token dummyHomeToken = new Token(loginResponse .getHeaders().get(SecurityConstants.TOKEN_HEADER_NAME).get(0)); // missing certificate triggers remote validation attempt assertEquals(ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate(dummyHomeToken.getToken(), applicationCertificatePEM, "", "")); } @Test @Ignore("offline validation WIP") public void validateRemoteForeignTokenRequestInIntranetUsingProvidedCertificate() throws ValidationException { // issuing dummy platform token HomeCredentials homeCredentials = new HomeCredentials(null, username, clientId, null, userKeyPair.getPrivate()); String loginRequest = CryptoHelper.buildHomeTokenAcquisitionRequest(homeCredentials); ResponseEntity<String> loginResponse = restTemplate.postForEntity(serverAddress + "/test/conn_err/paam" + SecurityConstants .AAM_GET_HOME_TOKEN, loginRequest, String.class); Token dummyHomeToken = new Token(loginResponse .getHeaders().get(SecurityConstants.TOKEN_HEADER_NAME).get(0)); // check if validation will use certificate instead of relay for offline configured aam // TODO valid chain // assertEquals(ValidationStatus.VALID, validationHelper.validateRemotelyIssuedToken(dummyHomeToken.getToken(), applicationCertificatePEM, rightSigningAAMCertificatePEM)); // wrong chain (signing cert) assertEquals(ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate(dummyHomeToken.getToken(), applicationCertificatePEM, wrongSigningAAMCertificatePEM, "TODO")); // wrong chain (token and clientCertificate don't match) assertEquals(ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate(dummyHomeToken.getToken(), applicationCertificatePEM, rightSigningAAMCertificatePEM, "TODO")); // missing certificate triggers remote validation attempt assertEquals(ValidationStatus.INVALID_TRUST_CHAIN, validationHelper.validate(dummyHomeToken.getToken(), applicationCertificatePEM, "", "TODO")); } @Test public void validateCertificateChainSuccess() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, IOException { assertTrue(validationHelper.isTrusted(rightSigningAAMCertificatePEM, applicationCertificatePEM)); } @Test public void validateCertificateChainFailure() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, IOException { assertFalse(validationHelper.isTrusted(wrongSigningAAMCertificatePEM, applicationCertificatePEM)); } private X509Certificate getCertificateFromTestKeystore(String keyStoreName, String certificateAlias) throws NoSuchProviderException, KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { KeyStore pkcs12Store = KeyStore.getInstance("PKCS12", "BC"); pkcs12Store.load(new ClassPathResource(keyStoreName).getInputStream(), KEY_STORE_PASSWORD.toCharArray()); return (X509Certificate) pkcs12Store.getCertificate(certificateAlias); } public PrivateKey getPrivateKeyFromKeystore(String keyStoreName, String certificateAlias) throws NoSuchProviderException, KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException { KeyStore pkcs12Store = KeyStore.getInstance("PKCS12", "BC"); pkcs12Store.load(new ClassPathResource(keyStoreName).getInputStream(), KEY_STORE_PASSWORD.toCharArray()); return (PrivateKey) pkcs12Store.getKey(certificateAlias, PV_KEY_PASSWORD.toCharArray()); } }
implemented certificates and remote home token matching test for offline validation
src/test/java/eu/h2020/symbiote/security/unit/credentialsvalidation/CredentialsValidationInCoreAAMUnitTests.java
implemented certificates and remote home token matching test for offline validation
Java
apache-2.0
625c5f18745b7cf2975a33ebc8b4ee1d0c4c318a
0
torte71/k-9,herpiko/k-9,tsunli/k-9,indus1/k-9,philipwhiuk/q-mail,denim2x/k-9,bashrc/k-9,sebkur/k-9,github201407/k-9,icedman21/k-9,jca02266/k-9,vasyl-khomko/k-9,ndew623/k-9,tsunli/k-9,sanderbaas/k-9,farmboy0/k-9,crr0004/k-9,dhootha/k-9,cketti/k-9,sedrubal/k-9,dgger/k-9,439teamwork/k-9,ndew623/k-9,vatsalsura/k-9,k9mail/k-9,dpereira411/k-9,dgger/k-9,dhootha/k-9,gnebsy/k-9,cliniome/pki,sonork/k-9,imaeses/k-9,imaeses/k-9,gaionim/k-9,msdgwzhy6/k-9,dpereira411/k-9,deepworks/k-9,crr0004/k-9,farmboy0/k-9,sonork/k-9,sanderbaas/k-9,GuillaumeSmaha/k-9,rollbrettler/k-9,tonytamsf/k-9,k9mail/k-9,huhu/k-9,vasyl-khomko/k-9,Valodim/k-9,rtreffer/openpgp-k-9,thuanpq/k-9,Eagles2F/k-9,denim2x/k-9,KitAway/k-9,bashrc/k-9,dhootha/k-9,gaionim/k-9,philipwhiuk/q-mail,deepworks/k-9,vatsalsura/k-9,farmboy0/k-9,cketti/k-9,WenduanMou1/k-9,cliniome/pki,dpereira411/k-9,philipwhiuk/k-9,KitAway/k-9,moparisthebest/k-9,G00fY2/k-9_material_design,mawiegand/k-9,roscrazy/k-9,thuanpq/k-9,cketti/k-9,leixinstar/k-9,jberkel/k-9,deepworks/k-9,sebkur/k-9,github201407/k-9,nilsbraden/k-9,439teamwork/k-9,jberkel/k-9,sebkur/k-9,jca02266/k-9,cooperpellaton/k-9,rishabhbitsg/k-9,KitAway/k-9,dgger/k-9,GuillaumeSmaha/k-9,gilbertw1/k-9,suzp1984/k-9,herpiko/k-9,sanderbaas/k-9,moparisthebest/k-9,gilbertw1/k-9,XiveZ/k-9,sedrubal/k-9,msdgwzhy6/k-9,konfer/k-9,ndew623/k-9,cooperpellaton/k-9,suzp1984/k-9,suzp1984/k-9,vt0r/k-9,herpiko/k-9,leixinstar/k-9,WenduanMou1/k-9,WenduanMou1/k-9,jca02266/k-9,indus1/k-9,rishabhbitsg/k-9,bashrc/k-9,cliniome/pki,XiveZ/k-9,thuanpq/k-9,k9mail/k-9,msdgwzhy6/k-9,vasyl-khomko/k-9,icedman21/k-9,gilbertw1/k-9,G00fY2/k-9_material_design,CodingRmy/k-9,tsunli/k-9,huhu/k-9,439teamwork/k-9,nilsbraden/k-9,cketti/k-9,torte71/k-9,github201407/k-9,konfer/k-9,XiveZ/k-9,moparisthebest/k-9,mawiegand/k-9,philipwhiuk/q-mail,gaionim/k-9,Eagles2F/k-9,denim2x/k-9,icedman21/k-9,tonytamsf/k-9,tonytamsf/k-9,imaeses/k-9,gnebsy/k-9,leixinstar/k-9,rollbrettler/k-9,vt0r/k-9,sonork/k-9,huhu/k-9,GuillaumeSmaha/k-9,cooperpellaton/k-9,konfer/k-9,roscrazy/k-9,torte71/k-9,Eagles2F/k-9,gnebsy/k-9,rollbrettler/k-9,mawiegand/k-9,rtreffer/openpgp-k-9,CodingRmy/k-9,philipwhiuk/k-9,crr0004/k-9,nilsbraden/k-9
package com.fsck.k9.controller; import java.io.CharArrayWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import android.app.Application; import android.app.KeyguardManager; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.PowerManager; import android.os.Process; import android.support.v4.app.NotificationCompat; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.style.TextAppearanceSpan; import android.util.Log; import com.fsck.k9.Account; import com.fsck.k9.AccountStats; import com.fsck.k9.K9; import com.fsck.k9.K9.NotificationHideSubject; import com.fsck.k9.K9.Intents; import com.fsck.k9.K9.NotificationQuickDelete; import com.fsck.k9.NotificationSetting; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.activity.FolderList; import com.fsck.k9.activity.MessageList; import com.fsck.k9.activity.MessageReference; import com.fsck.k9.activity.NotificationDeleteConfirmation; import com.fsck.k9.activity.setup.AccountSetupIncoming; import com.fsck.k9.activity.setup.AccountSetupOutgoing; import com.fsck.k9.cache.EmailProviderCache; import com.fsck.k9.helper.Contacts; import com.fsck.k9.helper.NotificationBuilder; import com.fsck.k9.helper.power.TracingPowerManager; import com.fsck.k9.helper.power.TracingPowerManager.TracingWakeLock; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.FetchProfile; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.Folder.FolderType; import com.fsck.k9.mail.Folder.OpenMode; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.Message.RecipientType; import com.fsck.k9.mail.CertificateValidationException; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.Part; import com.fsck.k9.mail.PushReceiver; import com.fsck.k9.mail.Pusher; import com.fsck.k9.mail.Store; import com.fsck.k9.mail.Transport; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.internet.MimeUtility; import com.fsck.k9.mail.internet.TextBody; import com.fsck.k9.mail.store.LocalStore; import com.fsck.k9.mail.store.LocalStore.LocalFolder; import com.fsck.k9.mail.store.LocalStore.LocalMessage; import com.fsck.k9.mail.store.LocalStore.PendingCommand; import com.fsck.k9.mail.store.Pop3Store; import com.fsck.k9.mail.store.UnavailableAccountException; import com.fsck.k9.mail.store.UnavailableStorageException; import com.fsck.k9.provider.EmailProvider; import com.fsck.k9.provider.EmailProvider.StatsColumns; import com.fsck.k9.search.ConditionsTreeNode; import com.fsck.k9.search.LocalSearch; import com.fsck.k9.search.SearchAccount; import com.fsck.k9.search.SearchSpecification; import com.fsck.k9.search.SqlQueryBuilder; import com.fsck.k9.service.NotificationActionService; /** * Starts a long running (application) Thread that will run through commands * that require remote mailbox access. This class is used to serialize and * prioritize these commands. Each method that will submit a command requires a * MessagingListener instance to be provided. It is expected that that listener * has also been added as a registered listener using addListener(). When a * command is to be executed, if the listener that was provided with the command * is no longer registered the command is skipped. The design idea for the above * is that when an Activity starts it registers as a listener. When it is paused * it removes itself. Thus, any commands that that activity submitted are * removed from the queue once the activity is no longer active. */ public class MessagingController implements Runnable { public static final long INVALID_MESSAGE_ID = -1; /** * Immutable empty {@link String} array */ private static final String[] EMPTY_STRING_ARRAY = new String[0]; /** * Immutable empty {@link Message} array */ private static final Message[] EMPTY_MESSAGE_ARRAY = new Message[0]; /** * Immutable empty {@link Folder} array */ private static final Folder[] EMPTY_FOLDER_ARRAY = new Folder[0]; /** * The maximum message size that we'll consider to be "small". A small message is downloaded * in full immediately instead of in pieces. Anything over this size will be downloaded in * pieces with attachments being left off completely and downloaded on demand. * * * 25k for a "small" message was picked by educated trial and error. * http://answers.google.com/answers/threadview?id=312463 claims that the * average size of an email is 59k, which I feel is too large for our * blind download. The following tests were performed on a download of * 25 random messages. * <pre> * 5k - 61 seconds, * 25k - 51 seconds, * 55k - 53 seconds, * </pre> * So 25k gives good performance and a reasonable data footprint. Sounds good to me. */ private static final String PENDING_COMMAND_MOVE_OR_COPY = "com.fsck.k9.MessagingController.moveOrCopy"; private static final String PENDING_COMMAND_MOVE_OR_COPY_BULK = "com.fsck.k9.MessagingController.moveOrCopyBulk"; private static final String PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW = "com.fsck.k9.MessagingController.moveOrCopyBulkNew"; private static final String PENDING_COMMAND_EMPTY_TRASH = "com.fsck.k9.MessagingController.emptyTrash"; private static final String PENDING_COMMAND_SET_FLAG_BULK = "com.fsck.k9.MessagingController.setFlagBulk"; private static final String PENDING_COMMAND_SET_FLAG = "com.fsck.k9.MessagingController.setFlag"; private static final String PENDING_COMMAND_APPEND = "com.fsck.k9.MessagingController.append"; private static final String PENDING_COMMAND_MARK_ALL_AS_READ = "com.fsck.k9.MessagingController.markAllAsRead"; private static final String PENDING_COMMAND_EXPUNGE = "com.fsck.k9.MessagingController.expunge"; public static class UidReverseComparator implements Comparator<Message> { @Override public int compare(Message o1, Message o2) { if (o1 == null || o2 == null || o1.getUid() == null || o2.getUid() == null) { return 0; } int id1, id2; try { id1 = Integer.parseInt(o1.getUid()); id2 = Integer.parseInt(o2.getUid()); } catch (NumberFormatException e) { return 0; } //reversed intentionally. if (id1 < id2) return 1; if (id1 > id2) return -1; return 0; } } /** * Maximum number of unsynced messages to store at once */ private static final int UNSYNC_CHUNK_SIZE = 5; private static MessagingController inst = null; private BlockingQueue<Command> mCommands = new PriorityBlockingQueue<Command>(); private Thread mThread; private Set<MessagingListener> mListeners = new CopyOnWriteArraySet<MessagingListener>(); private final ConcurrentHashMap<String, AtomicInteger> sendCount = new ConcurrentHashMap<String, AtomicInteger>(); ConcurrentHashMap<Account, Pusher> pushers = new ConcurrentHashMap<Account, Pusher>(); private final ExecutorService threadPool = Executors.newCachedThreadPool(); private MessagingListener checkMailListener = null; private MemorizingListener memorizingListener = new MemorizingListener(); private boolean mBusy; /** * {@link K9} */ private Application mApplication; /** * A holder class for pending notification data * * This class holds all pieces of information for constructing * a notification with message preview. */ private static class NotificationData { /** Number of unread messages before constructing the notification */ int unreadBeforeNotification; /** * List of messages that should be used for the inbox-style overview. * It's sorted from newest to oldest message. * Don't modify this list directly, but use {@link addMessage} and * {@link removeMatchingMessage} instead. */ LinkedList<Message> messages; /** * List of references for messages that the user is still to be notified of, * but which don't fit into the inbox style anymore. It's sorted from newest * to oldest message. */ LinkedList<MessageReference> droppedMessages; /** * Maximum number of messages to keep for the inbox-style overview. * As of Jellybean, phone notifications show a maximum of 5 lines, while tablet * notifications show 7 lines. To make sure no lines are silently dropped, * we default to 5 lines. */ private final static int MAX_MESSAGES = 5; /** * Constructs a new data instance. * * @param unread Number of unread messages prior to instance construction */ public NotificationData(int unread) { unreadBeforeNotification = unread; droppedMessages = new LinkedList<MessageReference>(); messages = new LinkedList<Message>(); } /** * Adds a new message to the list of pending messages for this notification. * * The implementation will take care of keeping a meaningful amount of * messages in {@link #messages}. * * @param m The new message to add. */ public void addMessage(Message m) { while (messages.size() >= MAX_MESSAGES) { Message dropped = messages.removeLast(); droppedMessages.addFirst(dropped.makeMessageReference()); } messages.addFirst(m); } /** * Remove a certain message from the message list. * * @param context A context. * @param ref Reference of the message to remove * @return true if message was found and removed, false otherwise */ public boolean removeMatchingMessage(Context context, MessageReference ref) { for (MessageReference dropped : droppedMessages) { if (dropped.equals(ref)) { droppedMessages.remove(dropped); return true; } } for (Message message : messages) { if (message.makeMessageReference().equals(ref)) { if (messages.remove(message) && !droppedMessages.isEmpty()) { Message restoredMessage = droppedMessages.getFirst().restoreToLocalMessage(context); if (restoredMessage != null) { messages.addLast(restoredMessage); droppedMessages.removeFirst(); } } return true; } } return false; } /** * Gets a list of references for all pending messages for the notification. * * @return Message reference list */ public ArrayList<MessageReference> getAllMessageRefs() { ArrayList<MessageReference> refs = new ArrayList<MessageReference>(); for (Message m : messages) { refs.add(m.makeMessageReference()); } refs.addAll(droppedMessages); return refs; } /** * Gets the total number of messages the user is to be notified of. * * @return Amount of new messages the notification notifies for */ public int getNewMessageCount() { return messages.size() + droppedMessages.size(); } }; // Key is accountNumber private ConcurrentHashMap<Integer, NotificationData> notificationData = new ConcurrentHashMap<Integer, NotificationData>(); private static final Flag[] SYNC_FLAGS = new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED, Flag.FORWARDED }; private void suppressMessages(Account account, List<Message> messages) { EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), mApplication.getApplicationContext()); cache.hideMessages(messages); } private void unsuppressMessages(Account account, Message[] messages) { EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), mApplication.getApplicationContext()); cache.unhideMessages(messages); } private boolean isMessageSuppressed(Account account, Message message) { LocalMessage localMessage = (LocalMessage) message; String accountUuid = account.getUuid(); long messageId = localMessage.getId(); long folderId = ((LocalFolder) localMessage.getFolder()).getId(); EmailProviderCache cache = EmailProviderCache.getCache(accountUuid, mApplication.getApplicationContext()); return cache.isMessageHidden(messageId, folderId); } private void setFlagInCache(final Account account, final List<Long> messageIds, final Flag flag, final boolean newState) { EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), mApplication.getApplicationContext()); String columnName = LocalStore.getColumnNameForFlag(flag); String value = Integer.toString((newState) ? 1 : 0); cache.setValueForMessages(messageIds, columnName, value); } private void removeFlagFromCache(final Account account, final List<Long> messageIds, final Flag flag) { EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), mApplication.getApplicationContext()); String columnName = LocalStore.getColumnNameForFlag(flag); cache.removeValueForMessages(messageIds, columnName); } private void setFlagForThreadsInCache(final Account account, final List<Long> threadRootIds, final Flag flag, final boolean newState) { EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), mApplication.getApplicationContext()); String columnName = LocalStore.getColumnNameForFlag(flag); String value = Integer.toString((newState) ? 1 : 0); cache.setValueForThreads(threadRootIds, columnName, value); } private void removeFlagForThreadsFromCache(final Account account, final List<Long> messageIds, final Flag flag) { EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), mApplication.getApplicationContext()); String columnName = LocalStore.getColumnNameForFlag(flag); cache.removeValueForThreads(messageIds, columnName); } /** * @param application {@link K9} */ private MessagingController(Application application) { mApplication = application; mThread = new Thread(this); mThread.setName("MessagingController"); mThread.start(); if (memorizingListener != null) { addListener(memorizingListener); } } /** * Gets or creates the singleton instance of MessagingController. Application is used to * provide a Context to classes that need it. * @param application {@link K9} * @return */ public synchronized static MessagingController getInstance(Application application) { if (inst == null) { inst = new MessagingController(application); } return inst; } public boolean isBusy() { return mBusy; } @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (true) { String commandDescription = null; try { final Command command = mCommands.take(); if (command != null) { commandDescription = command.description; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Running " + (command.isForeground ? "Foreground" : "Background") + " command '" + command.description + "', seq = " + command.sequence); mBusy = true; try { command.runnable.run(); } catch (UnavailableAccountException e) { // retry later new Thread() { @Override public void run() { try { sleep(30 * 1000); mCommands.put(command); } catch (InterruptedException e) { Log.e(K9.LOG_TAG, "interrupted while putting a pending command for" + " an unavailable account back into the queue." + " THIS SHOULD NEVER HAPPEN."); } } } .start(); } if (K9.DEBUG) Log.i(K9.LOG_TAG, (command.isForeground ? "Foreground" : "Background") + " Command '" + command.description + "' completed"); for (MessagingListener l : getListeners(command.listener)) { l.controllerCommandCompleted(!mCommands.isEmpty()); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e); } mBusy = false; } } private void put(String description, MessagingListener listener, Runnable runnable) { putCommand(mCommands, description, listener, runnable, true); } private void putBackground(String description, MessagingListener listener, Runnable runnable) { putCommand(mCommands, description, listener, runnable, false); } private void putCommand(BlockingQueue<Command> queue, String description, MessagingListener listener, Runnable runnable, boolean isForeground) { int retries = 10; Exception e = null; while (retries-- > 0) { try { Command command = new Command(); command.listener = listener; command.runnable = runnable; command.description = description; command.isForeground = isForeground; queue.put(command); return; } catch (InterruptedException ie) { try { Thread.sleep(200); } catch (InterruptedException ne) { } e = ie; } } throw new Error(e); } public void addListener(MessagingListener listener) { mListeners.add(listener); refreshListener(listener); } public void refreshListener(MessagingListener listener) { if (memorizingListener != null && listener != null) { memorizingListener.refreshOther(listener); } } public void removeListener(MessagingListener listener) { mListeners.remove(listener); } public Set<MessagingListener> getListeners() { return mListeners; } public Set<MessagingListener> getListeners(MessagingListener listener) { if (listener == null) { return mListeners; } Set<MessagingListener> listeners = new HashSet<MessagingListener>(mListeners); listeners.add(listener); return listeners; } /** * Lists folders that are available locally and remotely. This method calls * listFoldersCallback for local folders before it returns, and then for * remote folders at some later point. If there are no local folders * includeRemote is forced by this method. This method should be called from * a Thread as it may take several seconds to list the local folders. * TODO this needs to cache the remote folder list * * @param account * @param listener * @throws MessagingException */ public void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener) { threadPool.execute(new Runnable() { @Override public void run() { listFoldersSynchronous(account, refreshRemote, listener); } }); } /** * Lists folders that are available locally and remotely. This method calls * listFoldersCallback for local folders before it returns, and then for * remote folders at some later point. If there are no local folders * includeRemote is forced by this method. This method is called in the * foreground. * TODO this needs to cache the remote folder list * * @param account * @param listener * @throws MessagingException */ public void listFoldersSynchronous(final Account account, final boolean refreshRemote, final MessagingListener listener) { for (MessagingListener l : getListeners(listener)) { l.listFoldersStarted(account); } List <? extends Folder > localFolders = null; if (!account.isAvailable(mApplication)) { Log.i(K9.LOG_TAG, "not listing folders of unavailable account"); } else { try { Store localStore = account.getLocalStore(); localFolders = localStore.getPersonalNamespaces(false); Folder[] folderArray = localFolders.toArray(EMPTY_FOLDER_ARRAY); if (refreshRemote || localFolders.isEmpty()) { doRefreshRemote(account, listener); return; } for (MessagingListener l : getListeners(listener)) { l.listFolders(account, folderArray); } } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { l.listFoldersFailed(account, e.getMessage()); } addErrorMessage(account, null, e); return; } finally { if (localFolders != null) { for (Folder localFolder : localFolders) { closeFolder(localFolder); } } } } for (MessagingListener l : getListeners(listener)) { l.listFoldersFinished(account); } } private void doRefreshRemote(final Account account, final MessagingListener listener) { put("doRefreshRemote", listener, new Runnable() { @Override public void run() { List <? extends Folder > localFolders = null; try { Store store = account.getRemoteStore(); List <? extends Folder > remoteFolders = store.getPersonalNamespaces(false); LocalStore localStore = account.getLocalStore(); HashSet<String> remoteFolderNames = new HashSet<String>(); List<LocalFolder> foldersToCreate = new LinkedList<LocalFolder>(); localFolders = localStore.getPersonalNamespaces(false); HashSet<String> localFolderNames = new HashSet<String>(); for (Folder localFolder : localFolders) { localFolderNames.add(localFolder.getName()); } for (Folder remoteFolder : remoteFolders) { if (localFolderNames.contains(remoteFolder.getName()) == false) { LocalFolder localFolder = localStore.getFolder(remoteFolder.getName()); foldersToCreate.add(localFolder); } remoteFolderNames.add(remoteFolder.getName()); } localStore.createFolders(foldersToCreate, account.getDisplayCount()); localFolders = localStore.getPersonalNamespaces(false); /* * Clear out any folders that are no longer on the remote store. */ for (Folder localFolder : localFolders) { String localFolderName = localFolder.getName(); if (!account.isSpecialFolder(localFolderName) && !remoteFolderNames.contains(localFolderName)) { localFolder.delete(false); } } localFolders = localStore.getPersonalNamespaces(false); Folder[] folderArray = localFolders.toArray(EMPTY_FOLDER_ARRAY); for (MessagingListener l : getListeners(listener)) { l.listFolders(account, folderArray); } for (MessagingListener l : getListeners(listener)) { l.listFoldersFinished(account); } } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { l.listFoldersFailed(account, ""); } addErrorMessage(account, null, e); } finally { if (localFolders != null) { for (Folder localFolder : localFolders) { closeFolder(localFolder); } } } } }); } /** * Find all messages in any local account which match the query 'query' * @throws MessagingException */ public void searchLocalMessages(final LocalSearch search, final MessagingListener listener) { threadPool.execute(new Runnable() { @Override public void run() { searchLocalMessagesSynchronous(search, listener); } }); } public void searchLocalMessagesSynchronous(final LocalSearch search, final MessagingListener listener) { final AccountStats stats = new AccountStats(); final HashSet<String> uuidSet = new HashSet<String>(Arrays.asList(search.getAccountUuids())); Account[] accounts = Preferences.getPreferences(mApplication.getApplicationContext()).getAccounts(); boolean allAccounts = uuidSet.contains(SearchSpecification.ALL_ACCOUNTS); // for every account we want to search do the query in the localstore for (final Account account : accounts) { if (!allAccounts && !uuidSet.contains(account.getUuid())) { continue; } // Collecting statistics of the search result MessageRetrievalListener retrievalListener = new MessageRetrievalListener() { @Override public void messageStarted(String message, int number, int ofTotal) {} @Override public void messagesFinished(int number) {} @Override public void messageFinished(Message message, int number, int ofTotal) { if (!isMessageSuppressed(message.getFolder().getAccount(), message)) { List<Message> messages = new ArrayList<Message>(); messages.add(message); stats.unreadMessageCount += (!message.isSet(Flag.SEEN)) ? 1 : 0; stats.flaggedMessageCount += (message.isSet(Flag.FLAGGED)) ? 1 : 0; if (listener != null) { listener.listLocalMessagesAddMessages(account, null, messages); } } } }; // alert everyone the search has started if (listener != null) { listener.listLocalMessagesStarted(account, null); } // build and do the query in the localstore try { LocalStore localStore = account.getLocalStore(); localStore.searchForMessages(retrievalListener, search); } catch (Exception e) { if (listener != null) { listener.listLocalMessagesFailed(account, null, e.getMessage()); } addErrorMessage(account, null, e); } finally { if (listener != null) { listener.listLocalMessagesFinished(account, null); } } } // publish the total search statistics if (listener != null) { listener.searchStats(stats); } } public Future<?> searchRemoteMessages(final String acctUuid, final String folderName, final String query, final Flag[] requiredFlags, final Flag[] forbiddenFlags, final MessagingListener listener) { if (K9.DEBUG) { String msg = "searchRemoteMessages (" + "acct=" + acctUuid + ", folderName = " + folderName + ", query = " + query + ")"; Log.i(K9.LOG_TAG, msg); } return threadPool.submit(new Runnable() { @Override public void run() { searchRemoteMessagesSynchronous(acctUuid, folderName, query, requiredFlags, forbiddenFlags, listener); } }); } public void searchRemoteMessagesSynchronous(final String acctUuid, final String folderName, final String query, final Flag[] requiredFlags, final Flag[] forbiddenFlags, final MessagingListener listener) { final Account acct = Preferences.getPreferences(mApplication.getApplicationContext()).getAccount(acctUuid); if (listener != null) { listener.remoteSearchStarted(acct, folderName); } List<Message> extraResults = new ArrayList<Message>(); try { Store remoteStore = acct.getRemoteStore(); LocalStore localStore = acct.getLocalStore(); if (remoteStore == null || localStore == null) { throw new MessagingException("Could not get store"); } Folder remoteFolder = remoteStore.getFolder(folderName); LocalFolder localFolder = localStore.getFolder(folderName); if (remoteFolder == null || localFolder == null) { throw new MessagingException("Folder not found"); } List<Message> messages = remoteFolder.search(query, requiredFlags, forbiddenFlags); if (K9.DEBUG) { Log.i("Remote Search", "Remote search got " + messages.size() + " results"); } // There's no need to fetch messages already completely downloaded List<Message> remoteMessages = localFolder.extractNewMessages(messages); messages.clear(); if (listener != null) { listener.remoteSearchServerQueryComplete(acct, folderName, remoteMessages.size()); } Collections.sort(remoteMessages, new UidReverseComparator()); int resultLimit = acct.getRemoteSearchNumResults(); if (resultLimit > 0 && remoteMessages.size() > resultLimit) { extraResults = remoteMessages.subList(resultLimit, remoteMessages.size()); remoteMessages = remoteMessages.subList(0, resultLimit); } loadSearchResultsSynchronous(remoteMessages, localFolder, remoteFolder, listener); } catch (Exception e) { if (Thread.currentThread().isInterrupted()) { Log.i(K9.LOG_TAG, "Caught exception on aborted remote search; safe to ignore.", e); } else { Log.e(K9.LOG_TAG, "Could not complete remote search", e); if (listener != null) { listener.remoteSearchFailed(acct, null, e.getMessage()); } addErrorMessage(acct, null, e); } } finally { if (listener != null) { listener.remoteSearchFinished(acct, folderName, 0, extraResults); } } } public void loadSearchResults(final Account account, final String folderName, final List<Message> messages, final MessagingListener listener) { threadPool.execute(new Runnable() { @Override public void run() { if (listener != null) { listener.enableProgressIndicator(true); } try { Store remoteStore = account.getRemoteStore(); LocalStore localStore = account.getLocalStore(); if (remoteStore == null || localStore == null) { throw new MessagingException("Could not get store"); } Folder remoteFolder = remoteStore.getFolder(folderName); LocalFolder localFolder = localStore.getFolder(folderName); if (remoteFolder == null || localFolder == null) { throw new MessagingException("Folder not found"); } loadSearchResultsSynchronous(messages, localFolder, remoteFolder, listener); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Exception in loadSearchResults: " + e); addErrorMessage(account, null, e); } finally { if (listener != null) { listener.enableProgressIndicator(false); } } } }); } public void loadSearchResultsSynchronous(List<Message> messages, LocalFolder localFolder, Folder remoteFolder, MessagingListener listener) throws MessagingException { final FetchProfile header = new FetchProfile(); header.add(FetchProfile.Item.FLAGS); header.add(FetchProfile.Item.ENVELOPE); final FetchProfile structure = new FetchProfile(); structure.add(FetchProfile.Item.STRUCTURE); int i = 0; for (Message message : messages) { i++; LocalMessage localMsg = localFolder.getMessage(message.getUid()); if (localMsg == null) { remoteFolder.fetch(new Message [] {message}, header, null); //fun fact: ImapFolder.fetch can't handle getting STRUCTURE at same time as headers remoteFolder.fetch(new Message [] {message}, structure, null); localFolder.appendMessages(new Message [] {message}); localMsg = localFolder.getMessage(message.getUid()); } if (listener != null) { listener.remoteSearchAddMessage(remoteFolder.getAccount(), remoteFolder.getName(), localMsg, i, messages.size()); } } } public void loadMoreMessages(Account account, String folder, MessagingListener listener) { try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(folder); if (localFolder.getVisibleLimit() > 0) { localFolder.setVisibleLimit(localFolder.getVisibleLimit() + account.getDisplayCount()); } synchronizeMailbox(account, folder, listener, null); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Unable to set visible limit on folder", me); } } public void resetVisibleLimits(Collection<Account> accounts) { for (Account account : accounts) { account.resetVisibleLimits(); } } /** * Start background synchronization of the specified folder. * @param account * @param folder * @param listener * @param providedRemoteFolder TODO */ public void synchronizeMailbox(final Account account, final String folder, final MessagingListener listener, final Folder providedRemoteFolder) { putBackground("synchronizeMailbox", listener, new Runnable() { @Override public void run() { synchronizeMailboxSynchronous(account, folder, listener, providedRemoteFolder); } }); } /** * Start foreground synchronization of the specified folder. This is generally only called * by synchronizeMailbox. * @param account * @param folder * * TODO Break this method up into smaller chunks. * @param providedRemoteFolder TODO */ private void synchronizeMailboxSynchronous(final Account account, final String folder, final MessagingListener listener, Folder providedRemoteFolder) { Folder remoteFolder = null; LocalFolder tLocalFolder = null; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Synchronizing folder " + account.getDescription() + ":" + folder); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxStarted(account, folder); } /* * We don't ever sync the Outbox or errors folder */ if (folder.equals(account.getOutboxFolderName()) || folder.equals(account.getErrorFolderName())) { for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, 0, 0); } return; } Exception commandException = null; try { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to process pending commands for account " + account.getDescription()); try { processPendingCommandsSynchronous(account); } catch (Exception e) { addErrorMessage(account, null, e); Log.e(K9.LOG_TAG, "Failure processing command, but allow message sync attempt", e); commandException = e; } /* * Get the message list from the local store and create an index of * the uids within the list. */ if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get local folder " + folder); final LocalStore localStore = account.getLocalStore(); tLocalFolder = localStore.getFolder(folder); final LocalFolder localFolder = tLocalFolder; localFolder.open(OpenMode.READ_WRITE); localFolder.updateLastUid(); Message[] localMessages = localFolder.getMessages(null); HashMap<String, Message> localUidMap = new HashMap<String, Message>(); for (Message message : localMessages) { localUidMap.put(message.getUid(), message); } if (providedRemoteFolder != null) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: using providedRemoteFolder " + folder); remoteFolder = providedRemoteFolder; } else { Store remoteStore = account.getRemoteStore(); if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get remote folder " + folder); remoteFolder = remoteStore.getFolder(folder); if (! verifyOrCreateRemoteSpecialFolder(account, folder, remoteFolder, listener)) { return; } /* * Synchronization process: * Open the folder Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash) Get the message count Get the list of the newest K9.DEFAULT_VISIBLE_LIMIT messages getMessages(messageCount - K9.DEFAULT_VISIBLE_LIMIT, messageCount) See if we have each message locally, if not fetch it's flags and envelope Get and update the unread count for the folder Update the remote flags of any messages we have locally with an internal date newer than the remote message. Get the current flags for any messages we have locally but did not just download Update local flags For any message we have locally but not remotely, delete the local message to keep cache clean. Download larger parts of any new messages. (Optional) Download small attachments in the background. */ /* * Open the remote folder. This pre-loads certain metadata like message count. */ if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to open remote folder " + folder); remoteFolder.open(OpenMode.READ_WRITE); if (Account.EXPUNGE_ON_POLL.equals(account.getExpungePolicy())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Expunging folder " + account.getDescription() + ":" + folder); remoteFolder.expunge(); } } /* * Get the remote message count. */ int remoteMessageCount = remoteFolder.getMessageCount(); int visibleLimit = localFolder.getVisibleLimit(); if (visibleLimit < 0) { visibleLimit = K9.DEFAULT_VISIBLE_LIMIT; } Message[] remoteMessageArray = EMPTY_MESSAGE_ARRAY; final ArrayList<Message> remoteMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: Remote message count for folder " + folder + " is " + remoteMessageCount); final Date earliestDate = account.getEarliestPollDate(); if (remoteMessageCount > 0) { /* Message numbers start at 1. */ int remoteStart; if (visibleLimit > 0) { remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; } else { remoteStart = 1; } int remoteEnd = remoteMessageCount; if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through " + remoteEnd + " for folder " + folder); final AtomicInteger headerProgress = new AtomicInteger(0); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersStarted(account, folder); } remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteEnd, earliestDate, null); int messageCount = remoteMessageArray.length; for (Message thisMess : remoteMessageArray) { headerProgress.incrementAndGet(); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersProgress(account, folder, headerProgress.get(), messageCount); } Message localMessage = localUidMap.get(thisMess.getUid()); if (localMessage == null || !localMessage.olderThan(earliestDate)) { remoteMessages.add(thisMess); remoteUidMap.put(thisMess.getUid(), thisMess); } } if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: Got " + remoteUidMap.size() + " messages for folder " + folder); remoteMessageArray = null; for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersFinished(account, folder, headerProgress.get(), remoteUidMap.size()); } } else if (remoteMessageCount < 0) { throw new Exception("Message count " + remoteMessageCount + " for folder " + folder); } /* * Remove any messages that are in the local store but no longer on the remote store or are too old */ if (account.syncRemoteDeletions()) { ArrayList<Message> destroyMessages = new ArrayList<Message>(); for (Message localMessage : localMessages) { if (remoteUidMap.get(localMessage.getUid()) == null) { destroyMessages.add(localMessage); } } localFolder.destroyMessages(destroyMessages.toArray(EMPTY_MESSAGE_ARRAY)); for (Message destroyMessage : destroyMessages) { for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxRemovedMessage(account, folder, destroyMessage); } } } localMessages = null; /* * Now we download the actual content of messages. */ int newMessages = downloadMessages(account, remoteFolder, localFolder, remoteMessages, false); int unreadMessageCount = localFolder.getUnreadMessageCount(); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, unreadMessageCount); } /* Notify listeners that we're finally done. */ localFolder.setLastChecked(System.currentTimeMillis()); localFolder.setStatus(null); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date() + " with " + newMessages + " new messages"); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages); } if (commandException != null) { String rootMessage = getRootCauseMessage(commandException); Log.e(K9.LOG_TAG, "Root cause failure in " + account.getDescription() + ":" + tLocalFolder.getName() + " was '" + rootMessage + "'"); localFolder.setStatus(rootMessage); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFailed(account, folder, rootMessage); } } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder); } catch (Exception e) { Log.e(K9.LOG_TAG, "synchronizeMailbox", e); // If we don't set the last checked, it can try too often during // failure conditions String rootMessage = getRootCauseMessage(e); if (tLocalFolder != null) { try { tLocalFolder.setStatus(rootMessage); tLocalFolder.setLastChecked(System.currentTimeMillis()); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" + tLocalFolder.getName(), e); } } for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFailed(account, folder, rootMessage); } notifyUserIfCertificateProblem(mApplication, e, account, true); addErrorMessage(account, null, e); Log.e(K9.LOG_TAG, "Failed synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date()); } finally { if (providedRemoteFolder == null) { closeFolder(remoteFolder); } closeFolder(tLocalFolder); } } private void closeFolder(Folder f) { if (f != null) { f.close(); } } /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ private boolean verifyOrCreateRemoteSpecialFolder(final Account account, final String folder, final Folder remoteFolder, final MessagingListener listener) throws MessagingException { if (folder.equals(account.getTrashFolderName()) || folder.equals(account.getSentFolderName()) || folder.equals(account.getDraftsFolderName())) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, 0, 0); } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Done synchronizing folder " + folder); return false; } } } return true; } /** * Fetches the messages described by inputMessages from the remote store and writes them to * local storage. * * @param account * The account the remote store belongs to. * @param remoteFolder * The remote folder to download messages from. * @param localFolder * The {@link LocalFolder} instance corresponding to the remote folder. * @param inputMessages * A list of messages objects that store the UIDs of which messages to download. * @param flagSyncOnly * Only flags will be fetched from the remote store if this is {@code true}. * * @return The number of downloaded messages that are not flagged as {@link Flag#SEEN}. * * @throws MessagingException */ private int downloadMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, List<Message> inputMessages, boolean flagSyncOnly) throws MessagingException { final Date earliestDate = account.getEarliestPollDate(); Date downloadStarted = new Date(); // now if (earliestDate != null) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Only syncing messages after " + earliestDate); } } final String folder = remoteFolder.getName(); int unreadBeforeStart = 0; try { AccountStats stats = account.getStats(mApplication); unreadBeforeStart = stats.unreadMessageCount; } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e); } ArrayList<Message> syncFlagMessages = new ArrayList<Message>(); List<Message> unsyncedMessages = new ArrayList<Message>(); final AtomicInteger newMessages = new AtomicInteger(0); List<Message> messages = new ArrayList<Message>(inputMessages); for (Message message : messages) { evaluateMessageForDownload(message, folder, localFolder, remoteFolder, account, unsyncedMessages, syncFlagMessages , flagSyncOnly); } final AtomicInteger progress = new AtomicInteger(0); final int todo = unsyncedMessages.size() + syncFlagMessages.size(); for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Have " + unsyncedMessages.size() + " unsynced messages"); messages.clear(); final ArrayList<Message> largeMessages = new ArrayList<Message>(); final ArrayList<Message> smallMessages = new ArrayList<Message>(); if (!unsyncedMessages.isEmpty()) { /* * Reverse the order of the messages. Depending on the server this may get us * fetch results for newest to oldest. If not, no harm done. */ Collections.sort(unsyncedMessages, new UidReverseComparator()); int visibleLimit = localFolder.getVisibleLimit(); int listSize = unsyncedMessages.size(); if ((visibleLimit > 0) && (listSize > visibleLimit)) { unsyncedMessages = unsyncedMessages.subList(0, visibleLimit); } FetchProfile fp = new FetchProfile(); if (remoteFolder.supportsFetchingFlags()) { fp.add(FetchProfile.Item.FLAGS); } fp.add(FetchProfile.Item.ENVELOPE); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to fetch " + unsyncedMessages.size() + " unsynced messages for folder " + folder); fetchUnsyncedMessages(account, remoteFolder, localFolder, unsyncedMessages, smallMessages, largeMessages, progress, todo, fp); // If a message didn't exist, messageFinished won't be called, but we shouldn't try again // If we got here, nothing failed for (Message message : unsyncedMessages) { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); if (newPushState != null) { localFolder.setPushState(newPushState); } } if (K9.DEBUG) { Log.d(K9.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder); } } if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Have " + largeMessages.size() + " large messages and " + smallMessages.size() + " small messages out of " + unsyncedMessages.size() + " unsynced messages"); unsyncedMessages.clear(); /* * Grab the content of the small messages first. This is going to * be very fast and at very worst will be a single up of a few bytes and a single * download of 625k. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); // fp.add(FetchProfile.Item.FLAGS); // fp.add(FetchProfile.Item.ENVELOPE); downloadSmallMessages(account, remoteFolder, localFolder, smallMessages, progress, unreadBeforeStart, newMessages, todo, fp); smallMessages.clear(); /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); downloadLargeMessages(account, remoteFolder, localFolder, largeMessages, progress, unreadBeforeStart, newMessages, todo, fp); largeMessages.clear(); /* * Refresh the flags for any messages in the local store that we didn't just * download. */ refreshLocalMessageFlags(account, remoteFolder, localFolder, syncFlagMessages, progress, todo); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Synced remote messages for folder " + folder + ", " + newMessages.get() + " new messages"); localFolder.purgeToVisibleLimit(new MessageRemovalListener() { @Override public void messageRemoved(Message message) { for (MessagingListener l : getListeners()) { l.synchronizeMailboxRemovedMessage(account, folder, message); } } }); // If the oldest message seen on this sync is newer than // the oldest message seen on the previous sync, then // we want to move our high-water mark forward // this is all here just for pop which only syncs inbox // this would be a little wrong for IMAP (we'd want a folder-level pref, not an account level pref.) // fortunately, we just don't care. Long oldestMessageTime = localFolder.getOldestMessageDate(); if (oldestMessageTime != null) { Date oldestExtantMessage = new Date(oldestMessageTime); if (oldestExtantMessage.before(downloadStarted) && oldestExtantMessage.after(new Date(account.getLatestOldMessageSeenTime()))) { account.setLatestOldMessageSeenTime(oldestExtantMessage.getTime()); account.save(Preferences.getPreferences(mApplication.getApplicationContext())); } } return newMessages.get(); } private void evaluateMessageForDownload(final Message message, final String folder, final LocalFolder localFolder, final Folder remoteFolder, final Account account, final List<Message> unsyncedMessages, final ArrayList<Message> syncFlagMessages, boolean flagSyncOnly) throws MessagingException { if (message.isSet(Flag.DELETED)) { syncFlagMessages.add(message); return; } Message localMessage = localFolder.getMessage(message.getUid()); if (localMessage == null) { if (!flagSyncOnly) { if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " has not yet been downloaded"); unsyncedMessages.add(message); } else { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is partially or fully downloaded"); // Store the updated message locally localFolder.appendMessages(new Message[] { message }); localMessage = localFolder.getMessage(message.getUid()); localMessage.setFlag(Flag.X_DOWNLOADED_FULL, message.isSet(Flag.X_DOWNLOADED_FULL)); localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, message.isSet(Flag.X_DOWNLOADED_PARTIAL)); for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } } } } else if (!localMessage.isSet(Flag.DELETED)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is present in the local store"); if (!localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is not downloaded, even partially; trying again"); unsyncedMessages.add(message); } else { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); if (newPushState != null) { localFolder.setPushState(newPushState); } syncFlagMessages.add(message); } } } private void fetchUnsyncedMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, List<Message> unsyncedMessages, final ArrayList<Message> smallMessages, final ArrayList<Message> largeMessages, final AtomicInteger progress, final int todo, FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); /* * Messages to be batch written */ final List<Message> chunk = new ArrayList<Message>(UNSYNC_CHUNK_SIZE); remoteFolder.fetch(unsyncedMessages.toArray(EMPTY_MESSAGE_ARRAY), fp, new MessageRetrievalListener() { @Override public void messageFinished(Message message, int number, int ofTotal) { try { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); if (newPushState != null) { localFolder.setPushState(newPushState); } if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate)) { if (K9.DEBUG) { if (message.isSet(Flag.DELETED)) { Log.v(K9.LOG_TAG, "Newly downloaded message " + account + ":" + folder + ":" + message.getUid() + " was marked deleted on server, skipping"); } else { Log.d(K9.LOG_TAG, "Newly downloaded message " + message.getUid() + " is older than " + earliestDate + ", skipping"); } } progress.incrementAndGet(); for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } return; } if (account.getMaximumAutoDownloadMessageSize() > 0 && message.getSize() > account.getMaximumAutoDownloadMessageSize()) { largeMessages.add(message); } else { smallMessages.add(message); } // And include it in the view if (message.getSubject() != null && message.getFrom() != null) { /* * We check to make sure that we got something worth * showing (subject and from) because some protocols * (POP) may not be able to give us headers for * ENVELOPE, only size. */ // keep message for delayed storing chunk.add(message); if (chunk.size() >= UNSYNC_CHUNK_SIZE) { writeUnsyncedMessages(chunk, localFolder, account, folder); chunk.clear(); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e); addErrorMessage(account, null, e); } } @Override public void messageStarted(String uid, int number, int ofTotal) {} @Override public void messagesFinished(int total) { // FIXME this method is almost never invoked by various Stores! Don't rely on it unless fixed!! } }); if (!chunk.isEmpty()) { writeUnsyncedMessages(chunk, localFolder, account, folder); chunk.clear(); } } /** * Actual storing of messages * * <br> * FIXME: <strong>This method should really be moved in the above MessageRetrievalListener once {@link MessageRetrievalListener#messagesFinished(int)} is properly invoked by various stores</strong> * * @param messages Never <code>null</code>. * @param localFolder * @param account * @param folder */ private void writeUnsyncedMessages(final List<Message> messages, final LocalFolder localFolder, final Account account, final String folder) { if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Batch writing " + Integer.toString(messages.size()) + " messages"); } try { // Store the new message locally localFolder.appendMessages(messages.toArray(new Message[messages.size()])); for (final Message message : messages) { final Message localMessage = localFolder.getMessage(message.getUid()); syncFlags(localMessage, message); if (K9.DEBUG) Log.v(K9.LOG_TAG, "About to notify listeners that we got a new unsynced message " + account + ":" + folder + ":" + message.getUid()); for (final MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); } } } catch (final Exception e) { Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e); addErrorMessage(account, null, e); } } private boolean shouldImportMessage(final Account account, final String folder, final Message message, final AtomicInteger progress, final Date earliestDate) { if (account.isSearchByDateCapable() && message.olderThan(earliestDate)) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than " + earliestDate + ", hence not saving"); } return false; } return true; } private void downloadSmallMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, ArrayList<Message> smallMessages, final AtomicInteger progress, final int unreadBeforeStart, final AtomicInteger newMessages, final int todo, FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Fetching small messages for folder " + folder); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { @Override public void messageFinished(final Message message, int number, int ofTotal) { try { if (!shouldImportMessage(account, folder, message, progress, earliestDate)) { progress.incrementAndGet(); return; } // Store the updated message locally final Message localMessage = localFolder.storeSmallMessage(message, new Runnable() { @Override public void run() { progress.incrementAndGet(); } }); // Increment the number of "new messages" if the newly downloaded message is // not marked as read. if (!localMessage.isSet(Flag.SEEN)) { newMessages.incrementAndGet(); } if (K9.DEBUG) Log.v(K9.LOG_TAG, "About to notify listeners that we got a new small message " + account + ":" + folder + ":" + message.getUid()); // Update the listener with what we've found for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); l.synchronizeMailboxProgress(account, folder, progress.get(), todo); if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } // Send a notification of this message if (shouldNotifyForMessage(account, localFolder, message)) { // Notify with the localMessage so that we don't have to recalculate the content preview. notifyAccount(mApplication, account, localMessage, unreadBeforeStart); } } catch (MessagingException me) { addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "SYNC: fetch small messages", me); } } @Override public void messageStarted(String uid, int number, int ofTotal) {} @Override public void messagesFinished(int total) {} }); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder); } private void downloadLargeMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, ArrayList<Message> largeMessages, final AtomicInteger progress, final int unreadBeforeStart, final AtomicInteger newMessages, final int todo, FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Fetching large messages for folder " + folder); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (!shouldImportMessage(account, folder, message, progress, earliestDate)) { progress.incrementAndGet(); continue; } if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); // Certain (POP3) servers give you the whole message even when you ask for only the first x Kb if (!message.isSet(Flag.X_DOWNLOADED_FULL)) { /* * Mark the message as fully downloaded if the message size is smaller than * the account's autodownload size limit, otherwise mark as only a partial * download. This will prevent the system from downloading the same message * twice. * * If there is no limit on autodownload size, that's the same as the message * being smaller than the max size */ if (account.getMaximumAutoDownloadMessageSize() == 0 || message.getSize() < account.getMaximumAutoDownloadMessageSize()) { localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } else { // Set a flag indicating that the message has been partially downloaded and // is ready for view. localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } } } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ Set<Part> viewables = MimeUtility.collectTextParts(message); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { remoteFolder.fetchPart(message, part, null); } // Store the updated message locally localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } if (K9.DEBUG) Log.v(K9.LOG_TAG, "About to notify listeners that we got a new large message " + account + ":" + folder + ":" + message.getUid()); // Update the listener with what we've found progress.incrementAndGet(); // TODO do we need to re-fetch this here? Message localMessage = localFolder.getMessage(message.getUid()); // Increment the number of "new messages" if the newly downloaded message is // not marked as read. if (!localMessage.isSet(Flag.SEEN)) { newMessages.incrementAndGet(); } for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); l.synchronizeMailboxProgress(account, folder, progress.get(), todo); if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } // Send a notification of this message if (shouldNotifyForMessage(account, localFolder, message)) { // Notify with the localMessage so that we don't have to recalculate the content preview. notifyAccount(mApplication, account, localMessage, unreadBeforeStart); } }//for large messages if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder); } private void refreshLocalMessageFlags(final Account account, final Folder remoteFolder, final LocalFolder localFolder, ArrayList<Message> syncFlagMessages, final AtomicInteger progress, final int todo ) throws MessagingException { final String folder = remoteFolder.getName(); if (remoteFolder.supportsFetchingFlags()) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to sync flags for " + syncFlagMessages.size() + " remote messages for folder " + folder); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); List<Message> undeletedMessages = new LinkedList<Message>(); for (Message message : syncFlagMessages) { if (!message.isSet(Flag.DELETED)) { undeletedMessages.add(message); } } remoteFolder.fetch(undeletedMessages.toArray(EMPTY_MESSAGE_ARRAY), fp, null); for (Message remoteMessage : syncFlagMessages) { Message localMessage = localFolder.getMessage(remoteMessage.getUid()); boolean messageChanged = syncFlags(localMessage, remoteMessage); if (messageChanged) { boolean shouldBeNotifiedOf = false; if (localMessage.isSet(Flag.DELETED) || isMessageSuppressed(account, localMessage)) { for (MessagingListener l : getListeners()) { l.synchronizeMailboxRemovedMessage(account, folder, localMessage); } } else { for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); } if (shouldNotifyForMessage(account, localFolder, localMessage)) { shouldBeNotifiedOf = true; } } // we're only interested in messages that need removing if (!shouldBeNotifiedOf) { NotificationData data = getNotificationData(account, null); if (data != null) { synchronized (data) { MessageReference ref = localMessage.makeMessageReference(); if (data.removeMatchingMessage(mApplication, ref)) { notifyAccountWithDataLocked(mApplication, account, null, data); } } } } } progress.incrementAndGet(); for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } } } } private boolean syncFlags(Message localMessage, Message remoteMessage) throws MessagingException { boolean messageChanged = false; if (localMessage == null || localMessage.isSet(Flag.DELETED)) { return false; } if (remoteMessage.isSet(Flag.DELETED)) { if (localMessage.getFolder().getAccount().syncRemoteDeletions()) { localMessage.setFlag(Flag.DELETED, true); messageChanged = true; } } else { for (Flag flag : MessagingController.SYNC_FLAGS) { if (remoteMessage.isSet(flag) != localMessage.isSet(flag)) { localMessage.setFlag(flag, remoteMessage.isSet(flag)); messageChanged = true; } } } return messageChanged; } private String getRootCauseMessage(Throwable t) { Throwable rootCause = t; Throwable nextCause = rootCause; do { nextCause = rootCause.getCause(); if (nextCause != null) { rootCause = nextCause; } } while (nextCause != null); if (rootCause instanceof MessagingException) { return rootCause.getMessage(); } else { // Remove the namespace on the exception so we have a fighting chance of seeing more of the error in the // notification. return (rootCause.getLocalizedMessage() != null) ? (rootCause.getClass().getSimpleName() + ": " + rootCause.getLocalizedMessage()) : rootCause.getClass().getSimpleName(); } } private void queuePendingCommand(Account account, PendingCommand command) { try { LocalStore localStore = account.getLocalStore(); localStore.addPendingCommand(command); } catch (Exception e) { addErrorMessage(account, null, e); throw new RuntimeException("Unable to enqueue pending command", e); } } private void processPendingCommands(final Account account) { putBackground("processPendingCommands", null, new Runnable() { @Override public void run() { try { processPendingCommandsSynchronous(account); } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to process pending command because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "processPendingCommands", me); addErrorMessage(account, null, me); /* * Ignore any exceptions from the commands. Commands will be processed * on the next round. */ } } }); } private void processPendingCommandsSynchronous(Account account) throws MessagingException { LocalStore localStore = account.getLocalStore(); ArrayList<PendingCommand> commands = localStore.getPendingCommands(); int progress = 0; int todo = commands.size(); if (todo == 0) { return; } for (MessagingListener l : getListeners()) { l.pendingCommandsProcessing(account); l.synchronizeMailboxProgress(account, null, progress, todo); } PendingCommand processingCommand = null; try { for (PendingCommand command : commands) { processingCommand = command; if (K9.DEBUG) Log.d(K9.LOG_TAG, "Processing pending command '" + command + "'"); String[] components = command.command.split("\\."); String commandTitle = components[components.length - 1]; for (MessagingListener l : getListeners()) { l.pendingCommandStarted(account, commandTitle); } /* * We specifically do not catch any exceptions here. If a command fails it is * most likely due to a server or IO error and it must be retried before any * other command processes. This maintains the order of the commands. */ try { if (PENDING_COMMAND_APPEND.equals(command.command)) { processPendingAppend(command, account); } else if (PENDING_COMMAND_SET_FLAG_BULK.equals(command.command)) { processPendingSetFlag(command, account); } else if (PENDING_COMMAND_SET_FLAG.equals(command.command)) { processPendingSetFlagOld(command, account); } else if (PENDING_COMMAND_MARK_ALL_AS_READ.equals(command.command)) { processPendingMarkAllAsRead(command, account); } else if (PENDING_COMMAND_MOVE_OR_COPY_BULK.equals(command.command)) { processPendingMoveOrCopyOld2(command, account); } else if (PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW.equals(command.command)) { processPendingMoveOrCopy(command, account); } else if (PENDING_COMMAND_MOVE_OR_COPY.equals(command.command)) { processPendingMoveOrCopyOld(command, account); } else if (PENDING_COMMAND_EMPTY_TRASH.equals(command.command)) { processPendingEmptyTrash(command, account); } else if (PENDING_COMMAND_EXPUNGE.equals(command.command)) { processPendingExpunge(command, account); } localStore.removePendingCommand(command); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Done processing pending command '" + command + "'"); } catch (MessagingException me) { if (me.isPermanentFailure()) { addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "Failure of command '" + command + "' was permanent, removing command from queue"); localStore.removePendingCommand(processingCommand); } else { throw me; } } finally { progress++; for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, null, progress, todo); l.pendingCommandCompleted(account, commandTitle); } } } } catch (MessagingException me) { notifyUserIfCertificateProblem(mApplication, me, account, true); addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "Could not process command '" + processingCommand + "'", me); throw me; } finally { for (MessagingListener l : getListeners()) { l.pendingCommandsFinished(account); } } } /** * Process a pending append message command. This command uploads a local message to the * server, first checking to be sure that the server message is not newer than * the local message. Once the local message is successfully processed it is deleted so * that the server message will be synchronized down without an additional copy being * created. * TODO update the local message UID instead of deleteing it * * @param command arguments = (String folder, String uid) * @param account * @throws MessagingException */ private void processPendingAppend(PendingCommand command, Account account) throws MessagingException { Folder remoteFolder = null; LocalFolder localFolder = null; try { String folder = command.arguments[0]; String uid = command.arguments[1]; if (account.getErrorFolderName().equals(folder)) { return; } LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); LocalMessage localMessage = localFolder.getMessage(uid); if (localMessage == null) { return; } Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return; } } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } Message remoteMessage = null; if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteFolder.getMessage(localMessage.getUid()); } if (remoteMessage == null) { if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED)) { Log.w(K9.LOG_TAG, "Local message with uid " + localMessage.getUid() + " has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, checking for remote message with " + " same message id"); String rUid = remoteFolder.getUidFromMessageId(localMessage); if (rUid != null) { Log.w(K9.LOG_TAG, "Local message has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, and there is a remote message with " + " uid " + rUid + ", assuming message was already copied and aborting this copy"); String oldUid = localMessage.getUid(); localMessage.setUid(rUid); localFolder.changeUid(localMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } return; } else { Log.w(K9.LOG_TAG, "No remote message with message-id found, proceeding with append"); } } /* * If the message does not exist remotely we just upload it and then * update our local copy with the new uid. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { localMessage } , fp, null); String oldUid = localMessage.getUid(); localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true); remoteFolder.appendMessages(new Message[] { localMessage }); localFolder.changeUid(localMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } } else { /* * If the remote message exists we need to determine which copy to keep. */ /* * See if the remote message is newer than ours. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); remoteFolder.fetch(new Message[] { remoteMessage }, fp, null); Date localDate = localMessage.getInternalDate(); Date remoteDate = remoteMessage.getInternalDate(); if (remoteDate != null && remoteDate.compareTo(localDate) > 0) { /* * If the remote message is newer than ours we'll just * delete ours and move on. A sync will get the server message * if we need to be able to see it. */ localMessage.destroy(); } else { /* * Otherwise we'll upload our message and then delete the remote message. */ fp.clear(); fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { localMessage }, fp, null); String oldUid = localMessage.getUid(); localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true); remoteFolder.appendMessages(new Message[] { localMessage }); localFolder.changeUid(localMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } if (remoteDate != null) { remoteMessage.setFlag(Flag.DELETED, true); if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { remoteFolder.expunge(); } } } } } finally { closeFolder(remoteFolder); closeFolder(localFolder); } } private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[]) { if (account.getErrorFolderName().equals(srcFolder)) { return; } PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW; int length = 4 + uids.length; command.arguments = new String[length]; command.arguments[0] = srcFolder; command.arguments[1] = destFolder; command.arguments[2] = Boolean.toString(isCopy); command.arguments[3] = Boolean.toString(false); System.arraycopy(uids, 0, command.arguments, 4, uids.length); queuePendingCommand(account, command); } private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[], Map<String, String> uidMap) { if (uidMap == null || uidMap.isEmpty()) { queueMoveOrCopy(account, srcFolder, destFolder, isCopy, uids); } else { if (account.getErrorFolderName().equals(srcFolder)) { return; } PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW; int length = 4 + uidMap.keySet().size() + uidMap.values().size(); command.arguments = new String[length]; command.arguments[0] = srcFolder; command.arguments[1] = destFolder; command.arguments[2] = Boolean.toString(isCopy); command.arguments[3] = Boolean.toString(true); System.arraycopy(uidMap.keySet().toArray(), 0, command.arguments, 4, uidMap.keySet().size()); System.arraycopy(uidMap.values().toArray(), 0, command.arguments, 4 + uidMap.keySet().size(), uidMap.values().size()); queuePendingCommand(account, command); } } /** * Convert pending command to new format and call * {@link #processPendingMoveOrCopy(PendingCommand, Account)}. * * <p> * TODO: This method is obsolete and is only for transition from K-9 4.0 to K-9 4.2 * Eventually, it should be removed. * </p> * * @param command * Pending move/copy command in old format. * @param account * The account the pending command belongs to. * * @throws MessagingException * In case of an error. */ private void processPendingMoveOrCopyOld2(PendingCommand command, Account account) throws MessagingException { PendingCommand newCommand = new PendingCommand(); int len = command.arguments.length; newCommand.command = PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW; newCommand.arguments = new String[len + 1]; newCommand.arguments[0] = command.arguments[0]; newCommand.arguments[1] = command.arguments[1]; newCommand.arguments[2] = command.arguments[2]; newCommand.arguments[3] = Boolean.toString(false); System.arraycopy(command.arguments, 3, newCommand.arguments, 4, len - 3); processPendingMoveOrCopy(newCommand, account); } /** * Process a pending trash message command. * * @param command arguments = (String folder, String uid) * @param account * @throws MessagingException */ private void processPendingMoveOrCopy(PendingCommand command, Account account) throws MessagingException { Folder remoteSrcFolder = null; Folder remoteDestFolder = null; LocalFolder localDestFolder = null; try { String srcFolder = command.arguments[0]; if (account.getErrorFolderName().equals(srcFolder)) { return; } String destFolder = command.arguments[1]; String isCopyS = command.arguments[2]; String hasNewUidsS = command.arguments[3]; boolean hasNewUids = false; if (hasNewUidsS != null) { hasNewUids = Boolean.parseBoolean(hasNewUidsS); } Store remoteStore = account.getRemoteStore(); remoteSrcFolder = remoteStore.getFolder(srcFolder); Store localStore = account.getLocalStore(); localDestFolder = (LocalFolder) localStore.getFolder(destFolder); List<Message> messages = new ArrayList<Message>(); /* * We split up the localUidMap into two parts while sending the command, here we assemble it back. */ Map<String, String> localUidMap = new HashMap<String, String>(); if (hasNewUids) { int offset = (command.arguments.length - 4) / 2; for (int i = 4; i < 4 + offset; i++) { localUidMap.put(command.arguments[i], command.arguments[i + offset]); String uid = command.arguments[i]; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { messages.add(remoteSrcFolder.getMessage(uid)); } } } else { for (int i = 4; i < command.arguments.length; i++) { String uid = command.arguments[i]; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { messages.add(remoteSrcFolder.getMessage(uid)); } } } boolean isCopy = false; if (isCopyS != null) { isCopy = Boolean.parseBoolean(isCopyS); } if (!remoteSrcFolder.exists()) { throw new MessagingException("processingPendingMoveOrCopy: remoteFolder " + srcFolder + " does not exist", true); } remoteSrcFolder.open(OpenMode.READ_WRITE); if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processingPendingMoveOrCopy: could not open remoteSrcFolder " + srcFolder + " read/write", true); } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy: source folder = " + srcFolder + ", " + messages.size() + " messages, destination folder = " + destFolder + ", isCopy = " + isCopy); Map <String, String> remoteUidMap = null; if (!isCopy && destFolder.equals(account.getTrashFolderName())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy doing special case for deleting message"); String destFolderName = destFolder; if (K9.FOLDER_NONE.equals(destFolderName)) { destFolderName = null; } remoteSrcFolder.delete(messages.toArray(EMPTY_MESSAGE_ARRAY), destFolderName); } else { remoteDestFolder = remoteStore.getFolder(destFolder); if (isCopy) { remoteUidMap = remoteSrcFolder.copyMessages(messages.toArray(EMPTY_MESSAGE_ARRAY), remoteDestFolder); } else { remoteUidMap = remoteSrcFolder.moveMessages(messages.toArray(EMPTY_MESSAGE_ARRAY), remoteDestFolder); } } if (!isCopy && Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "processingPendingMoveOrCopy expunging folder " + account.getDescription() + ":" + srcFolder); remoteSrcFolder.expunge(); } /* * This next part is used to bring the local UIDs of the local destination folder * upto speed with the remote UIDs of remote destionation folder. */ if (!localUidMap.isEmpty() && remoteUidMap != null && !remoteUidMap.isEmpty()) { Set<Map.Entry<String, String>> remoteSrcEntries = remoteUidMap.entrySet(); Iterator<Map.Entry<String, String>> remoteSrcEntriesIterator = remoteSrcEntries.iterator(); while (remoteSrcEntriesIterator.hasNext()) { Map.Entry<String, String> entry = remoteSrcEntriesIterator.next(); String remoteSrcUid = entry.getKey(); String localDestUid = localUidMap.get(remoteSrcUid); String newUid = entry.getValue(); Message localDestMessage = localDestFolder.getMessage(localDestUid); if (localDestMessage != null) { localDestMessage.setUid(newUid); localDestFolder.changeUid((LocalMessage)localDestMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, destFolder, localDestUid, newUid); } } } } } finally { closeFolder(remoteSrcFolder); closeFolder(remoteDestFolder); } } private void queueSetFlag(final Account account, final String folderName, final String newState, final String flag, final String[] uids) { putBackground("queueSetFlag " + account.getDescription() + ":" + folderName, null, new Runnable() { @Override public void run() { PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_SET_FLAG_BULK; int length = 3 + uids.length; command.arguments = new String[length]; command.arguments[0] = folderName; command.arguments[1] = newState; command.arguments[2] = flag; System.arraycopy(uids, 0, command.arguments, 3, uids.length); queuePendingCommand(account, command); processPendingCommands(account); } }); } /** * Processes a pending mark read or unread command. * * @param command arguments = (String folder, String uid, boolean read) * @param account */ private void processPendingSetFlag(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; if (account.getErrorFolderName().equals(folder)) { return; } boolean newState = Boolean.parseBoolean(command.arguments[1]); Flag flag = Flag.valueOf(command.arguments[2]); Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists() || !remoteFolder.isFlagSupported(flag)) { return; } try { remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } List<Message> messages = new ArrayList<Message>(); for (int i = 3; i < command.arguments.length; i++) { String uid = command.arguments[i]; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { messages.add(remoteFolder.getMessage(uid)); } } if (messages.isEmpty()) { return; } remoteFolder.setFlags(messages.toArray(EMPTY_MESSAGE_ARRAY), new Flag[] { flag }, newState); } finally { closeFolder(remoteFolder); } } // TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1 // Eventually, it should be removed private void processPendingSetFlagOld(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; String uid = command.arguments[1]; if (account.getErrorFolderName().equals(folder)) { return; } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingSetFlagOld: folder = " + folder + ", uid = " + uid); boolean newState = Boolean.parseBoolean(command.arguments[2]); Flag flag = Flag.valueOf(command.arguments[3]); Folder remoteFolder = null; try { Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } Message remoteMessage = null; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteFolder.getMessage(uid); } if (remoteMessage == null) { return; } remoteMessage.setFlag(flag, newState); } finally { closeFolder(remoteFolder); } } private void queueExpunge(final Account account, final String folderName) { putBackground("queueExpunge " + account.getDescription() + ":" + folderName, null, new Runnable() { @Override public void run() { PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_EXPUNGE; command.arguments = new String[1]; command.arguments[0] = folderName; queuePendingCommand(account, command); processPendingCommands(account); } }); } private void processPendingExpunge(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; if (account.getErrorFolderName().equals(folder)) { return; } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingExpunge: folder = " + folder); Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(folder); try { if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } remoteFolder.expunge(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingExpunge: complete for folder = " + folder); } finally { closeFolder(remoteFolder); } } // TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1 // Eventually, it should be removed private void processPendingMoveOrCopyOld(PendingCommand command, Account account) throws MessagingException { String srcFolder = command.arguments[0]; String uid = command.arguments[1]; String destFolder = command.arguments[2]; String isCopyS = command.arguments[3]; boolean isCopy = false; if (isCopyS != null) { isCopy = Boolean.parseBoolean(isCopyS); } if (account.getErrorFolderName().equals(srcFolder)) { return; } Store remoteStore = account.getRemoteStore(); Folder remoteSrcFolder = remoteStore.getFolder(srcFolder); Folder remoteDestFolder = remoteStore.getFolder(destFolder); if (!remoteSrcFolder.exists()) { throw new MessagingException("processPendingMoveOrCopyOld: remoteFolder " + srcFolder + " does not exist", true); } remoteSrcFolder.open(OpenMode.READ_WRITE); if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteSrcFolder " + srcFolder + " read/write", true); } Message remoteMessage = null; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteSrcFolder.getMessage(uid); } if (remoteMessage == null) { throw new MessagingException("processPendingMoveOrCopyOld: remoteMessage " + uid + " does not exist", true); } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld: source folder = " + srcFolder + ", uid = " + uid + ", destination folder = " + destFolder + ", isCopy = " + isCopy); if (!isCopy && destFolder.equals(account.getTrashFolderName())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld doing special case for deleting message"); remoteMessage.delete(account.getTrashFolderName()); remoteSrcFolder.close(); return; } remoteDestFolder.open(OpenMode.READ_WRITE); if (remoteDestFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteDestFolder " + srcFolder + " read/write", true); } if (isCopy) { remoteSrcFolder.copyMessages(new Message[] { remoteMessage }, remoteDestFolder); } else { remoteSrcFolder.moveMessages(new Message[] { remoteMessage }, remoteDestFolder); } remoteSrcFolder.close(); remoteDestFolder.close(); } private void processPendingMarkAllAsRead(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; Folder remoteFolder = null; LocalFolder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = (LocalFolder) localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); Message[] messages = localFolder.getMessages(null, false); for (Message message : messages) { if (!message.isSet(Flag.SEEN)) { message.setFlag(Flag.SEEN, true); for (MessagingListener l : getListeners()) { l.listLocalMessagesUpdateMessage(account, folder, message); } } } for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, 0); } if (account.getErrorFolderName().equals(folder)) { return; } Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists() || !remoteFolder.isFlagSupported(Flag.SEEN)) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } remoteFolder.setFlags(new Flag[] {Flag.SEEN}, true); remoteFolder.close(); } catch (UnsupportedOperationException uoe) { Log.w(K9.LOG_TAG, "Could not mark all server-side as read because store doesn't support operation", uoe); } finally { closeFolder(localFolder); closeFolder(remoteFolder); } } private void notifyUserIfCertificateProblem(Context context, Exception e, Account account, boolean incoming) { if (!(e instanceof CertificateValidationException)) { return; } CertificateValidationException cve = (CertificateValidationException) e; if (!cve.needsUserAttention()) { return; } final int id = incoming ? K9.CERTIFICATE_EXCEPTION_NOTIFICATION_INCOMING + account.getAccountNumber() : K9.CERTIFICATE_EXCEPTION_NOTIFICATION_OUTGOING + account.getAccountNumber(); final Intent i = incoming ? AccountSetupIncoming.intentActionEditIncomingSettings(context, account) : AccountSetupOutgoing.intentActionEditOutgoingSettings(context, account); final PendingIntent pi = PendingIntent.getActivity(context, account.getAccountNumber(), i, PendingIntent.FLAG_UPDATE_CURRENT); final String title = context.getString( R.string.notification_certificate_error_title, account.getName()); final NotificationCompat.Builder builder = new NotificationBuilder(context); builder.setSmallIcon(R.drawable.ic_notify_new_mail); builder.setWhen(System.currentTimeMillis()); builder.setAutoCancel(true); builder.setTicker(title); builder.setContentTitle(title); builder.setContentText(context.getString(R.string.notification_certificate_error_text)); builder.setContentIntent(pi); configureNotification(builder, null, null, K9.NOTIFICATION_LED_FAILURE_COLOR, K9.NOTIFICATION_LED_BLINK_FAST, true); final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(null, id, builder.build()); } public void clearCertificateErrorNotifications(Context context, final Account account, boolean incoming, boolean outgoing) { final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (incoming) { nm.cancel(null, K9.CERTIFICATE_EXCEPTION_NOTIFICATION_INCOMING + account.getAccountNumber()); } if (outgoing) { nm.cancel(null, K9.CERTIFICATE_EXCEPTION_NOTIFICATION_OUTGOING + account.getAccountNumber()); } } static long uidfill = 0; static AtomicBoolean loopCatch = new AtomicBoolean(); public void addErrorMessage(Account account, String subject, Throwable t) { if (!loopCatch.compareAndSet(false, true)) { return; } try { if (t == null) { return; } CharArrayWriter baos = new CharArrayWriter(t.getStackTrace().length * 10); PrintWriter ps = new PrintWriter(baos); t.printStackTrace(ps); ps.close(); if (subject == null) { subject = getRootCauseMessage(t); } addErrorMessage(account, subject, baos.toString()); } catch (Throwable it) { Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it); } finally { loopCatch.set(false); } } public void addErrorMessage(Account account, String subject, String body) { if (!K9.ENABLE_ERROR_FOLDER) { return; } if (!loopCatch.compareAndSet(false, true)) { return; } try { if (body == null || body.length() < 1) { return; } Store localStore = account.getLocalStore(); LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName()); Message[] messages = new Message[1]; MimeMessage message = new MimeMessage(); message.setBody(new TextBody(body)); message.setFlag(Flag.X_DOWNLOADED_FULL, true); message.setSubject(subject); long nowTime = System.currentTimeMillis(); Date nowDate = new Date(nowTime); message.setInternalDate(nowDate); message.addSentDate(nowDate); message.setFrom(new Address(account.getEmail(), "K9mail internal")); messages[0] = message; localFolder.appendMessages(messages); localFolder.clearMessagesOlderThan(nowTime - (15 * 60 * 1000)); } catch (Throwable it) { Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it); } finally { loopCatch.set(false); } } public void markAllMessagesRead(final Account account, final String folder) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Marking all messages in " + account.getDescription() + ":" + folder + " as read"); List<String> args = new ArrayList<String>(); args.add(folder); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_MARK_ALL_AS_READ; command.arguments = args.toArray(EMPTY_STRING_ARRAY); queuePendingCommand(account, command); processPendingCommands(account); } public void setFlag(final Account account, final List<Long> messageIds, final Flag flag, final boolean newState) { setFlagInCache(account, messageIds, flag, newState); threadPool.execute(new Runnable() { @Override public void run() { setFlagSynchronous(account, messageIds, flag, newState, false); } }); } public void setFlagForThreads(final Account account, final List<Long> threadRootIds, final Flag flag, final boolean newState) { setFlagForThreadsInCache(account, threadRootIds, flag, newState); threadPool.execute(new Runnable() { @Override public void run() { setFlagSynchronous(account, threadRootIds, flag, newState, true); } }); } private void setFlagSynchronous(final Account account, final List<Long> ids, final Flag flag, final boolean newState, final boolean threadedList) { LocalStore localStore; try { localStore = account.getLocalStore(); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Couldn't get LocalStore instance", e); return; } // Update affected messages in the database. This should be as fast as possible so the UI // can be updated with the new state. try { if (threadedList) { localStore.setFlagForThreads(ids, flag, newState); removeFlagFromCache(account, ids, flag); } else { localStore.setFlag(ids, flag, newState); removeFlagForThreadsFromCache(account, ids, flag); } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Couldn't set flags in local database", e); } // Read folder name and UID of messages from the database Map<String, List<String>> folderMap; try { folderMap = localStore.getFoldersAndUids(ids, threadedList); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Couldn't get folder name and UID of messages", e); return; } // Loop over all folders for (Entry<String, List<String>> entry : folderMap.entrySet()) { String folderName = entry.getKey(); // Notify listeners of changed folder status LocalFolder localFolder = localStore.getFolder(folderName); try { int unreadMessageCount = localFolder.getUnreadMessageCount(); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folderName, unreadMessageCount); } } catch (MessagingException e) { Log.w(K9.LOG_TAG, "Couldn't get unread count for folder: " + folderName, e); } // The error folder is always a local folder // TODO: Skip the remote part for all local-only folders if (account.getErrorFolderName().equals(folderName)) { continue; } // Send flag change to server String[] uids = entry.getValue().toArray(EMPTY_STRING_ARRAY); queueSetFlag(account, folderName, Boolean.toString(newState), flag.toString(), uids); processPendingCommands(account); } } /** * Set or remove a flag for a set of messages in a specific folder. * * <p> * The {@link Message} objects passed in are updated to reflect the new flag state. * </p> * * @param account * The account the folder containing the messages belongs to. * @param folderName * The name of the folder. * @param messages * The messages to change the flag for. * @param flag * The flag to change. * @param newState * {@code true}, if the flag should be set. {@code false} if it should be removed. */ public void setFlag(Account account, String folderName, Message[] messages, Flag flag, boolean newState) { // TODO: Put this into the background, but right now some callers depend on the message // objects being modified right after this method returns. Folder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(folderName); localFolder.open(OpenMode.READ_WRITE); // Allows for re-allowing sending of messages that could not be sent if (flag == Flag.FLAGGED && !newState && account.getOutboxFolderName().equals(folderName)) { for (Message message : messages) { String uid = message.getUid(); if (uid != null) { sendCount.remove(uid); } } } // Update the messages in the local store localFolder.setFlags(messages, new Flag[] {flag}, newState); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folderName, localFolder.getUnreadMessageCount()); } /* * Handle the remote side */ // The error folder is always a local folder // TODO: Skip the remote part for all local-only folders if (account.getErrorFolderName().equals(folderName)) { return; } String[] uids = new String[messages.length]; for (int i = 0, end = uids.length; i < end; i++) { uids[i] = messages[i].getUid(); } queueSetFlag(account, folderName, Boolean.toString(newState), flag.toString(), uids); processPendingCommands(account); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException(me); } finally { closeFolder(localFolder); } } /** * Set or remove a flag for a message referenced by message UID. * * @param account * The account the folder containing the message belongs to. * @param folderName * The name of the folder. * @param uid * The UID of the message to change the flag for. * @param flag * The flag to change. * @param newState * {@code true}, if the flag should be set. {@code false} if it should be removed. */ public void setFlag(Account account, String folderName, String uid, Flag flag, boolean newState) { Folder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(folderName); localFolder.open(OpenMode.READ_WRITE); Message message = localFolder.getMessage(uid); if (message != null) { setFlag(account, folderName, new Message[] { message }, flag, newState); } } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException(me); } finally { closeFolder(localFolder); } } public void clearAllPending(final Account account) { try { Log.w(K9.LOG_TAG, "Clearing pending commands!"); LocalStore localStore = account.getLocalStore(); localStore.removePendingCommands(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to clear pending command", me); addErrorMessage(account, null, me); } } public void loadMessageForViewRemote(final Account account, final String folder, final String uid, final MessagingListener listener) { put("loadMessageForViewRemote", listener, new Runnable() { @Override public void run() { loadMessageForViewRemoteSynchronous(account, folder, uid, listener, false, false); } }); } public boolean loadMessageForViewRemoteSynchronous(final Account account, final String folder, final String uid, final MessagingListener listener, final boolean force, final boolean loadPartialFromSearch) { Folder remoteFolder = null; LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); Message message = localFolder.getMessage(uid); if (uid.startsWith(K9.LOCAL_UID_PREFIX)) { Log.w(K9.LOG_TAG, "Message has local UID so cannot download fully."); // ASH move toast android.widget.Toast.makeText(mApplication, "Message has local UID so cannot download fully", android.widget.Toast.LENGTH_LONG).show(); // TODO: Using X_DOWNLOADED_FULL is wrong because it's only a partial message. But // one we can't download completely. Maybe add a new flag; X_PARTIAL_MESSAGE ? message.setFlag(Flag.X_DOWNLOADED_FULL, true); message.setFlag(Flag.X_DOWNLOADED_PARTIAL, false); } /* commented out because this was pulled from another unmerged branch: } else if (localFolder.isLocalOnly() && !force) { Log.w(K9.LOG_TAG, "Message in local-only folder so cannot download fully."); // ASH move toast android.widget.Toast.makeText(mApplication, "Message in local-only folder so cannot download fully", android.widget.Toast.LENGTH_LONG).show(); message.setFlag(Flag.X_DOWNLOADED_FULL, true); message.setFlag(Flag.X_DOWNLOADED_PARTIAL, false); }*/ if (message.isSet(Flag.X_DOWNLOADED_FULL)) { /* * If the message has been synchronized since we were called we'll * just hand it back cause it's ready to go. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { message }, fp, null); } else { /* * At this point the message is not available, so we need to download it * fully if possible. */ Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); remoteFolder.open(OpenMode.READ_WRITE); // Get the remote message and fully download it Message remoteMessage = remoteFolder.getMessage(uid); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(new Message[] { remoteMessage }, fp, null); // Store the message locally and load the stored message into memory localFolder.appendMessages(new Message[] { remoteMessage }); if (loadPartialFromSearch) { fp.add(FetchProfile.Item.BODY); } fp.add(FetchProfile.Item.ENVELOPE); message = localFolder.getMessage(uid); localFolder.fetch(new Message[] { message }, fp, null); // Mark that this message is now fully synched if (account.isMarkMessageAsReadOnView()) { message.setFlag(Flag.SEEN, true); } message.setFlag(Flag.X_DOWNLOADED_FULL, true); } // now that we have the full message, refresh the headers for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewHeadersAvailable(account, folder, uid, message); } for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewBodyAvailable(account, folder, uid, message); } for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFinished(account, folder, uid, message); } return true; } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFailed(account, folder, uid, e); } notifyUserIfCertificateProblem(mApplication, e, account, true); addErrorMessage(account, null, e); return false; } finally { closeFolder(remoteFolder); closeFolder(localFolder); } } public void loadMessageForView(final Account account, final String folder, final String uid, final MessagingListener listener) { for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewStarted(account, folder, uid); } threadPool.execute(new Runnable() { @Override public void run() { try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); LocalMessage message = localFolder.getMessage(uid); if (message == null || message.getId() == 0) { throw new IllegalArgumentException("Message not found: folder=" + folder + ", uid=" + uid); } // IMAP search results will usually need to be downloaded before viewing. // TODO: limit by account.getMaximumAutoDownloadMessageSize(). if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL)) { if (loadMessageForViewRemoteSynchronous(account, folder, uid, listener, false, true)) { markMessageAsReadOnView(account, message); } return; } markMessageAsReadOnView(account, message); for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewHeadersAvailable(account, folder, uid, message); } FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { message }, fp, null); localFolder.close(); for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewBodyAvailable(account, folder, uid, message); } for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFinished(account, folder, uid, message); } } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFailed(account, folder, uid, e); } addErrorMessage(account, null, e); } } }); } /** * Mark the provided message as read if not disabled by the account setting. * * @param account * The account the message belongs to. * @param message * The message to mark as read. This {@link Message} instance will be modify by calling * {@link Message#setFlag(Flag, boolean)} on it. * * @throws MessagingException * * @see Account#isMarkMessageAsReadOnView() */ private void markMessageAsReadOnView(Account account, Message message) throws MessagingException { if (account.isMarkMessageAsReadOnView() && !message.isSet(Flag.SEEN)) { message.setFlag(Flag.SEEN, true); setFlagSynchronous(account, Collections.singletonList(Long.valueOf(message.getId())), Flag.SEEN, true, false); } } /** * Attempts to load the attachment specified by part from the given account and message. * @param account * @param message * @param part * @param listener */ public void loadAttachment( final Account account, final Message message, final Part part, final Object tag, final MessagingListener listener) { /* * Check if the attachment has already been downloaded. If it has there's no reason to * download it, so we just tell the listener that it's ready to go. */ if (part.getBody() != null) { for (MessagingListener l : getListeners(listener)) { l.loadAttachmentStarted(account, message, part, tag, false); } for (MessagingListener l : getListeners(listener)) { l.loadAttachmentFinished(account, message, part, tag); } return; } for (MessagingListener l : getListeners(listener)) { l.loadAttachmentStarted(account, message, part, tag, true); } put("loadAttachment", listener, new Runnable() { @Override public void run() { Folder remoteFolder = null; LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); List<Part> attachments = MimeUtility.collectAttachments(message); for (Part attachment : attachments) { attachment.setBody(null); } Store remoteStore = account.getRemoteStore(); localFolder = localStore.getFolder(message.getFolder().getName()); remoteFolder = remoteStore.getFolder(message.getFolder().getName()); remoteFolder.open(OpenMode.READ_WRITE); //FIXME: This is an ugly hack that won't be needed once the Message objects have been united. Message remoteMessage = remoteFolder.getMessage(message.getUid()); remoteMessage.setBody(message.getBody()); remoteFolder.fetchPart(remoteMessage, part, null); localFolder.updateMessage((LocalMessage)message); for (MessagingListener l : getListeners(listener)) { l.loadAttachmentFinished(account, message, part, tag); } } catch (MessagingException me) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Exception loading attachment", me); for (MessagingListener l : getListeners(listener)) { l.loadAttachmentFailed(account, message, part, tag, me.getMessage()); } notifyUserIfCertificateProblem(mApplication, me, account, true); addErrorMessage(account, null, me); } finally { closeFolder(localFolder); closeFolder(remoteFolder); } } }); } /** * Stores the given message in the Outbox and starts a sendPendingMessages command to * attempt to send the message. * @param account * @param message * @param listener */ public void sendMessage(final Account account, final Message message, MessagingListener listener) { try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(account.getOutboxFolderName()); localFolder.open(OpenMode.READ_WRITE); localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); localFolder.close(); sendPendingMessages(account, listener); } catch (Exception e) { /* for (MessagingListener l : getListeners()) { // TODO general failed } */ addErrorMessage(account, null, e); } } public void sendPendingMessages(MessagingListener listener) { final Preferences prefs = Preferences.getPreferences(mApplication.getApplicationContext()); for (Account account : prefs.getAvailableAccounts()) { sendPendingMessages(account, listener); } } /** * Attempt to send any messages that are sitting in the Outbox. * @param account * @param listener */ public void sendPendingMessages(final Account account, MessagingListener listener) { putBackground("sendPendingMessages", listener, new Runnable() { @Override public void run() { if (!account.isAvailable(mApplication)) { throw new UnavailableAccountException(); } if (messagesPendingSend(account)) { notifyWhileSending(account); try { sendPendingMessagesSynchronous(account); } finally { notifyWhileSendingDone(account); } } } }); } private void cancelNotification(int id) { NotificationManager notifMgr = (NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE); notifMgr.cancel(id); } private void notifyWhileSendingDone(Account account) { if (account.isShowOngoing()) { cancelNotification(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber()); } } /** * Display an ongoing notification while a message is being sent. * * @param account * The account the message is sent from. Never {@code null}. */ private void notifyWhileSending(Account account) { if (!account.isShowOngoing()) { return; } NotificationManager notifMgr = (NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationBuilder(mApplication); builder.setSmallIcon(R.drawable.ic_notify_check_mail); builder.setWhen(System.currentTimeMillis()); builder.setOngoing(true); builder.setTicker(mApplication.getString(R.string.notification_bg_send_ticker, account.getDescription())); builder.setContentTitle(mApplication.getString(R.string.notification_bg_send_title)); builder.setContentText(account.getDescription()); LocalSearch search = new LocalSearch(account.getInboxFolderName()); search.addAllowedFolder(account.getInboxFolderName()); search.addAccountUuid(account.getUuid()); Intent intent = MessageList.intentDisplaySearch(mApplication, search, false, true, true); PendingIntent pi = PendingIntent.getActivity(mApplication, 0, intent, 0); builder.setContentIntent(pi); if (K9.NOTIFICATION_LED_WHILE_SYNCING) { configureNotification(builder, null, null, account.getNotificationSetting().getLedColor(), K9.NOTIFICATION_LED_BLINK_FAST, true); } notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(), builder.build()); } private void notifySendTempFailed(Account account, Exception lastFailure) { notifySendFailed(account, lastFailure, account.getOutboxFolderName()); } private void notifySendPermFailed(Account account, Exception lastFailure) { notifySendFailed(account, lastFailure, account.getDraftsFolderName()); } /** * Display a notification when sending a message has failed. * * @param account * The account that was used to sent the message. * @param lastFailure * The {@link Exception} instance that indicated sending the message has failed. * @param openFolder * The name of the folder to open when the notification is clicked. */ private void notifySendFailed(Account account, Exception lastFailure, String openFolder) { NotificationManager notifMgr = (NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationBuilder(mApplication); builder.setSmallIcon(R.drawable.ic_notify_new_mail); builder.setWhen(System.currentTimeMillis()); builder.setAutoCancel(true); builder.setTicker(mApplication.getString(R.string.send_failure_subject)); builder.setContentTitle(mApplication.getString(R.string.send_failure_subject)); builder.setContentText(getRootCauseMessage(lastFailure)); Intent i = FolderList.actionHandleNotification(mApplication, account, openFolder); PendingIntent pi = PendingIntent.getActivity(mApplication, 0, i, 0); builder.setContentIntent(pi); configureNotification(builder, null, null, K9.NOTIFICATION_LED_FAILURE_COLOR, K9.NOTIFICATION_LED_BLINK_FAST, true); notifMgr.notify(K9.SEND_FAILED_NOTIFICATION - account.getAccountNumber(), builder.build()); } /** * Display an ongoing notification while checking for new messages on the server. * * @param account * The account that is checked for new messages. Never {@code null}. * @param folder * The folder that is being checked for new messages. Never {@code null}. */ private void notifyFetchingMail(final Account account, final Folder folder) { if (!account.isShowOngoing()) { return; } final NotificationManager notifMgr = (NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationBuilder(mApplication); builder.setSmallIcon(R.drawable.ic_notify_check_mail); builder.setWhen(System.currentTimeMillis()); builder.setOngoing(true); builder.setTicker(mApplication.getString( R.string.notification_bg_sync_ticker, account.getDescription(), folder.getName())); builder.setContentTitle(mApplication.getString(R.string.notification_bg_sync_title)); builder.setContentText(account.getDescription() + mApplication.getString(R.string.notification_bg_title_separator) + folder.getName()); LocalSearch search = new LocalSearch(account.getInboxFolderName()); search.addAllowedFolder(account.getInboxFolderName()); search.addAccountUuid(account.getUuid()); Intent intent = MessageList.intentDisplaySearch(mApplication, search, false, true, true); PendingIntent pi = PendingIntent.getActivity(mApplication, 0, intent, 0); builder.setContentIntent(pi); if (K9.NOTIFICATION_LED_WHILE_SYNCING) { configureNotification(builder, null, null, account.getNotificationSetting().getLedColor(), K9.NOTIFICATION_LED_BLINK_FAST, true); } notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(), builder.build()); } private void notifyFetchingMailCancel(final Account account) { if (account.isShowOngoing()) { cancelNotification(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber()); } } public boolean messagesPendingSend(final Account account) { Folder localFolder = null; try { localFolder = account.getLocalStore().getFolder( account.getOutboxFolderName()); if (!localFolder.exists()) { return false; } localFolder.open(OpenMode.READ_WRITE); if (localFolder.getMessageCount() > 0) { return true; } } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while checking for unsent messages", e); } finally { closeFolder(localFolder); } return false; } /** * Attempt to send any messages that are sitting in the Outbox. * @param account */ public void sendPendingMessagesSynchronous(final Account account) { Folder localFolder = null; Exception lastFailure = null; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder( account.getOutboxFolderName()); if (!localFolder.exists()) { return; } for (MessagingListener l : getListeners()) { l.sendPendingMessagesStarted(account); } localFolder.open(OpenMode.READ_WRITE); Message[] localMessages = localFolder.getMessages(null); int progress = 0; int todo = localMessages.length; for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo); } /* * The profile we will use to pull all of the content * for a given local message into memory for sending. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Scanning folder '" + account.getOutboxFolderName() + "' (" + ((LocalFolder)localFolder).getId() + ") for messages to send"); Transport transport = Transport.getInstance(account); for (Message message : localMessages) { if (message.isSet(Flag.DELETED)) { message.destroy(); continue; } try { AtomicInteger count = new AtomicInteger(0); AtomicInteger oldCount = sendCount.putIfAbsent(message.getUid(), count); if (oldCount != null) { count = oldCount; } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Send count for message " + message.getUid() + " is " + count.get()); if (count.incrementAndGet() > K9.MAX_SEND_ATTEMPTS) { Log.e(K9.LOG_TAG, "Send count for message " + message.getUid() + " can't be delivered after " + K9.MAX_SEND_ATTEMPTS + " attempts. Giving up until the user restarts the device"); notifySendTempFailed(account, new MessagingException(message.getSubject())); continue; } localFolder.fetch(new Message[] { message }, fp, null); try { if (message.getHeader(K9.IDENTITY_HEADER) != null) { Log.v(K9.LOG_TAG, "The user has set the Outbox and Drafts folder to the same thing. " + "This message appears to be a draft, so K-9 will not send it"); continue; } message.setFlag(Flag.X_SEND_IN_PROGRESS, true); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Sending message with UID " + message.getUid()); transport.sendMessage(message); message.setFlag(Flag.X_SEND_IN_PROGRESS, false); message.setFlag(Flag.SEEN, true); progress++; for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo); } if (!account.hasSentFolder()) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Account does not have a sent mail folder; deleting sent message"); message.setFlag(Flag.DELETED, true); } else { LocalFolder localSentFolder = (LocalFolder) localStore.getFolder(account.getSentFolderName()); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Moving sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") "); localFolder.moveMessages(new Message[] { message }, localSentFolder); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Moved sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") "); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; command.arguments = new String[] { localSentFolder.getName(), message.getUid() }; queuePendingCommand(account, command); processPendingCommands(account); } } catch (Exception e) { // 5.x.x errors from the SMTP server are "PERMFAIL" // move the message over to drafts rather than leaving it in the outbox // This is a complete hack, but is worlds better than the previous // "don't even bother" functionality if (getRootCauseMessage(e).startsWith("5")) { localFolder.moveMessages(new Message[] { message }, (LocalFolder) localStore.getFolder(account.getDraftsFolderName())); } notifyUserIfCertificateProblem(mApplication, e, account, false); message.setFlag(Flag.X_SEND_FAILED, true); Log.e(K9.LOG_TAG, "Failed to send message", e); for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed(account, localFolder.getName(), getRootCauseMessage(e)); } lastFailure = e; } } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to fetch message for sending", e); for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed(account, localFolder.getName(), getRootCauseMessage(e)); } lastFailure = e; } } for (MessagingListener l : getListeners()) { l.sendPendingMessagesCompleted(account); } if (lastFailure != null) { if (getRootCauseMessage(lastFailure).startsWith("5")) { notifySendPermFailed(account, lastFailure); } else { notifySendTempFailed(account, lastFailure); } } } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to send pending messages because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { for (MessagingListener l : getListeners()) { l.sendPendingMessagesFailed(account); } addErrorMessage(account, null, e); } finally { if (lastFailure == null) { cancelNotification(K9.SEND_FAILED_NOTIFICATION - account.getAccountNumber()); } closeFolder(localFolder); } } public void getAccountStats(final Context context, final Account account, final MessagingListener listener) { threadPool.execute(new Runnable() { @Override public void run() { try { AccountStats stats = account.getStats(context); listener.accountStatusChanged(account, stats); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me); } } }); } public void getSearchAccountStats(final SearchAccount searchAccount, final MessagingListener listener) { threadPool.execute(new Runnable() { @Override public void run() { getSearchAccountStatsSynchronous(searchAccount, listener); } }); } public AccountStats getSearchAccountStatsSynchronous(final SearchAccount searchAccount, final MessagingListener listener) { Preferences preferences = Preferences.getPreferences(mApplication); LocalSearch search = searchAccount.getRelatedSearch(); // Collect accounts that belong to the search String[] accountUuids = search.getAccountUuids(); Account[] accounts; if (search.searchAllAccounts()) { accounts = preferences.getAccounts(); } else { accounts = new Account[accountUuids.length]; for (int i = 0, len = accountUuids.length; i < len; i++) { String accountUuid = accountUuids[i]; accounts[i] = preferences.getAccount(accountUuid); } } ContentResolver cr = mApplication.getContentResolver(); int unreadMessageCount = 0; int flaggedMessageCount = 0; String[] projection = { StatsColumns.UNREAD_COUNT, StatsColumns.FLAGGED_COUNT }; for (Account account : accounts) { StringBuilder query = new StringBuilder(); List<String> queryArgs = new ArrayList<String>(); ConditionsTreeNode conditions = search.getConditions(); SqlQueryBuilder.buildWhereClause(account, conditions, query, queryArgs); String selection = query.toString(); String[] selectionArgs = queryArgs.toArray(EMPTY_STRING_ARRAY); Uri uri = Uri.withAppendedPath(EmailProvider.CONTENT_URI, "account/" + account.getUuid() + "/stats"); // Query content provider to get the account stats Cursor cursor = cr.query(uri, projection, selection, selectionArgs, null); try { if (cursor.moveToFirst()) { unreadMessageCount += cursor.getInt(0); flaggedMessageCount += cursor.getInt(1); } } finally { cursor.close(); } } // Create AccountStats instance... AccountStats stats = new AccountStats(); stats.unreadMessageCount = unreadMessageCount; stats.flaggedMessageCount = flaggedMessageCount; // ...and notify the listener if (listener != null) { listener.accountStatusChanged(searchAccount, stats); } return stats; } public void getFolderUnreadMessageCount(final Account account, final String folderName, final MessagingListener l) { Runnable unreadRunnable = new Runnable() { @Override public void run() { int unreadMessageCount = 0; try { Folder localFolder = account.getLocalStore().getFolder(folderName); unreadMessageCount = localFolder.getUnreadMessageCount(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me); } l.folderStatusChanged(account, folderName, unreadMessageCount); } }; put("getFolderUnread:" + account.getDescription() + ":" + folderName, l, unreadRunnable); } public boolean isMoveCapable(Message message) { return !message.getUid().startsWith(K9.LOCAL_UID_PREFIX); } public boolean isCopyCapable(Message message) { return isMoveCapable(message); } public boolean isMoveCapable(final Account account) { try { Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); return localStore.isMoveCapable() && remoteStore.isMoveCapable(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Exception while ascertaining move capability", me); return false; } } public boolean isCopyCapable(final Account account) { try { Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); return localStore.isCopyCapable() && remoteStore.isCopyCapable(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Exception while ascertaining copy capability", me); return false; } } public void moveMessages(final Account account, final String srcFolder, final List<Message> messages, final String destFolder, final MessagingListener listener) { suppressMessages(account, messages); putBackground("moveMessages", null, new Runnable() { @Override public void run() { moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, false, listener); } }); } public void moveMessagesInThread(final Account account, final String srcFolder, final List<Message> messages, final String destFolder) { suppressMessages(account, messages); putBackground("moveMessagesInThread", null, new Runnable() { @Override public void run() { try { List<Message> messagesInThreads = collectMessagesInThreads(account, messages); moveOrCopyMessageSynchronous(account, srcFolder, messagesInThreads, destFolder, false, null); } catch (MessagingException e) { addErrorMessage(account, "Exception while moving messages", e); } } }); } public void moveMessage(final Account account, final String srcFolder, final Message message, final String destFolder, final MessagingListener listener) { moveMessages(account, srcFolder, Collections.singletonList(message), destFolder, listener); } public void copyMessages(final Account account, final String srcFolder, final List<Message> messages, final String destFolder, final MessagingListener listener) { putBackground("copyMessages", null, new Runnable() { @Override public void run() { moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, true, listener); } }); } public void copyMessagesInThread(final Account account, final String srcFolder, final List<Message> messages, final String destFolder) { putBackground("copyMessagesInThread", null, new Runnable() { @Override public void run() { try { List<Message> messagesInThreads = collectMessagesInThreads(account, messages); moveOrCopyMessageSynchronous(account, srcFolder, messagesInThreads, destFolder, true, null); } catch (MessagingException e) { addErrorMessage(account, "Exception while copying messages", e); } } }); } public void copyMessage(final Account account, final String srcFolder, final Message message, final String destFolder, final MessagingListener listener) { copyMessages(account, srcFolder, Collections.singletonList(message), destFolder, listener); } private void moveOrCopyMessageSynchronous(final Account account, final String srcFolder, final List<Message> inMessages, final String destFolder, final boolean isCopy, MessagingListener listener) { try { Map<String, String> uidMap = new HashMap<String, String>(); Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); if (!isCopy && (!remoteStore.isMoveCapable() || !localStore.isMoveCapable())) { return; } if (isCopy && (!remoteStore.isCopyCapable() || !localStore.isCopyCapable())) { return; } Folder localSrcFolder = localStore.getFolder(srcFolder); Folder localDestFolder = localStore.getFolder(destFolder); boolean unreadCountAffected = false; List<String> uids = new LinkedList<String>(); for (Message message : inMessages) { String uid = message.getUid(); if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { uids.add(uid); } if (!unreadCountAffected && !message.isSet(Flag.SEEN)) { unreadCountAffected = true; } } Message[] messages = localSrcFolder.getMessages(uids.toArray(EMPTY_STRING_ARRAY), null); if (messages.length > 0) { Map<String, Message> origUidMap = new HashMap<String, Message>(); for (Message message : messages) { origUidMap.put(message.getUid(), message); } if (K9.DEBUG) Log.i(K9.LOG_TAG, "moveOrCopyMessageSynchronous: source folder = " + srcFolder + ", " + messages.length + " messages, " + ", destination folder = " + destFolder + ", isCopy = " + isCopy); if (isCopy) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localSrcFolder.fetch(messages, fp, null); uidMap = localSrcFolder.copyMessages(messages, localDestFolder); if (unreadCountAffected) { // If this copy operation changes the unread count in the destination // folder, notify the listeners. int unreadMessageCount = localDestFolder.getUnreadMessageCount(); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, destFolder, unreadMessageCount); } } } else { uidMap = localSrcFolder.moveMessages(messages, localDestFolder); for (Map.Entry<String, Message> entry : origUidMap.entrySet()) { String origUid = entry.getKey(); Message message = entry.getValue(); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, srcFolder, origUid, message.getUid()); } } unsuppressMessages(account, messages); if (unreadCountAffected) { // If this move operation changes the unread count, notify the listeners // that the unread count changed in both the source and destination folder. int unreadMessageCountSrc = localSrcFolder.getUnreadMessageCount(); int unreadMessageCountDest = localDestFolder.getUnreadMessageCount(); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, srcFolder, unreadMessageCountSrc); l.folderStatusChanged(account, destFolder, unreadMessageCountDest); } } } queueMoveOrCopy(account, srcFolder, destFolder, isCopy, origUidMap.keySet().toArray(EMPTY_STRING_ARRAY), uidMap); } processPendingCommands(account); } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to move/copy message because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Error moving message", me); } } public void expunge(final Account account, final String folder, final MessagingListener listener) { putBackground("expunge", null, new Runnable() { @Override public void run() { queueExpunge(account, folder); } }); } public void deleteDraft(final Account account, long id) { LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(account.getDraftsFolderName()); localFolder.open(OpenMode.READ_WRITE); String uid = localFolder.getMessageUidById(id); if (uid != null) { Message message = localFolder.getMessage(uid); if (message != null) { deleteMessages(Collections.singletonList(message), null); } } } catch (MessagingException me) { addErrorMessage(account, null, me); } finally { closeFolder(localFolder); } } public void deleteThreads(final List<Message> messages) { actOnMessages(messages, new MessageActor() { @Override public void act(final Account account, final Folder folder, final List<Message> accountMessages) { suppressMessages(account, messages); putBackground("deleteThreads", null, new Runnable() { @Override public void run() { deleteThreadsSynchronous(account, folder.getName(), accountMessages); } }); } }); } public void deleteThreadsSynchronous(Account account, String folderName, List<Message> messages) { try { List<Message> messagesToDelete = collectMessagesInThreads(account, messages); deleteMessagesSynchronous(account, folderName, messagesToDelete.toArray(EMPTY_MESSAGE_ARRAY), null); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Something went wrong while deleting threads", e); } } public List<Message> collectMessagesInThreads(Account account, List<Message> messages) throws MessagingException { LocalStore localStore = account.getLocalStore(); List<Message> messagesInThreads = new ArrayList<Message>(); for (Message message : messages) { LocalMessage localMessage = (LocalMessage) message; long rootId = localMessage.getRootId(); long threadId = (rootId == -1) ? localMessage.getThreadId() : rootId; Message[] messagesInThread = localStore.getMessagesInThread(threadId); Collections.addAll(messagesInThreads, messagesInThread); } return messagesInThreads; } public void deleteMessages(final List<Message> messages, final MessagingListener listener) { actOnMessages(messages, new MessageActor() { @Override public void act(final Account account, final Folder folder, final List<Message> accountMessages) { suppressMessages(account, messages); putBackground("deleteMessages", null, new Runnable() { @Override public void run() { deleteMessagesSynchronous(account, folder.getName(), accountMessages.toArray(EMPTY_MESSAGE_ARRAY), listener); } }); } }); } private void deleteMessagesSynchronous(final Account account, final String folder, final Message[] messages, MessagingListener listener) { Folder localFolder = null; Folder localTrashFolder = null; String[] uids = getUidsFromMessages(messages); try { //We need to make these callbacks before moving the messages to the trash //as messages get a new UID after being moved for (Message message : messages) { for (MessagingListener l : getListeners(listener)) { l.messageDeleted(account, folder, message); } } Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); Map<String, String> uidMap = null; if (folder.equals(account.getTrashFolderName()) || !account.hasTrashFolder()) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Deleting messages in trash folder or trash set to -None-, not copying"); localFolder.setFlags(messages, new Flag[] { Flag.DELETED }, true); } else { localTrashFolder = localStore.getFolder(account.getTrashFolderName()); if (!localTrashFolder.exists()) { localTrashFolder.create(Folder.FolderType.HOLDS_MESSAGES); } if (localTrashFolder.exists()) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Deleting messages in normal folder, moving"); uidMap = localFolder.moveMessages(messages, localTrashFolder); } } for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, localFolder.getUnreadMessageCount()); if (localTrashFolder != null) { l.folderStatusChanged(account, account.getTrashFolderName(), localTrashFolder.getUnreadMessageCount()); } } if (K9.DEBUG) Log.d(K9.LOG_TAG, "Delete policy for account " + account.getDescription() + " is " + account.getDeletePolicy()); if (folder.equals(account.getOutboxFolderName())) { for (Message message : messages) { // If the message was in the Outbox, then it has been copied to local Trash, and has // to be copied to remote trash PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; command.arguments = new String[] { account.getTrashFolderName(), message.getUid() }; queuePendingCommand(account, command); } processPendingCommands(account); } else if (account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE) { if (folder.equals(account.getTrashFolderName())) { queueSetFlag(account, folder, Boolean.toString(true), Flag.DELETED.toString(), uids); } else { queueMoveOrCopy(account, folder, account.getTrashFolderName(), false, uids, uidMap); } processPendingCommands(account); } else if (account.getDeletePolicy() == Account.DELETE_POLICY_MARK_AS_READ) { queueSetFlag(account, folder, Boolean.toString(true), Flag.SEEN.toString(), uids); processPendingCommands(account); } else { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Delete policy " + account.getDeletePolicy() + " prevents delete from server"); } unsuppressMessages(account, messages); } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to delete message because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Error deleting message from local store.", me); } finally { closeFolder(localFolder); closeFolder(localTrashFolder); } } private String[] getUidsFromMessages(Message[] messages) { String[] uids = new String[messages.length]; for (int i = 0; i < messages.length; i++) { uids[i] = messages[i].getUid(); } return uids; } private void processPendingEmptyTrash(PendingCommand command, Account account) throws MessagingException { Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(account.getTrashFolderName()); try { if (remoteFolder.exists()) { remoteFolder.open(OpenMode.READ_WRITE); remoteFolder.setFlags(new Flag [] { Flag.DELETED }, true); if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { remoteFolder.expunge(); } // When we empty trash, we need to actually synchronize the folder // or local deletes will never get cleaned up synchronizeFolder(account, remoteFolder, true, 0, null); compact(account, null); } } finally { closeFolder(remoteFolder); } } public void emptyTrash(final Account account, MessagingListener listener) { putBackground("emptyTrash", listener, new Runnable() { @Override public void run() { LocalFolder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = (LocalFolder) localStore.getFolder(account.getTrashFolderName()); localFolder.open(OpenMode.READ_WRITE); boolean isTrashLocalOnly = isTrashLocalOnly(account); if (isTrashLocalOnly) { localFolder.clearAllMessages(); } else { localFolder.setFlags(new Flag[] { Flag.DELETED }, true); } for (MessagingListener l : getListeners()) { l.emptyTrashCompleted(account); } if (!isTrashLocalOnly) { List<String> args = new ArrayList<String>(); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_EMPTY_TRASH; command.arguments = args.toArray(EMPTY_STRING_ARRAY); queuePendingCommand(account, command); processPendingCommands(account); } } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to empty trash because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { Log.e(K9.LOG_TAG, "emptyTrash failed", e); addErrorMessage(account, null, e); } finally { closeFolder(localFolder); } } }); } /** * Find out whether the account type only supports a local Trash folder. * * <p>Note: Currently this is only the case for POP3 accounts.</p> * * @param account * The account to check. * * @return {@code true} if the account only has a local Trash folder that is not synchronized * with a folder on the server. {@code false} otherwise. * * @throws MessagingException * In case of an error. */ private boolean isTrashLocalOnly(Account account) throws MessagingException { // TODO: Get rid of the tight coupling once we properly support local folders return (account.getRemoteStore() instanceof Pop3Store); } public void sendAlternate(final Context context, Account account, Message message) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "About to load message " + account.getDescription() + ":" + message.getFolder().getName() + ":" + message.getUid() + " for sendAlternate"); loadMessageForView(account, message.getFolder().getName(), message.getUid(), new MessagingListener() { @Override public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, Message message) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got message " + account.getDescription() + ":" + folder + ":" + message.getUid() + " for sendAlternate"); try { Intent msg = new Intent(Intent.ACTION_SEND); String quotedText = null; Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain"); if (part == null) { part = MimeUtility.findFirstPartByMimeType(message, "text/html"); } if (part != null) { quotedText = MimeUtility.getTextFromPart(part); } if (quotedText != null) { msg.putExtra(Intent.EXTRA_TEXT, quotedText); } msg.putExtra(Intent.EXTRA_SUBJECT, message.getSubject()); Address[] from = message.getFrom(); String[] senders = new String[from.length]; for (int i = 0; i < from.length; i++) { senders[i] = from[i].toString(); } msg.putExtra(Intents.Share.EXTRA_FROM, senders); Address[] to = message.getRecipients(RecipientType.TO); String[] recipientsTo = new String[to.length]; for (int i = 0; i < to.length; i++) { recipientsTo[i] = to[i].toString(); } msg.putExtra(Intent.EXTRA_EMAIL, recipientsTo); Address[] cc = message.getRecipients(RecipientType.CC); String[] recipientsCc = new String[cc.length]; for (int i = 0; i < cc.length; i++) { recipientsCc[i] = cc[i].toString(); } msg.putExtra(Intent.EXTRA_CC, recipientsCc); msg.setType("text/plain"); context.startActivity(Intent.createChooser(msg, context.getString(R.string.send_alternate_chooser_title))); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to send email through alternate program", me); } } }); } /** * Checks mail for one or multiple accounts. If account is null all accounts * are checked. * * @param context * @param account * @param listener */ public void checkMail(final Context context, final Account account, final boolean ignoreLastCheckedTime, final boolean useManualWakeLock, final MessagingListener listener) { TracingWakeLock twakeLock = null; if (useManualWakeLock) { TracingPowerManager pm = TracingPowerManager.getPowerManager(context); twakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "K9 MessagingController.checkMail"); twakeLock.setReferenceCounted(false); twakeLock.acquire(K9.MANUAL_WAKE_LOCK_TIMEOUT); } final TracingWakeLock wakeLock = twakeLock; for (MessagingListener l : getListeners()) { l.checkMailStarted(context, account); } putBackground("checkMail", listener, new Runnable() { @Override public void run() { try { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Starting mail check"); Preferences prefs = Preferences.getPreferences(context); Collection<Account> accounts; if (account != null) { accounts = new ArrayList<Account>(1); accounts.add(account); } else { accounts = prefs.getAvailableAccounts(); } for (final Account account : accounts) { checkMailForAccount(context, account, ignoreLastCheckedTime, prefs, listener); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to synchronize mail", e); addErrorMessage(account, null, e); } putBackground("finalize sync", null, new Runnable() { @Override public void run() { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Finished mail sync"); if (wakeLock != null) { wakeLock.release(); } for (MessagingListener l : getListeners()) { l.checkMailFinished(context, account); } } } ); } }); } private void checkMailForAccount(final Context context, final Account account, final boolean ignoreLastCheckedTime, final Preferences prefs, final MessagingListener listener) { if (!account.isAvailable(context)) { if (K9.DEBUG) { Log.i(K9.LOG_TAG, "Skipping synchronizing unavailable account " + account.getDescription()); } return; } final long accountInterval = account.getAutomaticCheckIntervalMinutes() * 60 * 1000; if (!ignoreLastCheckedTime && accountInterval <= 0) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Skipping synchronizing account " + account.getDescription()); return; } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Synchronizing account " + account.getDescription()); account.setRingNotified(false); sendPendingMessages(account, listener); try { Account.FolderMode aDisplayMode = account.getFolderDisplayMode(); Account.FolderMode aSyncMode = account.getFolderSyncMode(); Store localStore = account.getLocalStore(); for (final Folder folder : localStore.getPersonalNamespaces(false)) { folder.open(Folder.OpenMode.READ_WRITE); folder.refresh(prefs); Folder.FolderClass fDisplayClass = folder.getDisplayClass(); Folder.FolderClass fSyncClass = folder.getSyncClass(); if (modeMismatch(aDisplayMode, fDisplayClass)) { // Never sync a folder that isn't displayed /* if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() + " which is in display mode " + fDisplayClass + " while account is in display mode " + aDisplayMode); */ continue; } if (modeMismatch(aSyncMode, fSyncClass)) { // Do not sync folders in the wrong class /* if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() + " which is in sync mode " + fSyncClass + " while account is in sync mode " + aSyncMode); */ continue; } synchronizeFolder(account, folder, ignoreLastCheckedTime, accountInterval, listener); } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to synchronize account " + account.getName(), e); addErrorMessage(account, null, e); } finally { putBackground("clear notification flag for " + account.getDescription(), null, new Runnable() { @Override public void run() { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Clearing notification flag for " + account.getDescription()); account.setRingNotified(false); try { AccountStats stats = account.getStats(context); if (stats == null || stats.unreadMessageCount == 0) { notifyAccountCancel(context, account); } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e); } } } ); } } private void synchronizeFolder( final Account account, final Folder folder, final boolean ignoreLastCheckedTime, final long accountInterval, final MessagingListener listener) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Folder " + folder.getName() + " was last synced @ " + new Date(folder.getLastChecked())); if (!ignoreLastCheckedTime && folder.getLastChecked() > (System.currentTimeMillis() - accountInterval)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() + ", previously synced @ " + new Date(folder.getLastChecked()) + " which would be too recent for the account period"); return; } putBackground("sync" + folder.getName(), null, new Runnable() { @Override public void run() { LocalFolder tLocalFolder = null; try { // In case multiple Commands get enqueued, don't run more than // once final LocalStore localStore = account.getLocalStore(); tLocalFolder = localStore.getFolder(folder.getName()); tLocalFolder.open(Folder.OpenMode.READ_WRITE); if (!ignoreLastCheckedTime && tLocalFolder.getLastChecked() > (System.currentTimeMillis() - accountInterval)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not running Command for folder " + folder.getName() + ", previously synced @ " + new Date(folder.getLastChecked()) + " which would be too recent for the account period"); return; } notifyFetchingMail(account, folder); try { synchronizeMailboxSynchronous(account, folder.getName(), listener, null); } finally { notifyFetchingMailCancel(account); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while processing folder " + account.getDescription() + ":" + folder.getName(), e); addErrorMessage(account, null, e); } finally { closeFolder(tLocalFolder); } } } ); } public void compact(final Account account, final MessagingListener ml) { putBackground("compact:" + account.getDescription(), ml, new Runnable() { @Override public void run() { try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.compact(); long newSize = localStore.getSize(); for (MessagingListener l : getListeners(ml)) { l.accountSizeChanged(account, oldSize, newSize); } } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to compact account because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to compact account " + account.getDescription(), e); } } }); } public void clear(final Account account, final MessagingListener ml) { putBackground("clear:" + account.getDescription(), ml, new Runnable() { @Override public void run() { try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.clear(); localStore.resetVisibleLimits(account.getDisplayCount()); long newSize = localStore.getSize(); AccountStats stats = new AccountStats(); stats.size = newSize; stats.unreadMessageCount = 0; stats.flaggedMessageCount = 0; for (MessagingListener l : getListeners(ml)) { l.accountSizeChanged(account, oldSize, newSize); l.accountStatusChanged(account, stats); } } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to clear account because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to clear account " + account.getDescription(), e); } } }); } public void recreate(final Account account, final MessagingListener ml) { putBackground("recreate:" + account.getDescription(), ml, new Runnable() { @Override public void run() { try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.recreate(); localStore.resetVisibleLimits(account.getDisplayCount()); long newSize = localStore.getSize(); AccountStats stats = new AccountStats(); stats.size = newSize; stats.unreadMessageCount = 0; stats.flaggedMessageCount = 0; for (MessagingListener l : getListeners(ml)) { l.accountSizeChanged(account, oldSize, newSize); l.accountStatusChanged(account, stats); } } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to recreate an account because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to recreate account " + account.getDescription(), e); } } }); } private boolean shouldNotifyForMessage(Account account, LocalFolder localFolder, Message message) { // If we don't even have an account name, don't show the notification. // (This happens during initial account setup) if (account.getName() == null) { return false; } // Do not notify if the user does not have notifications enabled or if the message has // been read. if (!account.isNotifyNewMail() || message.isSet(Flag.SEEN)) { return false; } // If the account is a POP3 account and the message is older than the oldest message we've // previously seen, then don't notify about it. if (account.getStoreUri().startsWith("pop3") && message.olderThan(new Date(account.getLatestOldMessageSeenTime()))) { return false; } // No notification for new messages in Trash, Drafts, Spam or Sent folder. // But do notify if it's the INBOX (see issue 1817). Folder folder = message.getFolder(); if (folder != null) { String folderName = folder.getName(); if (!account.getInboxFolderName().equals(folderName) && (account.getTrashFolderName().equals(folderName) || account.getDraftsFolderName().equals(folderName) || account.getSpamFolderName().equals(folderName) || account.getSentFolderName().equals(folderName))) { return false; } } if (message.getUid() != null && localFolder.getLastUid() != null) { try { Integer messageUid = Integer.parseInt(message.getUid()); if (messageUid <= localFolder.getLastUid()) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Message uid is " + messageUid + ", max message uid is " + localFolder.getLastUid() + ". Skipping notification."); return false; } } catch (NumberFormatException e) { // Nothing to be done here. } } // Don't notify if the sender address matches one of our identities and the user chose not // to be notified for such messages. if (account.isAnIdentity(message.getFrom()) && !account.isNotifySelfNewMail()) { return false; } return true; } /** * Get the pending notification data for an account. * See {@link NotificationData}. * * @param account The account to retrieve the pending data for * @param previousUnreadMessageCount The number of currently pending messages, which will be used * if there's no pending data yet. If passed as null, a new instance * won't be created if currently not existent. * @return A pending data instance, or null if one doesn't exist and * previousUnreadMessageCount was passed as null. */ private NotificationData getNotificationData(Account account, Integer previousUnreadMessageCount) { NotificationData data; synchronized (notificationData) { data = notificationData.get(account.getAccountNumber()); if (data == null && previousUnreadMessageCount != null) { data = new NotificationData(previousUnreadMessageCount); notificationData.put(account.getAccountNumber(), data); } } return data; } private CharSequence getMessageSender(Context context, Account account, Message message) { try { boolean isSelf = false; final Contacts contacts = K9.showContactName() ? Contacts.getInstance(context) : null; final Address[] fromAddrs = message.getFrom(); if (fromAddrs != null) { isSelf = account.isAnIdentity(fromAddrs); if (!isSelf && fromAddrs.length > 0) { return fromAddrs[0].toFriendly(contacts).toString(); } } if (isSelf) { // show To: if the message was sent from me Address[] rcpts = message.getRecipients(Message.RecipientType.TO); if (rcpts != null && rcpts.length > 0) { return context.getString(R.string.message_to_fmt, rcpts[0].toFriendly(contacts).toString()); } return context.getString(R.string.general_no_sender); } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to get sender information for notification.", e); } return null; } private CharSequence getMessageSubject(Context context, Message message) { String subject = message.getSubject(); if (!TextUtils.isEmpty(subject)) { return subject; } return context.getString(R.string.general_no_subject); } private static TextAppearanceSpan sEmphasizedSpan; private TextAppearanceSpan getEmphasizedSpan(Context context) { if (sEmphasizedSpan == null) { sEmphasizedSpan = new TextAppearanceSpan(context, R.style.TextAppearance_StatusBar_EventContent_Emphasized); } return sEmphasizedSpan; } private CharSequence getMessagePreview(Context context, Message message) { CharSequence subject = getMessageSubject(context, message); String snippet = message.getPreview(); if (TextUtils.isEmpty(subject)) { return snippet; } else if (TextUtils.isEmpty(snippet)) { return subject; } SpannableStringBuilder preview = new SpannableStringBuilder(); preview.append(subject); preview.append('\n'); preview.append(snippet); preview.setSpan(getEmphasizedSpan(context), 0, subject.length(), 0); return preview; } private CharSequence buildMessageSummary(Context context, CharSequence sender, CharSequence subject) { if (sender == null) { return subject; } SpannableStringBuilder summary = new SpannableStringBuilder(); summary.append(sender); summary.append(" "); summary.append(subject); summary.setSpan(getEmphasizedSpan(context), 0, sender.length(), 0); return summary; } private static final boolean platformShowsNumberInNotification() { // Honeycomb and newer don't show the number as overlay on the notification icon. // However, the number will appear in the detailed notification view. return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; } public static final boolean platformSupportsExtendedNotifications() { // supported in Jellybean // TODO: use constant once target SDK is set to >= 16 return Build.VERSION.SDK_INT >= 16; } private Message findNewestMessageForNotificationLocked(Context context, Account account, NotificationData data) { if (!data.messages.isEmpty()) { return data.messages.getFirst(); } if (!data.droppedMessages.isEmpty()) { return data.droppedMessages.getFirst().restoreToLocalMessage(context); } return null; } /** * Creates a notification of a newly received message. */ private void notifyAccount(Context context, Account account, Message message, int previousUnreadMessageCount) { final NotificationData data = getNotificationData(account, previousUnreadMessageCount); synchronized (data) { notifyAccountWithDataLocked(context, account, message, data); } } private void notifyAccountWithDataLocked(Context context, Account account, Message message, NotificationData data) { boolean updateSilently = false; if (message == null) { /* this can happen if a message we previously notified for is read or deleted remotely */ message = findNewestMessageForNotificationLocked(context, account, data); updateSilently = true; if (message == null) { // seemingly both the message list as well as the overflow list is empty; // it probably is a good idea to cancel the notification in that case notifyAccountCancel(context, account); return; } } else { data.addMessage(message); } final KeyguardManager keyguardService = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); final CharSequence sender = getMessageSender(context, account, message); final CharSequence subject = getMessageSubject(context, message); CharSequence summary = buildMessageSummary(context, sender, subject); // If privacy mode active and keyguard active // OR // GlobalPreference is ALWAYS hide subject // OR // If we could not set a per-message notification, revert to a default message if ((K9.getNotificationHideSubject() == NotificationHideSubject.WHEN_LOCKED && keyguardService.inKeyguardRestrictedInputMode()) || (K9.getNotificationHideSubject() == NotificationHideSubject.ALWAYS) || summary.length() == 0) { summary = context.getString(R.string.notification_new_title); } NotificationManager notifMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationBuilder(context); builder.setSmallIcon(R.drawable.ic_notify_new_mail); builder.setWhen(System.currentTimeMillis()); if (!updateSilently) { builder.setTicker(summary); } final int newMessages = data.getNewMessageCount(); final int unreadCount = data.unreadBeforeNotification + newMessages; if (account.isNotificationShowsUnreadCount() || platformShowsNumberInNotification()) { builder.setNumber(unreadCount); } String accountDescr = (account.getDescription() != null) ? account.getDescription() : account.getEmail(); final ArrayList<MessageReference> allRefs = data.getAllMessageRefs(); if (platformSupportsExtendedNotifications()) { if (newMessages > 1) { // multiple messages pending, show inbox style NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(builder); for (Message m : data.messages) { style.addLine(buildMessageSummary(context, getMessageSender(context, account, m), getMessageSubject(context, m))); } if (!data.droppedMessages.isEmpty()) { style.setSummaryText(context.getString(R.string.notification_additional_messages, data.droppedMessages.size(), accountDescr)); } String title = context.getString(R.string.notification_new_messages_title, newMessages); style.setBigContentTitle(title); builder.setContentTitle(title); builder.setSubText(accountDescr); builder.setStyle(style); } else { // single message pending, show big text NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle(builder); CharSequence preview = getMessagePreview(context, message); if (preview != null) { style.bigText(preview); } builder.setContentText(subject); builder.setSubText(accountDescr); builder.setContentTitle(sender); builder.setStyle(style); builder.addAction(R.drawable.ic_action_single_message_options_dark, context.getString(R.string.notification_action_reply), NotificationActionService.getReplyIntent(context, account, message.makeMessageReference())); } builder.addAction(R.drawable.ic_action_mark_as_read_dark, context.getString(R.string.notification_action_read), NotificationActionService.getReadAllMessagesIntent(context, account, allRefs)); NotificationQuickDelete deleteOption = K9.getNotificationQuickDeleteBehaviour(); boolean showDeleteAction = deleteOption == NotificationQuickDelete.ALWAYS || (deleteOption == NotificationQuickDelete.FOR_SINGLE_MSG && newMessages == 1); if (showDeleteAction) { // we need to pass the action directly to the activity, otherwise the // status bar won't be pulled up and we won't see the confirmation (if used) builder.addAction(R.drawable.ic_action_delete_dark, context.getString(R.string.notification_action_delete), NotificationDeleteConfirmation.getIntent(context, account, allRefs)); } } else { String accountNotice = context.getString(R.string.notification_new_one_account_fmt, unreadCount, accountDescr); builder.setContentTitle(accountNotice); builder.setContentText(summary); } for (Message m : data.messages) { if (m.isSet(Flag.FLAGGED)) { builder.setPriority(NotificationCompat.PRIORITY_HIGH); break; } } Intent targetIntent; boolean treatAsSingleMessageNotification; if (platformSupportsExtendedNotifications()) { // in the new-style notifications, we focus on the new messages, not the unread ones treatAsSingleMessageNotification = newMessages == 1; } else { // in the old-style notifications, we focus on unread messages, as we don't have a // good way to express the new message count treatAsSingleMessageNotification = unreadCount == 1; } if (treatAsSingleMessageNotification) { targetIntent = MessageList.actionHandleNotificationIntent( context, message.makeMessageReference()); } else { String initialFolder = message.getFolder().getName(); /* only go to folder if all messages are in the same folder, else go to folder list */ for (MessageReference ref : allRefs) { if (!TextUtils.equals(initialFolder, ref.folderName)) { initialFolder = null; break; } } targetIntent = FolderList.actionHandleNotification(context, account, initialFolder); } builder.setContentIntent(PendingIntent.getActivity(context, account.getAccountNumber(), targetIntent, PendingIntent.FLAG_UPDATE_CURRENT)); builder.setDeleteIntent(NotificationActionService.getAcknowledgeIntent(context, account)); // Only ring or vibrate if we have not done so already on this account and fetch boolean ringAndVibrate = false; if (!updateSilently && !account.isRingNotified()) { account.setRingNotified(true); ringAndVibrate = true; } NotificationSetting n = account.getNotificationSetting(); configureNotification( builder, (n.shouldRing()) ? n.getRingtone() : null, (n.shouldVibrate()) ? n.getVibration() : null, (n.isLed()) ? Integer.valueOf(n.getLedColor()) : null, K9.NOTIFICATION_LED_BLINK_SLOW, ringAndVibrate); notifMgr.notify(account.getAccountNumber(), builder.build()); } /** * Configure the notification sound and LED * * @param builder * {@link NotificationCompat.Builder} instance used to configure the notification. * Never {@code null}. * @param ringtone * String name of ringtone. {@code null}, if no ringtone should be played. * @param vibrationPattern * {@code long[]} vibration pattern. {@code null}, if no vibration should be played. * @param ledColor * Color to flash LED. {@code null}, if no LED flash should happen. * @param ledSpeed * Either {@link K9#NOTIFICATION_LED_BLINK_SLOW} or * {@link K9#NOTIFICATION_LED_BLINK_FAST}. * @param ringAndVibrate * {@code true}, if ringtone/vibration are allowed. {@code false}, otherwise. */ private void configureNotification(NotificationCompat.Builder builder, String ringtone, long[] vibrationPattern, Integer ledColor, int ledSpeed, boolean ringAndVibrate) { // if it's quiet time, then we shouldn't be ringing, buzzing or flashing if (K9.isQuietTime()) { return; } if (ringAndVibrate) { if (ringtone != null && !TextUtils.isEmpty(ringtone)) { builder.setSound(Uri.parse(ringtone)); } if (vibrationPattern != null) { builder.setVibrate(vibrationPattern); } } if (ledColor != null) { int ledOnMS; int ledOffMS; if (ledSpeed == K9.NOTIFICATION_LED_BLINK_SLOW) { ledOnMS = K9.NOTIFICATION_LED_ON_TIME; ledOffMS = K9.NOTIFICATION_LED_OFF_TIME; } else { ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME; ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME; } builder.setLights(ledColor, ledOnMS, ledOffMS); } } /** Cancel a notification of new email messages */ public void notifyAccountCancel(Context context, Account account) { NotificationManager notifMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); notifMgr.cancel(account.getAccountNumber()); notifMgr.cancel(-1000 - account.getAccountNumber()); notificationData.remove(account.getAccountNumber()); } /** * Save a draft message. * @param account Account we are saving for. * @param message Message to save. * @return Message representing the entry in the local store. */ public Message saveDraft(final Account account, final Message message, long existingDraftId) { Message localMessage = null; try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(account.getDraftsFolderName()); localFolder.open(OpenMode.READ_WRITE); if (existingDraftId != INVALID_MESSAGE_ID) { String uid = localFolder.getMessageUidById(existingDraftId); message.setUid(uid); } // Save the message to the store. localFolder.appendMessages(new Message[] { message }); // Fetch the message back from the store. This is the Message that's returned to the caller. localMessage = localFolder.getMessage(message.getUid()); localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; command.arguments = new String[] { localFolder.getName(), localMessage.getUid() }; queuePendingCommand(account, command); processPendingCommands(account); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to save message as draft.", e); addErrorMessage(account, null, e); } return localMessage; } public long getId(Message message) { long id; if (message instanceof LocalMessage) { id = ((LocalMessage) message).getId(); } else { Log.w(K9.LOG_TAG, "MessagingController.getId() called without a LocalMessage"); id = INVALID_MESSAGE_ID; } return id; } public boolean modeMismatch(Account.FolderMode aMode, Folder.FolderClass fMode) { if (aMode == Account.FolderMode.NONE || (aMode == Account.FolderMode.FIRST_CLASS && fMode != Folder.FolderClass.FIRST_CLASS) || (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS && fMode != Folder.FolderClass.FIRST_CLASS && fMode != Folder.FolderClass.SECOND_CLASS) || (aMode == Account.FolderMode.NOT_SECOND_CLASS && fMode == Folder.FolderClass.SECOND_CLASS)) { return true; } else { return false; } } static AtomicInteger sequencing = new AtomicInteger(0); static class Command implements Comparable<Command> { public Runnable runnable; public MessagingListener listener; public String description; boolean isForeground; int sequence = sequencing.getAndIncrement(); @Override public int compareTo(Command other) { if (other.isForeground && !isForeground) { return 1; } else if (!other.isForeground && isForeground) { return -1; } else { return (sequence - other.sequence); } } } public MessagingListener getCheckMailListener() { return checkMailListener; } public void setCheckMailListener(MessagingListener checkMailListener) { if (this.checkMailListener != null) { removeListener(this.checkMailListener); } this.checkMailListener = checkMailListener; if (this.checkMailListener != null) { addListener(this.checkMailListener); } } public Collection<Pusher> getPushers() { return pushers.values(); } public boolean setupPushing(final Account account) { try { Pusher previousPusher = pushers.remove(account); if (previousPusher != null) { previousPusher.stop(); } Preferences prefs = Preferences.getPreferences(mApplication); Account.FolderMode aDisplayMode = account.getFolderDisplayMode(); Account.FolderMode aPushMode = account.getFolderPushMode(); List<String> names = new ArrayList<String>(); Store localStore = account.getLocalStore(); for (final Folder folder : localStore.getPersonalNamespaces(false)) { if (folder.getName().equals(account.getErrorFolderName()) || folder.getName().equals(account.getOutboxFolderName())) { /* if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() + " which should never be pushed"); */ continue; } folder.open(Folder.OpenMode.READ_WRITE); folder.refresh(prefs); Folder.FolderClass fDisplayClass = folder.getDisplayClass(); Folder.FolderClass fPushClass = folder.getPushClass(); if (modeMismatch(aDisplayMode, fDisplayClass)) { // Never push a folder that isn't displayed /* if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() + " which is in display class " + fDisplayClass + " while account is in display mode " + aDisplayMode); */ continue; } if (modeMismatch(aPushMode, fPushClass)) { // Do not push folders in the wrong class /* if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() + " which is in push mode " + fPushClass + " while account is in push mode " + aPushMode); */ continue; } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Starting pusher for " + account.getDescription() + ":" + folder.getName()); names.add(folder.getName()); } if (!names.isEmpty()) { PushReceiver receiver = new MessagingControllerPushReceiver(mApplication, account, this); int maxPushFolders = account.getMaxPushFolders(); if (names.size() > maxPushFolders) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Count of folders to push for account " + account.getDescription() + " is " + names.size() + ", greater than limit of " + maxPushFolders + ", truncating"); names = names.subList(0, maxPushFolders); } try { Store store = account.getRemoteStore(); if (!store.isPushCapable()) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Account " + account.getDescription() + " is not push capable, skipping"); return false; } Pusher pusher = store.getPusher(receiver); if (pusher != null) { Pusher oldPusher = pushers.putIfAbsent(account, pusher); if (oldPusher == null) { pusher.start(names); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not get remote store", e); return false; } return true; } else { if (K9.DEBUG) Log.i(K9.LOG_TAG, "No folders are configured for pushing in account " + account.getDescription()); return false; } } catch (Exception e) { Log.e(K9.LOG_TAG, "Got exception while setting up pushing", e); } return false; } public void stopAllPushing() { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Stopping all pushers"); Iterator<Pusher> iter = pushers.values().iterator(); while (iter.hasNext()) { Pusher pusher = iter.next(); iter.remove(); pusher.stop(); } } public void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages, final boolean flagSyncOnly) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Got new pushed email messages for account " + account.getDescription() + ", folder " + remoteFolder.getName()); final CountDownLatch latch = new CountDownLatch(1); putBackground("Push messageArrived of account " + account.getDescription() + ", folder " + remoteFolder.getName(), null, new Runnable() { @Override public void run() { LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(remoteFolder.getName()); localFolder.open(OpenMode.READ_WRITE); account.setRingNotified(false); int newCount = downloadMessages(account, remoteFolder, localFolder, messages, flagSyncOnly); int unreadMessageCount = localFolder.getUnreadMessageCount(); localFolder.setLastPush(System.currentTimeMillis()); localFolder.setStatus(null); if (K9.DEBUG) Log.i(K9.LOG_TAG, "messagesArrived newCount = " + newCount + ", unread count = " + unreadMessageCount); if (unreadMessageCount == 0) { notifyAccountCancel(mApplication, account); } for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, remoteFolder.getName(), unreadMessageCount); } } catch (Exception e) { String rootMessage = getRootCauseMessage(e); String errorMessage = "Push failed: " + rootMessage; try { // Oddly enough, using a local variable gets rid of a // potential null pointer access warning with Eclipse. LocalFolder folder = localFolder; folder.setStatus(errorMessage); } catch (Exception se) { Log.e(K9.LOG_TAG, "Unable to set failed status on localFolder", se); } for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed(account, remoteFolder.getName(), errorMessage); } addErrorMessage(account, null, e); } finally { closeFolder(localFolder); latch.countDown(); } } }); try { latch.await(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Interrupted while awaiting latch release", e); } if (K9.DEBUG) Log.i(K9.LOG_TAG, "MessagingController.messagesArrivedLatch released"); } public void systemStatusChanged() { for (MessagingListener l : getListeners()) { l.systemStatusChanged(); } } enum MemorizingState { STARTED, FINISHED, FAILED } static class Memory { Account account; String folderName; MemorizingState syncingState = null; MemorizingState sendingState = null; MemorizingState pushingState = null; MemorizingState processingState = null; String failureMessage = null; int syncingTotalMessagesInMailbox; int syncingNumNewMessages; int folderCompleted = 0; int folderTotal = 0; String processingCommandTitle = null; Memory(Account nAccount, String nFolderName) { account = nAccount; folderName = nFolderName; } String getKey() { return getMemoryKey(account, folderName); } } static String getMemoryKey(Account taccount, String tfolderName) { return taccount.getDescription() + ":" + tfolderName; } static class MemorizingListener extends MessagingListener { HashMap<String, Memory> memories = new HashMap<String, Memory>(31); Memory getMemory(Account account, String folderName) { Memory memory = memories.get(getMemoryKey(account, folderName)); if (memory == null) { memory = new Memory(account, folderName); memories.put(memory.getKey(), memory); } return memory; } @Override public synchronized void synchronizeMailboxStarted(Account account, String folder) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.STARTED; memory.folderCompleted = 0; memory.folderTotal = 0; } @Override public synchronized void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.FINISHED; memory.syncingTotalMessagesInMailbox = totalMessagesInMailbox; memory.syncingNumNewMessages = numNewMessages; } @Override public synchronized void synchronizeMailboxFailed(Account account, String folder, String message) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.FAILED; memory.failureMessage = message; } synchronized void refreshOther(MessagingListener other) { if (other != null) { Memory syncStarted = null; Memory sendStarted = null; Memory processingStarted = null; for (Memory memory : memories.values()) { if (memory.syncingState != null) { switch (memory.syncingState) { case STARTED: syncStarted = memory; break; case FINISHED: other.synchronizeMailboxFinished(memory.account, memory.folderName, memory.syncingTotalMessagesInMailbox, memory.syncingNumNewMessages); break; case FAILED: other.synchronizeMailboxFailed(memory.account, memory.folderName, memory.failureMessage); break; } } if (memory.sendingState != null) { switch (memory.sendingState) { case STARTED: sendStarted = memory; break; case FINISHED: other.sendPendingMessagesCompleted(memory.account); break; case FAILED: other.sendPendingMessagesFailed(memory.account); break; } } if (memory.pushingState != null) { switch (memory.pushingState) { case STARTED: other.setPushActive(memory.account, memory.folderName, true); break; case FINISHED: other.setPushActive(memory.account, memory.folderName, false); break; case FAILED: break; } } if (memory.processingState != null) { switch (memory.processingState) { case STARTED: processingStarted = memory; break; case FINISHED: case FAILED: other.pendingCommandsFinished(memory.account); break; } } } Memory somethingStarted = null; if (syncStarted != null) { other.synchronizeMailboxStarted(syncStarted.account, syncStarted.folderName); somethingStarted = syncStarted; } if (sendStarted != null) { other.sendPendingMessagesStarted(sendStarted.account); somethingStarted = sendStarted; } if (processingStarted != null) { other.pendingCommandsProcessing(processingStarted.account); if (processingStarted.processingCommandTitle != null) { other.pendingCommandStarted(processingStarted.account, processingStarted.processingCommandTitle); } else { other.pendingCommandCompleted(processingStarted.account, processingStarted.processingCommandTitle); } somethingStarted = processingStarted; } if (somethingStarted != null && somethingStarted.folderTotal > 0) { other.synchronizeMailboxProgress(somethingStarted.account, somethingStarted.folderName, somethingStarted.folderCompleted, somethingStarted.folderTotal); } } } @Override public synchronized void setPushActive(Account account, String folderName, boolean active) { Memory memory = getMemory(account, folderName); memory.pushingState = (active ? MemorizingState.STARTED : MemorizingState.FINISHED); } @Override public synchronized void sendPendingMessagesStarted(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.STARTED; memory.folderCompleted = 0; memory.folderTotal = 0; } @Override public synchronized void sendPendingMessagesCompleted(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.FINISHED; } @Override public synchronized void sendPendingMessagesFailed(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.FAILED; } @Override public synchronized void synchronizeMailboxProgress(Account account, String folderName, int completed, int total) { Memory memory = getMemory(account, folderName); memory.folderCompleted = completed; memory.folderTotal = total; } @Override public synchronized void pendingCommandsProcessing(Account account) { Memory memory = getMemory(account, null); memory.processingState = MemorizingState.STARTED; memory.folderCompleted = 0; memory.folderTotal = 0; } @Override public synchronized void pendingCommandsFinished(Account account) { Memory memory = getMemory(account, null); memory.processingState = MemorizingState.FINISHED; } @Override public synchronized void pendingCommandStarted(Account account, String commandTitle) { Memory memory = getMemory(account, null); memory.processingCommandTitle = commandTitle; } @Override public synchronized void pendingCommandCompleted(Account account, String commandTitle) { Memory memory = getMemory(account, null); memory.processingCommandTitle = null; } } private void actOnMessages(List<Message> messages, MessageActor actor) { Map<Account, Map<Folder, List<Message>>> accountMap = new HashMap<Account, Map<Folder, List<Message>>>(); for (Message message : messages) { Folder folder = message.getFolder(); Account account = folder.getAccount(); Map<Folder, List<Message>> folderMap = accountMap.get(account); if (folderMap == null) { folderMap = new HashMap<Folder, List<Message>>(); accountMap.put(account, folderMap); } List<Message> messageList = folderMap.get(folder); if (messageList == null) { messageList = new LinkedList<Message>(); folderMap.put(folder, messageList); } messageList.add(message); } for (Map.Entry<Account, Map<Folder, List<Message>>> entry : accountMap.entrySet()) { Account account = entry.getKey(); //account.refresh(Preferences.getPreferences(K9.app)); Map<Folder, List<Message>> folderMap = entry.getValue(); for (Map.Entry<Folder, List<Message>> folderEntry : folderMap.entrySet()) { Folder folder = folderEntry.getKey(); List<Message> messageList = folderEntry.getValue(); actor.act(account, folder, messageList); } } } interface MessageActor { public void act(final Account account, final Folder folder, final List<Message> messages); } }
src/com/fsck/k9/controller/MessagingController.java
package com.fsck.k9.controller; import java.io.CharArrayWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import android.app.Application; import android.app.KeyguardManager; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.PowerManager; import android.os.Process; import android.support.v4.app.NotificationCompat; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.style.TextAppearanceSpan; import android.util.Log; import com.fsck.k9.Account; import com.fsck.k9.AccountStats; import com.fsck.k9.K9; import com.fsck.k9.K9.NotificationHideSubject; import com.fsck.k9.K9.Intents; import com.fsck.k9.K9.NotificationQuickDelete; import com.fsck.k9.NotificationSetting; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.activity.FolderList; import com.fsck.k9.activity.MessageList; import com.fsck.k9.activity.MessageReference; import com.fsck.k9.activity.NotificationDeleteConfirmation; import com.fsck.k9.activity.setup.AccountSetupIncoming; import com.fsck.k9.activity.setup.AccountSetupOutgoing; import com.fsck.k9.cache.EmailProviderCache; import com.fsck.k9.helper.Contacts; import com.fsck.k9.helper.NotificationBuilder; import com.fsck.k9.helper.power.TracingPowerManager; import com.fsck.k9.helper.power.TracingPowerManager.TracingWakeLock; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.FetchProfile; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.Folder.FolderType; import com.fsck.k9.mail.Folder.OpenMode; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.Message.RecipientType; import com.fsck.k9.mail.CertificateValidationException; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.Part; import com.fsck.k9.mail.PushReceiver; import com.fsck.k9.mail.Pusher; import com.fsck.k9.mail.Store; import com.fsck.k9.mail.Transport; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.internet.MimeUtility; import com.fsck.k9.mail.internet.TextBody; import com.fsck.k9.mail.store.LocalStore; import com.fsck.k9.mail.store.LocalStore.LocalFolder; import com.fsck.k9.mail.store.LocalStore.LocalMessage; import com.fsck.k9.mail.store.LocalStore.PendingCommand; import com.fsck.k9.mail.store.UnavailableAccountException; import com.fsck.k9.mail.store.UnavailableStorageException; import com.fsck.k9.provider.EmailProvider; import com.fsck.k9.provider.EmailProvider.StatsColumns; import com.fsck.k9.search.ConditionsTreeNode; import com.fsck.k9.search.LocalSearch; import com.fsck.k9.search.SearchAccount; import com.fsck.k9.search.SearchSpecification; import com.fsck.k9.search.SqlQueryBuilder; import com.fsck.k9.service.NotificationActionService; /** * Starts a long running (application) Thread that will run through commands * that require remote mailbox access. This class is used to serialize and * prioritize these commands. Each method that will submit a command requires a * MessagingListener instance to be provided. It is expected that that listener * has also been added as a registered listener using addListener(). When a * command is to be executed, if the listener that was provided with the command * is no longer registered the command is skipped. The design idea for the above * is that when an Activity starts it registers as a listener. When it is paused * it removes itself. Thus, any commands that that activity submitted are * removed from the queue once the activity is no longer active. */ public class MessagingController implements Runnable { public static final long INVALID_MESSAGE_ID = -1; /** * Immutable empty {@link String} array */ private static final String[] EMPTY_STRING_ARRAY = new String[0]; /** * Immutable empty {@link Message} array */ private static final Message[] EMPTY_MESSAGE_ARRAY = new Message[0]; /** * Immutable empty {@link Folder} array */ private static final Folder[] EMPTY_FOLDER_ARRAY = new Folder[0]; /** * The maximum message size that we'll consider to be "small". A small message is downloaded * in full immediately instead of in pieces. Anything over this size will be downloaded in * pieces with attachments being left off completely and downloaded on demand. * * * 25k for a "small" message was picked by educated trial and error. * http://answers.google.com/answers/threadview?id=312463 claims that the * average size of an email is 59k, which I feel is too large for our * blind download. The following tests were performed on a download of * 25 random messages. * <pre> * 5k - 61 seconds, * 25k - 51 seconds, * 55k - 53 seconds, * </pre> * So 25k gives good performance and a reasonable data footprint. Sounds good to me. */ private static final String PENDING_COMMAND_MOVE_OR_COPY = "com.fsck.k9.MessagingController.moveOrCopy"; private static final String PENDING_COMMAND_MOVE_OR_COPY_BULK = "com.fsck.k9.MessagingController.moveOrCopyBulk"; private static final String PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW = "com.fsck.k9.MessagingController.moveOrCopyBulkNew"; private static final String PENDING_COMMAND_EMPTY_TRASH = "com.fsck.k9.MessagingController.emptyTrash"; private static final String PENDING_COMMAND_SET_FLAG_BULK = "com.fsck.k9.MessagingController.setFlagBulk"; private static final String PENDING_COMMAND_SET_FLAG = "com.fsck.k9.MessagingController.setFlag"; private static final String PENDING_COMMAND_APPEND = "com.fsck.k9.MessagingController.append"; private static final String PENDING_COMMAND_MARK_ALL_AS_READ = "com.fsck.k9.MessagingController.markAllAsRead"; private static final String PENDING_COMMAND_EXPUNGE = "com.fsck.k9.MessagingController.expunge"; public static class UidReverseComparator implements Comparator<Message> { @Override public int compare(Message o1, Message o2) { if (o1 == null || o2 == null || o1.getUid() == null || o2.getUid() == null) { return 0; } int id1, id2; try { id1 = Integer.parseInt(o1.getUid()); id2 = Integer.parseInt(o2.getUid()); } catch (NumberFormatException e) { return 0; } //reversed intentionally. if (id1 < id2) return 1; if (id1 > id2) return -1; return 0; } } /** * Maximum number of unsynced messages to store at once */ private static final int UNSYNC_CHUNK_SIZE = 5; private static MessagingController inst = null; private BlockingQueue<Command> mCommands = new PriorityBlockingQueue<Command>(); private Thread mThread; private Set<MessagingListener> mListeners = new CopyOnWriteArraySet<MessagingListener>(); private final ConcurrentHashMap<String, AtomicInteger> sendCount = new ConcurrentHashMap<String, AtomicInteger>(); ConcurrentHashMap<Account, Pusher> pushers = new ConcurrentHashMap<Account, Pusher>(); private final ExecutorService threadPool = Executors.newCachedThreadPool(); private MessagingListener checkMailListener = null; private MemorizingListener memorizingListener = new MemorizingListener(); private boolean mBusy; /** * {@link K9} */ private Application mApplication; /** * A holder class for pending notification data * * This class holds all pieces of information for constructing * a notification with message preview. */ private static class NotificationData { /** Number of unread messages before constructing the notification */ int unreadBeforeNotification; /** * List of messages that should be used for the inbox-style overview. * It's sorted from newest to oldest message. * Don't modify this list directly, but use {@link addMessage} and * {@link removeMatchingMessage} instead. */ LinkedList<Message> messages; /** * List of references for messages that the user is still to be notified of, * but which don't fit into the inbox style anymore. It's sorted from newest * to oldest message. */ LinkedList<MessageReference> droppedMessages; /** * Maximum number of messages to keep for the inbox-style overview. * As of Jellybean, phone notifications show a maximum of 5 lines, while tablet * notifications show 7 lines. To make sure no lines are silently dropped, * we default to 5 lines. */ private final static int MAX_MESSAGES = 5; /** * Constructs a new data instance. * * @param unread Number of unread messages prior to instance construction */ public NotificationData(int unread) { unreadBeforeNotification = unread; droppedMessages = new LinkedList<MessageReference>(); messages = new LinkedList<Message>(); } /** * Adds a new message to the list of pending messages for this notification. * * The implementation will take care of keeping a meaningful amount of * messages in {@link #messages}. * * @param m The new message to add. */ public void addMessage(Message m) { while (messages.size() >= MAX_MESSAGES) { Message dropped = messages.removeLast(); droppedMessages.addFirst(dropped.makeMessageReference()); } messages.addFirst(m); } /** * Remove a certain message from the message list. * * @param context A context. * @param ref Reference of the message to remove * @return true if message was found and removed, false otherwise */ public boolean removeMatchingMessage(Context context, MessageReference ref) { for (MessageReference dropped : droppedMessages) { if (dropped.equals(ref)) { droppedMessages.remove(dropped); return true; } } for (Message message : messages) { if (message.makeMessageReference().equals(ref)) { if (messages.remove(message) && !droppedMessages.isEmpty()) { Message restoredMessage = droppedMessages.getFirst().restoreToLocalMessage(context); if (restoredMessage != null) { messages.addLast(restoredMessage); droppedMessages.removeFirst(); } } return true; } } return false; } /** * Gets a list of references for all pending messages for the notification. * * @return Message reference list */ public ArrayList<MessageReference> getAllMessageRefs() { ArrayList<MessageReference> refs = new ArrayList<MessageReference>(); for (Message m : messages) { refs.add(m.makeMessageReference()); } refs.addAll(droppedMessages); return refs; } /** * Gets the total number of messages the user is to be notified of. * * @return Amount of new messages the notification notifies for */ public int getNewMessageCount() { return messages.size() + droppedMessages.size(); } }; // Key is accountNumber private ConcurrentHashMap<Integer, NotificationData> notificationData = new ConcurrentHashMap<Integer, NotificationData>(); private static final Flag[] SYNC_FLAGS = new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED, Flag.FORWARDED }; private void suppressMessages(Account account, List<Message> messages) { EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), mApplication.getApplicationContext()); cache.hideMessages(messages); } private void unsuppressMessages(Account account, Message[] messages) { EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), mApplication.getApplicationContext()); cache.unhideMessages(messages); } private boolean isMessageSuppressed(Account account, Message message) { LocalMessage localMessage = (LocalMessage) message; String accountUuid = account.getUuid(); long messageId = localMessage.getId(); long folderId = ((LocalFolder) localMessage.getFolder()).getId(); EmailProviderCache cache = EmailProviderCache.getCache(accountUuid, mApplication.getApplicationContext()); return cache.isMessageHidden(messageId, folderId); } private void setFlagInCache(final Account account, final List<Long> messageIds, final Flag flag, final boolean newState) { EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), mApplication.getApplicationContext()); String columnName = LocalStore.getColumnNameForFlag(flag); String value = Integer.toString((newState) ? 1 : 0); cache.setValueForMessages(messageIds, columnName, value); } private void removeFlagFromCache(final Account account, final List<Long> messageIds, final Flag flag) { EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), mApplication.getApplicationContext()); String columnName = LocalStore.getColumnNameForFlag(flag); cache.removeValueForMessages(messageIds, columnName); } private void setFlagForThreadsInCache(final Account account, final List<Long> threadRootIds, final Flag flag, final boolean newState) { EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), mApplication.getApplicationContext()); String columnName = LocalStore.getColumnNameForFlag(flag); String value = Integer.toString((newState) ? 1 : 0); cache.setValueForThreads(threadRootIds, columnName, value); } private void removeFlagForThreadsFromCache(final Account account, final List<Long> messageIds, final Flag flag) { EmailProviderCache cache = EmailProviderCache.getCache(account.getUuid(), mApplication.getApplicationContext()); String columnName = LocalStore.getColumnNameForFlag(flag); cache.removeValueForThreads(messageIds, columnName); } /** * @param application {@link K9} */ private MessagingController(Application application) { mApplication = application; mThread = new Thread(this); mThread.setName("MessagingController"); mThread.start(); if (memorizingListener != null) { addListener(memorizingListener); } } /** * Gets or creates the singleton instance of MessagingController. Application is used to * provide a Context to classes that need it. * @param application {@link K9} * @return */ public synchronized static MessagingController getInstance(Application application) { if (inst == null) { inst = new MessagingController(application); } return inst; } public boolean isBusy() { return mBusy; } @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (true) { String commandDescription = null; try { final Command command = mCommands.take(); if (command != null) { commandDescription = command.description; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Running " + (command.isForeground ? "Foreground" : "Background") + " command '" + command.description + "', seq = " + command.sequence); mBusy = true; try { command.runnable.run(); } catch (UnavailableAccountException e) { // retry later new Thread() { @Override public void run() { try { sleep(30 * 1000); mCommands.put(command); } catch (InterruptedException e) { Log.e(K9.LOG_TAG, "interrupted while putting a pending command for" + " an unavailable account back into the queue." + " THIS SHOULD NEVER HAPPEN."); } } } .start(); } if (K9.DEBUG) Log.i(K9.LOG_TAG, (command.isForeground ? "Foreground" : "Background") + " Command '" + command.description + "' completed"); for (MessagingListener l : getListeners(command.listener)) { l.controllerCommandCompleted(!mCommands.isEmpty()); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e); } mBusy = false; } } private void put(String description, MessagingListener listener, Runnable runnable) { putCommand(mCommands, description, listener, runnable, true); } private void putBackground(String description, MessagingListener listener, Runnable runnable) { putCommand(mCommands, description, listener, runnable, false); } private void putCommand(BlockingQueue<Command> queue, String description, MessagingListener listener, Runnable runnable, boolean isForeground) { int retries = 10; Exception e = null; while (retries-- > 0) { try { Command command = new Command(); command.listener = listener; command.runnable = runnable; command.description = description; command.isForeground = isForeground; queue.put(command); return; } catch (InterruptedException ie) { try { Thread.sleep(200); } catch (InterruptedException ne) { } e = ie; } } throw new Error(e); } public void addListener(MessagingListener listener) { mListeners.add(listener); refreshListener(listener); } public void refreshListener(MessagingListener listener) { if (memorizingListener != null && listener != null) { memorizingListener.refreshOther(listener); } } public void removeListener(MessagingListener listener) { mListeners.remove(listener); } public Set<MessagingListener> getListeners() { return mListeners; } public Set<MessagingListener> getListeners(MessagingListener listener) { if (listener == null) { return mListeners; } Set<MessagingListener> listeners = new HashSet<MessagingListener>(mListeners); listeners.add(listener); return listeners; } /** * Lists folders that are available locally and remotely. This method calls * listFoldersCallback for local folders before it returns, and then for * remote folders at some later point. If there are no local folders * includeRemote is forced by this method. This method should be called from * a Thread as it may take several seconds to list the local folders. * TODO this needs to cache the remote folder list * * @param account * @param listener * @throws MessagingException */ public void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener) { threadPool.execute(new Runnable() { @Override public void run() { listFoldersSynchronous(account, refreshRemote, listener); } }); } /** * Lists folders that are available locally and remotely. This method calls * listFoldersCallback for local folders before it returns, and then for * remote folders at some later point. If there are no local folders * includeRemote is forced by this method. This method is called in the * foreground. * TODO this needs to cache the remote folder list * * @param account * @param listener * @throws MessagingException */ public void listFoldersSynchronous(final Account account, final boolean refreshRemote, final MessagingListener listener) { for (MessagingListener l : getListeners(listener)) { l.listFoldersStarted(account); } List <? extends Folder > localFolders = null; if (!account.isAvailable(mApplication)) { Log.i(K9.LOG_TAG, "not listing folders of unavailable account"); } else { try { Store localStore = account.getLocalStore(); localFolders = localStore.getPersonalNamespaces(false); Folder[] folderArray = localFolders.toArray(EMPTY_FOLDER_ARRAY); if (refreshRemote || localFolders.isEmpty()) { doRefreshRemote(account, listener); return; } for (MessagingListener l : getListeners(listener)) { l.listFolders(account, folderArray); } } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { l.listFoldersFailed(account, e.getMessage()); } addErrorMessage(account, null, e); return; } finally { if (localFolders != null) { for (Folder localFolder : localFolders) { closeFolder(localFolder); } } } } for (MessagingListener l : getListeners(listener)) { l.listFoldersFinished(account); } } private void doRefreshRemote(final Account account, final MessagingListener listener) { put("doRefreshRemote", listener, new Runnable() { @Override public void run() { List <? extends Folder > localFolders = null; try { Store store = account.getRemoteStore(); List <? extends Folder > remoteFolders = store.getPersonalNamespaces(false); LocalStore localStore = account.getLocalStore(); HashSet<String> remoteFolderNames = new HashSet<String>(); List<LocalFolder> foldersToCreate = new LinkedList<LocalFolder>(); localFolders = localStore.getPersonalNamespaces(false); HashSet<String> localFolderNames = new HashSet<String>(); for (Folder localFolder : localFolders) { localFolderNames.add(localFolder.getName()); } for (Folder remoteFolder : remoteFolders) { if (localFolderNames.contains(remoteFolder.getName()) == false) { LocalFolder localFolder = localStore.getFolder(remoteFolder.getName()); foldersToCreate.add(localFolder); } remoteFolderNames.add(remoteFolder.getName()); } localStore.createFolders(foldersToCreate, account.getDisplayCount()); localFolders = localStore.getPersonalNamespaces(false); /* * Clear out any folders that are no longer on the remote store. */ for (Folder localFolder : localFolders) { String localFolderName = localFolder.getName(); if (!account.isSpecialFolder(localFolderName) && !remoteFolderNames.contains(localFolderName)) { localFolder.delete(false); } } localFolders = localStore.getPersonalNamespaces(false); Folder[] folderArray = localFolders.toArray(EMPTY_FOLDER_ARRAY); for (MessagingListener l : getListeners(listener)) { l.listFolders(account, folderArray); } for (MessagingListener l : getListeners(listener)) { l.listFoldersFinished(account); } } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { l.listFoldersFailed(account, ""); } addErrorMessage(account, null, e); } finally { if (localFolders != null) { for (Folder localFolder : localFolders) { closeFolder(localFolder); } } } } }); } /** * Find all messages in any local account which match the query 'query' * @throws MessagingException */ public void searchLocalMessages(final LocalSearch search, final MessagingListener listener) { threadPool.execute(new Runnable() { @Override public void run() { searchLocalMessagesSynchronous(search, listener); } }); } public void searchLocalMessagesSynchronous(final LocalSearch search, final MessagingListener listener) { final AccountStats stats = new AccountStats(); final HashSet<String> uuidSet = new HashSet<String>(Arrays.asList(search.getAccountUuids())); Account[] accounts = Preferences.getPreferences(mApplication.getApplicationContext()).getAccounts(); boolean allAccounts = uuidSet.contains(SearchSpecification.ALL_ACCOUNTS); // for every account we want to search do the query in the localstore for (final Account account : accounts) { if (!allAccounts && !uuidSet.contains(account.getUuid())) { continue; } // Collecting statistics of the search result MessageRetrievalListener retrievalListener = new MessageRetrievalListener() { @Override public void messageStarted(String message, int number, int ofTotal) {} @Override public void messagesFinished(int number) {} @Override public void messageFinished(Message message, int number, int ofTotal) { if (!isMessageSuppressed(message.getFolder().getAccount(), message)) { List<Message> messages = new ArrayList<Message>(); messages.add(message); stats.unreadMessageCount += (!message.isSet(Flag.SEEN)) ? 1 : 0; stats.flaggedMessageCount += (message.isSet(Flag.FLAGGED)) ? 1 : 0; if (listener != null) { listener.listLocalMessagesAddMessages(account, null, messages); } } } }; // alert everyone the search has started if (listener != null) { listener.listLocalMessagesStarted(account, null); } // build and do the query in the localstore try { LocalStore localStore = account.getLocalStore(); localStore.searchForMessages(retrievalListener, search); } catch (Exception e) { if (listener != null) { listener.listLocalMessagesFailed(account, null, e.getMessage()); } addErrorMessage(account, null, e); } finally { if (listener != null) { listener.listLocalMessagesFinished(account, null); } } } // publish the total search statistics if (listener != null) { listener.searchStats(stats); } } public Future<?> searchRemoteMessages(final String acctUuid, final String folderName, final String query, final Flag[] requiredFlags, final Flag[] forbiddenFlags, final MessagingListener listener) { if (K9.DEBUG) { String msg = "searchRemoteMessages (" + "acct=" + acctUuid + ", folderName = " + folderName + ", query = " + query + ")"; Log.i(K9.LOG_TAG, msg); } return threadPool.submit(new Runnable() { @Override public void run() { searchRemoteMessagesSynchronous(acctUuid, folderName, query, requiredFlags, forbiddenFlags, listener); } }); } public void searchRemoteMessagesSynchronous(final String acctUuid, final String folderName, final String query, final Flag[] requiredFlags, final Flag[] forbiddenFlags, final MessagingListener listener) { final Account acct = Preferences.getPreferences(mApplication.getApplicationContext()).getAccount(acctUuid); if (listener != null) { listener.remoteSearchStarted(acct, folderName); } List<Message> extraResults = new ArrayList<Message>(); try { Store remoteStore = acct.getRemoteStore(); LocalStore localStore = acct.getLocalStore(); if (remoteStore == null || localStore == null) { throw new MessagingException("Could not get store"); } Folder remoteFolder = remoteStore.getFolder(folderName); LocalFolder localFolder = localStore.getFolder(folderName); if (remoteFolder == null || localFolder == null) { throw new MessagingException("Folder not found"); } List<Message> messages = remoteFolder.search(query, requiredFlags, forbiddenFlags); if (K9.DEBUG) { Log.i("Remote Search", "Remote search got " + messages.size() + " results"); } // There's no need to fetch messages already completely downloaded List<Message> remoteMessages = localFolder.extractNewMessages(messages); messages.clear(); if (listener != null) { listener.remoteSearchServerQueryComplete(acct, folderName, remoteMessages.size()); } Collections.sort(remoteMessages, new UidReverseComparator()); int resultLimit = acct.getRemoteSearchNumResults(); if (resultLimit > 0 && remoteMessages.size() > resultLimit) { extraResults = remoteMessages.subList(resultLimit, remoteMessages.size()); remoteMessages = remoteMessages.subList(0, resultLimit); } loadSearchResultsSynchronous(remoteMessages, localFolder, remoteFolder, listener); } catch (Exception e) { if (Thread.currentThread().isInterrupted()) { Log.i(K9.LOG_TAG, "Caught exception on aborted remote search; safe to ignore.", e); } else { Log.e(K9.LOG_TAG, "Could not complete remote search", e); if (listener != null) { listener.remoteSearchFailed(acct, null, e.getMessage()); } addErrorMessage(acct, null, e); } } finally { if (listener != null) { listener.remoteSearchFinished(acct, folderName, 0, extraResults); } } } public void loadSearchResults(final Account account, final String folderName, final List<Message> messages, final MessagingListener listener) { threadPool.execute(new Runnable() { @Override public void run() { if (listener != null) { listener.enableProgressIndicator(true); } try { Store remoteStore = account.getRemoteStore(); LocalStore localStore = account.getLocalStore(); if (remoteStore == null || localStore == null) { throw new MessagingException("Could not get store"); } Folder remoteFolder = remoteStore.getFolder(folderName); LocalFolder localFolder = localStore.getFolder(folderName); if (remoteFolder == null || localFolder == null) { throw new MessagingException("Folder not found"); } loadSearchResultsSynchronous(messages, localFolder, remoteFolder, listener); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Exception in loadSearchResults: " + e); addErrorMessage(account, null, e); } finally { if (listener != null) { listener.enableProgressIndicator(false); } } } }); } public void loadSearchResultsSynchronous(List<Message> messages, LocalFolder localFolder, Folder remoteFolder, MessagingListener listener) throws MessagingException { final FetchProfile header = new FetchProfile(); header.add(FetchProfile.Item.FLAGS); header.add(FetchProfile.Item.ENVELOPE); final FetchProfile structure = new FetchProfile(); structure.add(FetchProfile.Item.STRUCTURE); int i = 0; for (Message message : messages) { i++; LocalMessage localMsg = localFolder.getMessage(message.getUid()); if (localMsg == null) { remoteFolder.fetch(new Message [] {message}, header, null); //fun fact: ImapFolder.fetch can't handle getting STRUCTURE at same time as headers remoteFolder.fetch(new Message [] {message}, structure, null); localFolder.appendMessages(new Message [] {message}); localMsg = localFolder.getMessage(message.getUid()); } if (listener != null) { listener.remoteSearchAddMessage(remoteFolder.getAccount(), remoteFolder.getName(), localMsg, i, messages.size()); } } } public void loadMoreMessages(Account account, String folder, MessagingListener listener) { try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(folder); if (localFolder.getVisibleLimit() > 0) { localFolder.setVisibleLimit(localFolder.getVisibleLimit() + account.getDisplayCount()); } synchronizeMailbox(account, folder, listener, null); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Unable to set visible limit on folder", me); } } public void resetVisibleLimits(Collection<Account> accounts) { for (Account account : accounts) { account.resetVisibleLimits(); } } /** * Start background synchronization of the specified folder. * @param account * @param folder * @param listener * @param providedRemoteFolder TODO */ public void synchronizeMailbox(final Account account, final String folder, final MessagingListener listener, final Folder providedRemoteFolder) { putBackground("synchronizeMailbox", listener, new Runnable() { @Override public void run() { synchronizeMailboxSynchronous(account, folder, listener, providedRemoteFolder); } }); } /** * Start foreground synchronization of the specified folder. This is generally only called * by synchronizeMailbox. * @param account * @param folder * * TODO Break this method up into smaller chunks. * @param providedRemoteFolder TODO */ private void synchronizeMailboxSynchronous(final Account account, final String folder, final MessagingListener listener, Folder providedRemoteFolder) { Folder remoteFolder = null; LocalFolder tLocalFolder = null; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Synchronizing folder " + account.getDescription() + ":" + folder); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxStarted(account, folder); } /* * We don't ever sync the Outbox or errors folder */ if (folder.equals(account.getOutboxFolderName()) || folder.equals(account.getErrorFolderName())) { for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, 0, 0); } return; } Exception commandException = null; try { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to process pending commands for account " + account.getDescription()); try { processPendingCommandsSynchronous(account); } catch (Exception e) { addErrorMessage(account, null, e); Log.e(K9.LOG_TAG, "Failure processing command, but allow message sync attempt", e); commandException = e; } /* * Get the message list from the local store and create an index of * the uids within the list. */ if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get local folder " + folder); final LocalStore localStore = account.getLocalStore(); tLocalFolder = localStore.getFolder(folder); final LocalFolder localFolder = tLocalFolder; localFolder.open(OpenMode.READ_WRITE); localFolder.updateLastUid(); Message[] localMessages = localFolder.getMessages(null); HashMap<String, Message> localUidMap = new HashMap<String, Message>(); for (Message message : localMessages) { localUidMap.put(message.getUid(), message); } if (providedRemoteFolder != null) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: using providedRemoteFolder " + folder); remoteFolder = providedRemoteFolder; } else { Store remoteStore = account.getRemoteStore(); if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get remote folder " + folder); remoteFolder = remoteStore.getFolder(folder); if (! verifyOrCreateRemoteSpecialFolder(account, folder, remoteFolder, listener)) { return; } /* * Synchronization process: * Open the folder Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash) Get the message count Get the list of the newest K9.DEFAULT_VISIBLE_LIMIT messages getMessages(messageCount - K9.DEFAULT_VISIBLE_LIMIT, messageCount) See if we have each message locally, if not fetch it's flags and envelope Get and update the unread count for the folder Update the remote flags of any messages we have locally with an internal date newer than the remote message. Get the current flags for any messages we have locally but did not just download Update local flags For any message we have locally but not remotely, delete the local message to keep cache clean. Download larger parts of any new messages. (Optional) Download small attachments in the background. */ /* * Open the remote folder. This pre-loads certain metadata like message count. */ if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to open remote folder " + folder); remoteFolder.open(OpenMode.READ_WRITE); if (Account.EXPUNGE_ON_POLL.equals(account.getExpungePolicy())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Expunging folder " + account.getDescription() + ":" + folder); remoteFolder.expunge(); } } /* * Get the remote message count. */ int remoteMessageCount = remoteFolder.getMessageCount(); int visibleLimit = localFolder.getVisibleLimit(); if (visibleLimit < 0) { visibleLimit = K9.DEFAULT_VISIBLE_LIMIT; } Message[] remoteMessageArray = EMPTY_MESSAGE_ARRAY; final ArrayList<Message> remoteMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: Remote message count for folder " + folder + " is " + remoteMessageCount); final Date earliestDate = account.getEarliestPollDate(); if (remoteMessageCount > 0) { /* Message numbers start at 1. */ int remoteStart; if (visibleLimit > 0) { remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; } else { remoteStart = 1; } int remoteEnd = remoteMessageCount; if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through " + remoteEnd + " for folder " + folder); final AtomicInteger headerProgress = new AtomicInteger(0); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersStarted(account, folder); } remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteEnd, earliestDate, null); int messageCount = remoteMessageArray.length; for (Message thisMess : remoteMessageArray) { headerProgress.incrementAndGet(); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersProgress(account, folder, headerProgress.get(), messageCount); } Message localMessage = localUidMap.get(thisMess.getUid()); if (localMessage == null || !localMessage.olderThan(earliestDate)) { remoteMessages.add(thisMess); remoteUidMap.put(thisMess.getUid(), thisMess); } } if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: Got " + remoteUidMap.size() + " messages for folder " + folder); remoteMessageArray = null; for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersFinished(account, folder, headerProgress.get(), remoteUidMap.size()); } } else if (remoteMessageCount < 0) { throw new Exception("Message count " + remoteMessageCount + " for folder " + folder); } /* * Remove any messages that are in the local store but no longer on the remote store or are too old */ if (account.syncRemoteDeletions()) { ArrayList<Message> destroyMessages = new ArrayList<Message>(); for (Message localMessage : localMessages) { if (remoteUidMap.get(localMessage.getUid()) == null) { destroyMessages.add(localMessage); } } localFolder.destroyMessages(destroyMessages.toArray(EMPTY_MESSAGE_ARRAY)); for (Message destroyMessage : destroyMessages) { for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxRemovedMessage(account, folder, destroyMessage); } } } localMessages = null; /* * Now we download the actual content of messages. */ int newMessages = downloadMessages(account, remoteFolder, localFolder, remoteMessages, false); int unreadMessageCount = localFolder.getUnreadMessageCount(); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, unreadMessageCount); } /* Notify listeners that we're finally done. */ localFolder.setLastChecked(System.currentTimeMillis()); localFolder.setStatus(null); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date() + " with " + newMessages + " new messages"); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages); } if (commandException != null) { String rootMessage = getRootCauseMessage(commandException); Log.e(K9.LOG_TAG, "Root cause failure in " + account.getDescription() + ":" + tLocalFolder.getName() + " was '" + rootMessage + "'"); localFolder.setStatus(rootMessage); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFailed(account, folder, rootMessage); } } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder); } catch (Exception e) { Log.e(K9.LOG_TAG, "synchronizeMailbox", e); // If we don't set the last checked, it can try too often during // failure conditions String rootMessage = getRootCauseMessage(e); if (tLocalFolder != null) { try { tLocalFolder.setStatus(rootMessage); tLocalFolder.setLastChecked(System.currentTimeMillis()); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" + tLocalFolder.getName(), e); } } for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFailed(account, folder, rootMessage); } notifyUserIfCertificateProblem(mApplication, e, account, true); addErrorMessage(account, null, e); Log.e(K9.LOG_TAG, "Failed synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date()); } finally { if (providedRemoteFolder == null) { closeFolder(remoteFolder); } closeFolder(tLocalFolder); } } private void closeFolder(Folder f) { if (f != null) { f.close(); } } /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ private boolean verifyOrCreateRemoteSpecialFolder(final Account account, final String folder, final Folder remoteFolder, final MessagingListener listener) throws MessagingException { if (folder.equals(account.getTrashFolderName()) || folder.equals(account.getSentFolderName()) || folder.equals(account.getDraftsFolderName())) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, 0, 0); } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Done synchronizing folder " + folder); return false; } } } return true; } /** * Fetches the messages described by inputMessages from the remote store and writes them to * local storage. * * @param account * The account the remote store belongs to. * @param remoteFolder * The remote folder to download messages from. * @param localFolder * The {@link LocalFolder} instance corresponding to the remote folder. * @param inputMessages * A list of messages objects that store the UIDs of which messages to download. * @param flagSyncOnly * Only flags will be fetched from the remote store if this is {@code true}. * * @return The number of downloaded messages that are not flagged as {@link Flag#SEEN}. * * @throws MessagingException */ private int downloadMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, List<Message> inputMessages, boolean flagSyncOnly) throws MessagingException { final Date earliestDate = account.getEarliestPollDate(); Date downloadStarted = new Date(); // now if (earliestDate != null) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Only syncing messages after " + earliestDate); } } final String folder = remoteFolder.getName(); int unreadBeforeStart = 0; try { AccountStats stats = account.getStats(mApplication); unreadBeforeStart = stats.unreadMessageCount; } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e); } ArrayList<Message> syncFlagMessages = new ArrayList<Message>(); List<Message> unsyncedMessages = new ArrayList<Message>(); final AtomicInteger newMessages = new AtomicInteger(0); List<Message> messages = new ArrayList<Message>(inputMessages); for (Message message : messages) { evaluateMessageForDownload(message, folder, localFolder, remoteFolder, account, unsyncedMessages, syncFlagMessages , flagSyncOnly); } final AtomicInteger progress = new AtomicInteger(0); final int todo = unsyncedMessages.size() + syncFlagMessages.size(); for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Have " + unsyncedMessages.size() + " unsynced messages"); messages.clear(); final ArrayList<Message> largeMessages = new ArrayList<Message>(); final ArrayList<Message> smallMessages = new ArrayList<Message>(); if (!unsyncedMessages.isEmpty()) { /* * Reverse the order of the messages. Depending on the server this may get us * fetch results for newest to oldest. If not, no harm done. */ Collections.sort(unsyncedMessages, new UidReverseComparator()); int visibleLimit = localFolder.getVisibleLimit(); int listSize = unsyncedMessages.size(); if ((visibleLimit > 0) && (listSize > visibleLimit)) { unsyncedMessages = unsyncedMessages.subList(0, visibleLimit); } FetchProfile fp = new FetchProfile(); if (remoteFolder.supportsFetchingFlags()) { fp.add(FetchProfile.Item.FLAGS); } fp.add(FetchProfile.Item.ENVELOPE); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to fetch " + unsyncedMessages.size() + " unsynced messages for folder " + folder); fetchUnsyncedMessages(account, remoteFolder, localFolder, unsyncedMessages, smallMessages, largeMessages, progress, todo, fp); // If a message didn't exist, messageFinished won't be called, but we shouldn't try again // If we got here, nothing failed for (Message message : unsyncedMessages) { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); if (newPushState != null) { localFolder.setPushState(newPushState); } } if (K9.DEBUG) { Log.d(K9.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder); } } if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Have " + largeMessages.size() + " large messages and " + smallMessages.size() + " small messages out of " + unsyncedMessages.size() + " unsynced messages"); unsyncedMessages.clear(); /* * Grab the content of the small messages first. This is going to * be very fast and at very worst will be a single up of a few bytes and a single * download of 625k. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); // fp.add(FetchProfile.Item.FLAGS); // fp.add(FetchProfile.Item.ENVELOPE); downloadSmallMessages(account, remoteFolder, localFolder, smallMessages, progress, unreadBeforeStart, newMessages, todo, fp); smallMessages.clear(); /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); downloadLargeMessages(account, remoteFolder, localFolder, largeMessages, progress, unreadBeforeStart, newMessages, todo, fp); largeMessages.clear(); /* * Refresh the flags for any messages in the local store that we didn't just * download. */ refreshLocalMessageFlags(account, remoteFolder, localFolder, syncFlagMessages, progress, todo); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Synced remote messages for folder " + folder + ", " + newMessages.get() + " new messages"); localFolder.purgeToVisibleLimit(new MessageRemovalListener() { @Override public void messageRemoved(Message message) { for (MessagingListener l : getListeners()) { l.synchronizeMailboxRemovedMessage(account, folder, message); } } }); // If the oldest message seen on this sync is newer than // the oldest message seen on the previous sync, then // we want to move our high-water mark forward // this is all here just for pop which only syncs inbox // this would be a little wrong for IMAP (we'd want a folder-level pref, not an account level pref.) // fortunately, we just don't care. Long oldestMessageTime = localFolder.getOldestMessageDate(); if (oldestMessageTime != null) { Date oldestExtantMessage = new Date(oldestMessageTime); if (oldestExtantMessage.before(downloadStarted) && oldestExtantMessage.after(new Date(account.getLatestOldMessageSeenTime()))) { account.setLatestOldMessageSeenTime(oldestExtantMessage.getTime()); account.save(Preferences.getPreferences(mApplication.getApplicationContext())); } } return newMessages.get(); } private void evaluateMessageForDownload(final Message message, final String folder, final LocalFolder localFolder, final Folder remoteFolder, final Account account, final List<Message> unsyncedMessages, final ArrayList<Message> syncFlagMessages, boolean flagSyncOnly) throws MessagingException { if (message.isSet(Flag.DELETED)) { syncFlagMessages.add(message); return; } Message localMessage = localFolder.getMessage(message.getUid()); if (localMessage == null) { if (!flagSyncOnly) { if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " has not yet been downloaded"); unsyncedMessages.add(message); } else { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is partially or fully downloaded"); // Store the updated message locally localFolder.appendMessages(new Message[] { message }); localMessage = localFolder.getMessage(message.getUid()); localMessage.setFlag(Flag.X_DOWNLOADED_FULL, message.isSet(Flag.X_DOWNLOADED_FULL)); localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, message.isSet(Flag.X_DOWNLOADED_PARTIAL)); for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } } } } else if (!localMessage.isSet(Flag.DELETED)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is present in the local store"); if (!localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is not downloaded, even partially; trying again"); unsyncedMessages.add(message); } else { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); if (newPushState != null) { localFolder.setPushState(newPushState); } syncFlagMessages.add(message); } } } private void fetchUnsyncedMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, List<Message> unsyncedMessages, final ArrayList<Message> smallMessages, final ArrayList<Message> largeMessages, final AtomicInteger progress, final int todo, FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); /* * Messages to be batch written */ final List<Message> chunk = new ArrayList<Message>(UNSYNC_CHUNK_SIZE); remoteFolder.fetch(unsyncedMessages.toArray(EMPTY_MESSAGE_ARRAY), fp, new MessageRetrievalListener() { @Override public void messageFinished(Message message, int number, int ofTotal) { try { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); if (newPushState != null) { localFolder.setPushState(newPushState); } if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate)) { if (K9.DEBUG) { if (message.isSet(Flag.DELETED)) { Log.v(K9.LOG_TAG, "Newly downloaded message " + account + ":" + folder + ":" + message.getUid() + " was marked deleted on server, skipping"); } else { Log.d(K9.LOG_TAG, "Newly downloaded message " + message.getUid() + " is older than " + earliestDate + ", skipping"); } } progress.incrementAndGet(); for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } return; } if (account.getMaximumAutoDownloadMessageSize() > 0 && message.getSize() > account.getMaximumAutoDownloadMessageSize()) { largeMessages.add(message); } else { smallMessages.add(message); } // And include it in the view if (message.getSubject() != null && message.getFrom() != null) { /* * We check to make sure that we got something worth * showing (subject and from) because some protocols * (POP) may not be able to give us headers for * ENVELOPE, only size. */ // keep message for delayed storing chunk.add(message); if (chunk.size() >= UNSYNC_CHUNK_SIZE) { writeUnsyncedMessages(chunk, localFolder, account, folder); chunk.clear(); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e); addErrorMessage(account, null, e); } } @Override public void messageStarted(String uid, int number, int ofTotal) {} @Override public void messagesFinished(int total) { // FIXME this method is almost never invoked by various Stores! Don't rely on it unless fixed!! } }); if (!chunk.isEmpty()) { writeUnsyncedMessages(chunk, localFolder, account, folder); chunk.clear(); } } /** * Actual storing of messages * * <br> * FIXME: <strong>This method should really be moved in the above MessageRetrievalListener once {@link MessageRetrievalListener#messagesFinished(int)} is properly invoked by various stores</strong> * * @param messages Never <code>null</code>. * @param localFolder * @param account * @param folder */ private void writeUnsyncedMessages(final List<Message> messages, final LocalFolder localFolder, final Account account, final String folder) { if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Batch writing " + Integer.toString(messages.size()) + " messages"); } try { // Store the new message locally localFolder.appendMessages(messages.toArray(new Message[messages.size()])); for (final Message message : messages) { final Message localMessage = localFolder.getMessage(message.getUid()); syncFlags(localMessage, message); if (K9.DEBUG) Log.v(K9.LOG_TAG, "About to notify listeners that we got a new unsynced message " + account + ":" + folder + ":" + message.getUid()); for (final MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); } } } catch (final Exception e) { Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e); addErrorMessage(account, null, e); } } private boolean shouldImportMessage(final Account account, final String folder, final Message message, final AtomicInteger progress, final Date earliestDate) { if (account.isSearchByDateCapable() && message.olderThan(earliestDate)) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than " + earliestDate + ", hence not saving"); } return false; } return true; } private void downloadSmallMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, ArrayList<Message> smallMessages, final AtomicInteger progress, final int unreadBeforeStart, final AtomicInteger newMessages, final int todo, FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Fetching small messages for folder " + folder); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { @Override public void messageFinished(final Message message, int number, int ofTotal) { try { if (!shouldImportMessage(account, folder, message, progress, earliestDate)) { progress.incrementAndGet(); return; } // Store the updated message locally final Message localMessage = localFolder.storeSmallMessage(message, new Runnable() { @Override public void run() { progress.incrementAndGet(); } }); // Increment the number of "new messages" if the newly downloaded message is // not marked as read. if (!localMessage.isSet(Flag.SEEN)) { newMessages.incrementAndGet(); } if (K9.DEBUG) Log.v(K9.LOG_TAG, "About to notify listeners that we got a new small message " + account + ":" + folder + ":" + message.getUid()); // Update the listener with what we've found for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); l.synchronizeMailboxProgress(account, folder, progress.get(), todo); if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } // Send a notification of this message if (shouldNotifyForMessage(account, localFolder, message)) { // Notify with the localMessage so that we don't have to recalculate the content preview. notifyAccount(mApplication, account, localMessage, unreadBeforeStart); } } catch (MessagingException me) { addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "SYNC: fetch small messages", me); } } @Override public void messageStarted(String uid, int number, int ofTotal) {} @Override public void messagesFinished(int total) {} }); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder); } private void downloadLargeMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, ArrayList<Message> largeMessages, final AtomicInteger progress, final int unreadBeforeStart, final AtomicInteger newMessages, final int todo, FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Fetching large messages for folder " + folder); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (!shouldImportMessage(account, folder, message, progress, earliestDate)) { progress.incrementAndGet(); continue; } if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); // Certain (POP3) servers give you the whole message even when you ask for only the first x Kb if (!message.isSet(Flag.X_DOWNLOADED_FULL)) { /* * Mark the message as fully downloaded if the message size is smaller than * the account's autodownload size limit, otherwise mark as only a partial * download. This will prevent the system from downloading the same message * twice. * * If there is no limit on autodownload size, that's the same as the message * being smaller than the max size */ if (account.getMaximumAutoDownloadMessageSize() == 0 || message.getSize() < account.getMaximumAutoDownloadMessageSize()) { localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } else { // Set a flag indicating that the message has been partially downloaded and // is ready for view. localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } } } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ Set<Part> viewables = MimeUtility.collectTextParts(message); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { remoteFolder.fetchPart(message, part, null); } // Store the updated message locally localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } if (K9.DEBUG) Log.v(K9.LOG_TAG, "About to notify listeners that we got a new large message " + account + ":" + folder + ":" + message.getUid()); // Update the listener with what we've found progress.incrementAndGet(); // TODO do we need to re-fetch this here? Message localMessage = localFolder.getMessage(message.getUid()); // Increment the number of "new messages" if the newly downloaded message is // not marked as read. if (!localMessage.isSet(Flag.SEEN)) { newMessages.incrementAndGet(); } for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); l.synchronizeMailboxProgress(account, folder, progress.get(), todo); if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } // Send a notification of this message if (shouldNotifyForMessage(account, localFolder, message)) { // Notify with the localMessage so that we don't have to recalculate the content preview. notifyAccount(mApplication, account, localMessage, unreadBeforeStart); } }//for large messages if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder); } private void refreshLocalMessageFlags(final Account account, final Folder remoteFolder, final LocalFolder localFolder, ArrayList<Message> syncFlagMessages, final AtomicInteger progress, final int todo ) throws MessagingException { final String folder = remoteFolder.getName(); if (remoteFolder.supportsFetchingFlags()) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to sync flags for " + syncFlagMessages.size() + " remote messages for folder " + folder); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); List<Message> undeletedMessages = new LinkedList<Message>(); for (Message message : syncFlagMessages) { if (!message.isSet(Flag.DELETED)) { undeletedMessages.add(message); } } remoteFolder.fetch(undeletedMessages.toArray(EMPTY_MESSAGE_ARRAY), fp, null); for (Message remoteMessage : syncFlagMessages) { Message localMessage = localFolder.getMessage(remoteMessage.getUid()); boolean messageChanged = syncFlags(localMessage, remoteMessage); if (messageChanged) { boolean shouldBeNotifiedOf = false; if (localMessage.isSet(Flag.DELETED) || isMessageSuppressed(account, localMessage)) { for (MessagingListener l : getListeners()) { l.synchronizeMailboxRemovedMessage(account, folder, localMessage); } } else { for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); } if (shouldNotifyForMessage(account, localFolder, localMessage)) { shouldBeNotifiedOf = true; } } // we're only interested in messages that need removing if (!shouldBeNotifiedOf) { NotificationData data = getNotificationData(account, null); if (data != null) { synchronized (data) { MessageReference ref = localMessage.makeMessageReference(); if (data.removeMatchingMessage(mApplication, ref)) { notifyAccountWithDataLocked(mApplication, account, null, data); } } } } } progress.incrementAndGet(); for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } } } } private boolean syncFlags(Message localMessage, Message remoteMessage) throws MessagingException { boolean messageChanged = false; if (localMessage == null || localMessage.isSet(Flag.DELETED)) { return false; } if (remoteMessage.isSet(Flag.DELETED)) { if (localMessage.getFolder().getAccount().syncRemoteDeletions()) { localMessage.setFlag(Flag.DELETED, true); messageChanged = true; } } else { for (Flag flag : MessagingController.SYNC_FLAGS) { if (remoteMessage.isSet(flag) != localMessage.isSet(flag)) { localMessage.setFlag(flag, remoteMessage.isSet(flag)); messageChanged = true; } } } return messageChanged; } private String getRootCauseMessage(Throwable t) { Throwable rootCause = t; Throwable nextCause = rootCause; do { nextCause = rootCause.getCause(); if (nextCause != null) { rootCause = nextCause; } } while (nextCause != null); if (rootCause instanceof MessagingException) { return rootCause.getMessage(); } else { // Remove the namespace on the exception so we have a fighting chance of seeing more of the error in the // notification. return (rootCause.getLocalizedMessage() != null) ? (rootCause.getClass().getSimpleName() + ": " + rootCause.getLocalizedMessage()) : rootCause.getClass().getSimpleName(); } } private void queuePendingCommand(Account account, PendingCommand command) { try { LocalStore localStore = account.getLocalStore(); localStore.addPendingCommand(command); } catch (Exception e) { addErrorMessage(account, null, e); throw new RuntimeException("Unable to enqueue pending command", e); } } private void processPendingCommands(final Account account) { putBackground("processPendingCommands", null, new Runnable() { @Override public void run() { try { processPendingCommandsSynchronous(account); } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to process pending command because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "processPendingCommands", me); addErrorMessage(account, null, me); /* * Ignore any exceptions from the commands. Commands will be processed * on the next round. */ } } }); } private void processPendingCommandsSynchronous(Account account) throws MessagingException { LocalStore localStore = account.getLocalStore(); ArrayList<PendingCommand> commands = localStore.getPendingCommands(); int progress = 0; int todo = commands.size(); if (todo == 0) { return; } for (MessagingListener l : getListeners()) { l.pendingCommandsProcessing(account); l.synchronizeMailboxProgress(account, null, progress, todo); } PendingCommand processingCommand = null; try { for (PendingCommand command : commands) { processingCommand = command; if (K9.DEBUG) Log.d(K9.LOG_TAG, "Processing pending command '" + command + "'"); String[] components = command.command.split("\\."); String commandTitle = components[components.length - 1]; for (MessagingListener l : getListeners()) { l.pendingCommandStarted(account, commandTitle); } /* * We specifically do not catch any exceptions here. If a command fails it is * most likely due to a server or IO error and it must be retried before any * other command processes. This maintains the order of the commands. */ try { if (PENDING_COMMAND_APPEND.equals(command.command)) { processPendingAppend(command, account); } else if (PENDING_COMMAND_SET_FLAG_BULK.equals(command.command)) { processPendingSetFlag(command, account); } else if (PENDING_COMMAND_SET_FLAG.equals(command.command)) { processPendingSetFlagOld(command, account); } else if (PENDING_COMMAND_MARK_ALL_AS_READ.equals(command.command)) { processPendingMarkAllAsRead(command, account); } else if (PENDING_COMMAND_MOVE_OR_COPY_BULK.equals(command.command)) { processPendingMoveOrCopyOld2(command, account); } else if (PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW.equals(command.command)) { processPendingMoveOrCopy(command, account); } else if (PENDING_COMMAND_MOVE_OR_COPY.equals(command.command)) { processPendingMoveOrCopyOld(command, account); } else if (PENDING_COMMAND_EMPTY_TRASH.equals(command.command)) { processPendingEmptyTrash(command, account); } else if (PENDING_COMMAND_EXPUNGE.equals(command.command)) { processPendingExpunge(command, account); } localStore.removePendingCommand(command); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Done processing pending command '" + command + "'"); } catch (MessagingException me) { if (me.isPermanentFailure()) { addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "Failure of command '" + command + "' was permanent, removing command from queue"); localStore.removePendingCommand(processingCommand); } else { throw me; } } finally { progress++; for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, null, progress, todo); l.pendingCommandCompleted(account, commandTitle); } } } } catch (MessagingException me) { notifyUserIfCertificateProblem(mApplication, me, account, true); addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "Could not process command '" + processingCommand + "'", me); throw me; } finally { for (MessagingListener l : getListeners()) { l.pendingCommandsFinished(account); } } } /** * Process a pending append message command. This command uploads a local message to the * server, first checking to be sure that the server message is not newer than * the local message. Once the local message is successfully processed it is deleted so * that the server message will be synchronized down without an additional copy being * created. * TODO update the local message UID instead of deleteing it * * @param command arguments = (String folder, String uid) * @param account * @throws MessagingException */ private void processPendingAppend(PendingCommand command, Account account) throws MessagingException { Folder remoteFolder = null; LocalFolder localFolder = null; try { String folder = command.arguments[0]; String uid = command.arguments[1]; if (account.getErrorFolderName().equals(folder)) { return; } LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); LocalMessage localMessage = localFolder.getMessage(uid); if (localMessage == null) { return; } Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return; } } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } Message remoteMessage = null; if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteFolder.getMessage(localMessage.getUid()); } if (remoteMessage == null) { if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED)) { Log.w(K9.LOG_TAG, "Local message with uid " + localMessage.getUid() + " has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, checking for remote message with " + " same message id"); String rUid = remoteFolder.getUidFromMessageId(localMessage); if (rUid != null) { Log.w(K9.LOG_TAG, "Local message has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, and there is a remote message with " + " uid " + rUid + ", assuming message was already copied and aborting this copy"); String oldUid = localMessage.getUid(); localMessage.setUid(rUid); localFolder.changeUid(localMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } return; } else { Log.w(K9.LOG_TAG, "No remote message with message-id found, proceeding with append"); } } /* * If the message does not exist remotely we just upload it and then * update our local copy with the new uid. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { localMessage } , fp, null); String oldUid = localMessage.getUid(); localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true); remoteFolder.appendMessages(new Message[] { localMessage }); localFolder.changeUid(localMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } } else { /* * If the remote message exists we need to determine which copy to keep. */ /* * See if the remote message is newer than ours. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); remoteFolder.fetch(new Message[] { remoteMessage }, fp, null); Date localDate = localMessage.getInternalDate(); Date remoteDate = remoteMessage.getInternalDate(); if (remoteDate != null && remoteDate.compareTo(localDate) > 0) { /* * If the remote message is newer than ours we'll just * delete ours and move on. A sync will get the server message * if we need to be able to see it. */ localMessage.destroy(); } else { /* * Otherwise we'll upload our message and then delete the remote message. */ fp.clear(); fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { localMessage }, fp, null); String oldUid = localMessage.getUid(); localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true); remoteFolder.appendMessages(new Message[] { localMessage }); localFolder.changeUid(localMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } if (remoteDate != null) { remoteMessage.setFlag(Flag.DELETED, true); if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { remoteFolder.expunge(); } } } } } finally { closeFolder(remoteFolder); closeFolder(localFolder); } } private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[]) { if (account.getErrorFolderName().equals(srcFolder)) { return; } PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW; int length = 4 + uids.length; command.arguments = new String[length]; command.arguments[0] = srcFolder; command.arguments[1] = destFolder; command.arguments[2] = Boolean.toString(isCopy); command.arguments[3] = Boolean.toString(false); System.arraycopy(uids, 0, command.arguments, 4, uids.length); queuePendingCommand(account, command); } private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[], Map<String, String> uidMap) { if (uidMap == null || uidMap.isEmpty()) { queueMoveOrCopy(account, srcFolder, destFolder, isCopy, uids); } else { if (account.getErrorFolderName().equals(srcFolder)) { return; } PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW; int length = 4 + uidMap.keySet().size() + uidMap.values().size(); command.arguments = new String[length]; command.arguments[0] = srcFolder; command.arguments[1] = destFolder; command.arguments[2] = Boolean.toString(isCopy); command.arguments[3] = Boolean.toString(true); System.arraycopy(uidMap.keySet().toArray(), 0, command.arguments, 4, uidMap.keySet().size()); System.arraycopy(uidMap.values().toArray(), 0, command.arguments, 4 + uidMap.keySet().size(), uidMap.values().size()); queuePendingCommand(account, command); } } /** * Convert pending command to new format and call * {@link #processPendingMoveOrCopy(PendingCommand, Account)}. * * <p> * TODO: This method is obsolete and is only for transition from K-9 4.0 to K-9 4.2 * Eventually, it should be removed. * </p> * * @param command * Pending move/copy command in old format. * @param account * The account the pending command belongs to. * * @throws MessagingException * In case of an error. */ private void processPendingMoveOrCopyOld2(PendingCommand command, Account account) throws MessagingException { PendingCommand newCommand = new PendingCommand(); int len = command.arguments.length; newCommand.command = PENDING_COMMAND_MOVE_OR_COPY_BULK_NEW; newCommand.arguments = new String[len + 1]; newCommand.arguments[0] = command.arguments[0]; newCommand.arguments[1] = command.arguments[1]; newCommand.arguments[2] = command.arguments[2]; newCommand.arguments[3] = Boolean.toString(false); System.arraycopy(command.arguments, 3, newCommand.arguments, 4, len - 3); processPendingMoveOrCopy(newCommand, account); } /** * Process a pending trash message command. * * @param command arguments = (String folder, String uid) * @param account * @throws MessagingException */ private void processPendingMoveOrCopy(PendingCommand command, Account account) throws MessagingException { Folder remoteSrcFolder = null; Folder remoteDestFolder = null; LocalFolder localDestFolder = null; try { String srcFolder = command.arguments[0]; if (account.getErrorFolderName().equals(srcFolder)) { return; } String destFolder = command.arguments[1]; String isCopyS = command.arguments[2]; String hasNewUidsS = command.arguments[3]; boolean hasNewUids = false; if (hasNewUidsS != null) { hasNewUids = Boolean.parseBoolean(hasNewUidsS); } Store remoteStore = account.getRemoteStore(); remoteSrcFolder = remoteStore.getFolder(srcFolder); Store localStore = account.getLocalStore(); localDestFolder = (LocalFolder) localStore.getFolder(destFolder); List<Message> messages = new ArrayList<Message>(); /* * We split up the localUidMap into two parts while sending the command, here we assemble it back. */ Map<String, String> localUidMap = new HashMap<String, String>(); if (hasNewUids) { int offset = (command.arguments.length - 4) / 2; for (int i = 4; i < 4 + offset; i++) { localUidMap.put(command.arguments[i], command.arguments[i + offset]); String uid = command.arguments[i]; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { messages.add(remoteSrcFolder.getMessage(uid)); } } } else { for (int i = 4; i < command.arguments.length; i++) { String uid = command.arguments[i]; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { messages.add(remoteSrcFolder.getMessage(uid)); } } } boolean isCopy = false; if (isCopyS != null) { isCopy = Boolean.parseBoolean(isCopyS); } if (!remoteSrcFolder.exists()) { throw new MessagingException("processingPendingMoveOrCopy: remoteFolder " + srcFolder + " does not exist", true); } remoteSrcFolder.open(OpenMode.READ_WRITE); if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processingPendingMoveOrCopy: could not open remoteSrcFolder " + srcFolder + " read/write", true); } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy: source folder = " + srcFolder + ", " + messages.size() + " messages, destination folder = " + destFolder + ", isCopy = " + isCopy); Map <String, String> remoteUidMap = null; if (!isCopy && destFolder.equals(account.getTrashFolderName())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy doing special case for deleting message"); String destFolderName = destFolder; if (K9.FOLDER_NONE.equals(destFolderName)) { destFolderName = null; } remoteSrcFolder.delete(messages.toArray(EMPTY_MESSAGE_ARRAY), destFolderName); } else { remoteDestFolder = remoteStore.getFolder(destFolder); if (isCopy) { remoteUidMap = remoteSrcFolder.copyMessages(messages.toArray(EMPTY_MESSAGE_ARRAY), remoteDestFolder); } else { remoteUidMap = remoteSrcFolder.moveMessages(messages.toArray(EMPTY_MESSAGE_ARRAY), remoteDestFolder); } } if (!isCopy && Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "processingPendingMoveOrCopy expunging folder " + account.getDescription() + ":" + srcFolder); remoteSrcFolder.expunge(); } /* * This next part is used to bring the local UIDs of the local destination folder * upto speed with the remote UIDs of remote destionation folder. */ if (!localUidMap.isEmpty() && remoteUidMap != null && !remoteUidMap.isEmpty()) { Set<Map.Entry<String, String>> remoteSrcEntries = remoteUidMap.entrySet(); Iterator<Map.Entry<String, String>> remoteSrcEntriesIterator = remoteSrcEntries.iterator(); while (remoteSrcEntriesIterator.hasNext()) { Map.Entry<String, String> entry = remoteSrcEntriesIterator.next(); String remoteSrcUid = entry.getKey(); String localDestUid = localUidMap.get(remoteSrcUid); String newUid = entry.getValue(); Message localDestMessage = localDestFolder.getMessage(localDestUid); if (localDestMessage != null) { localDestMessage.setUid(newUid); localDestFolder.changeUid((LocalMessage)localDestMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, destFolder, localDestUid, newUid); } } } } } finally { closeFolder(remoteSrcFolder); closeFolder(remoteDestFolder); } } private void queueSetFlag(final Account account, final String folderName, final String newState, final String flag, final String[] uids) { putBackground("queueSetFlag " + account.getDescription() + ":" + folderName, null, new Runnable() { @Override public void run() { PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_SET_FLAG_BULK; int length = 3 + uids.length; command.arguments = new String[length]; command.arguments[0] = folderName; command.arguments[1] = newState; command.arguments[2] = flag; System.arraycopy(uids, 0, command.arguments, 3, uids.length); queuePendingCommand(account, command); processPendingCommands(account); } }); } /** * Processes a pending mark read or unread command. * * @param command arguments = (String folder, String uid, boolean read) * @param account */ private void processPendingSetFlag(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; if (account.getErrorFolderName().equals(folder)) { return; } boolean newState = Boolean.parseBoolean(command.arguments[1]); Flag flag = Flag.valueOf(command.arguments[2]); Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists() || !remoteFolder.isFlagSupported(flag)) { return; } try { remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } List<Message> messages = new ArrayList<Message>(); for (int i = 3; i < command.arguments.length; i++) { String uid = command.arguments[i]; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { messages.add(remoteFolder.getMessage(uid)); } } if (messages.isEmpty()) { return; } remoteFolder.setFlags(messages.toArray(EMPTY_MESSAGE_ARRAY), new Flag[] { flag }, newState); } finally { closeFolder(remoteFolder); } } // TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1 // Eventually, it should be removed private void processPendingSetFlagOld(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; String uid = command.arguments[1]; if (account.getErrorFolderName().equals(folder)) { return; } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingSetFlagOld: folder = " + folder + ", uid = " + uid); boolean newState = Boolean.parseBoolean(command.arguments[2]); Flag flag = Flag.valueOf(command.arguments[3]); Folder remoteFolder = null; try { Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } Message remoteMessage = null; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteFolder.getMessage(uid); } if (remoteMessage == null) { return; } remoteMessage.setFlag(flag, newState); } finally { closeFolder(remoteFolder); } } private void queueExpunge(final Account account, final String folderName) { putBackground("queueExpunge " + account.getDescription() + ":" + folderName, null, new Runnable() { @Override public void run() { PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_EXPUNGE; command.arguments = new String[1]; command.arguments[0] = folderName; queuePendingCommand(account, command); processPendingCommands(account); } }); } private void processPendingExpunge(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; if (account.getErrorFolderName().equals(folder)) { return; } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingExpunge: folder = " + folder); Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(folder); try { if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } remoteFolder.expunge(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingExpunge: complete for folder = " + folder); } finally { closeFolder(remoteFolder); } } // TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1 // Eventually, it should be removed private void processPendingMoveOrCopyOld(PendingCommand command, Account account) throws MessagingException { String srcFolder = command.arguments[0]; String uid = command.arguments[1]; String destFolder = command.arguments[2]; String isCopyS = command.arguments[3]; boolean isCopy = false; if (isCopyS != null) { isCopy = Boolean.parseBoolean(isCopyS); } if (account.getErrorFolderName().equals(srcFolder)) { return; } Store remoteStore = account.getRemoteStore(); Folder remoteSrcFolder = remoteStore.getFolder(srcFolder); Folder remoteDestFolder = remoteStore.getFolder(destFolder); if (!remoteSrcFolder.exists()) { throw new MessagingException("processPendingMoveOrCopyOld: remoteFolder " + srcFolder + " does not exist", true); } remoteSrcFolder.open(OpenMode.READ_WRITE); if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteSrcFolder " + srcFolder + " read/write", true); } Message remoteMessage = null; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteSrcFolder.getMessage(uid); } if (remoteMessage == null) { throw new MessagingException("processPendingMoveOrCopyOld: remoteMessage " + uid + " does not exist", true); } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld: source folder = " + srcFolder + ", uid = " + uid + ", destination folder = " + destFolder + ", isCopy = " + isCopy); if (!isCopy && destFolder.equals(account.getTrashFolderName())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld doing special case for deleting message"); remoteMessage.delete(account.getTrashFolderName()); remoteSrcFolder.close(); return; } remoteDestFolder.open(OpenMode.READ_WRITE); if (remoteDestFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteDestFolder " + srcFolder + " read/write", true); } if (isCopy) { remoteSrcFolder.copyMessages(new Message[] { remoteMessage }, remoteDestFolder); } else { remoteSrcFolder.moveMessages(new Message[] { remoteMessage }, remoteDestFolder); } remoteSrcFolder.close(); remoteDestFolder.close(); } private void processPendingMarkAllAsRead(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; Folder remoteFolder = null; LocalFolder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = (LocalFolder) localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); Message[] messages = localFolder.getMessages(null, false); for (Message message : messages) { if (!message.isSet(Flag.SEEN)) { message.setFlag(Flag.SEEN, true); for (MessagingListener l : getListeners()) { l.listLocalMessagesUpdateMessage(account, folder, message); } } } for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, 0); } if (account.getErrorFolderName().equals(folder)) { return; } Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists() || !remoteFolder.isFlagSupported(Flag.SEEN)) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } remoteFolder.setFlags(new Flag[] {Flag.SEEN}, true); remoteFolder.close(); } catch (UnsupportedOperationException uoe) { Log.w(K9.LOG_TAG, "Could not mark all server-side as read because store doesn't support operation", uoe); } finally { closeFolder(localFolder); closeFolder(remoteFolder); } } private void notifyUserIfCertificateProblem(Context context, Exception e, Account account, boolean incoming) { if (!(e instanceof CertificateValidationException)) { return; } CertificateValidationException cve = (CertificateValidationException) e; if (!cve.needsUserAttention()) { return; } final int id = incoming ? K9.CERTIFICATE_EXCEPTION_NOTIFICATION_INCOMING + account.getAccountNumber() : K9.CERTIFICATE_EXCEPTION_NOTIFICATION_OUTGOING + account.getAccountNumber(); final Intent i = incoming ? AccountSetupIncoming.intentActionEditIncomingSettings(context, account) : AccountSetupOutgoing.intentActionEditOutgoingSettings(context, account); final PendingIntent pi = PendingIntent.getActivity(context, account.getAccountNumber(), i, PendingIntent.FLAG_UPDATE_CURRENT); final String title = context.getString( R.string.notification_certificate_error_title, account.getName()); final NotificationCompat.Builder builder = new NotificationBuilder(context); builder.setSmallIcon(R.drawable.ic_notify_new_mail); builder.setWhen(System.currentTimeMillis()); builder.setAutoCancel(true); builder.setTicker(title); builder.setContentTitle(title); builder.setContentText(context.getString(R.string.notification_certificate_error_text)); builder.setContentIntent(pi); configureNotification(builder, null, null, K9.NOTIFICATION_LED_FAILURE_COLOR, K9.NOTIFICATION_LED_BLINK_FAST, true); final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(null, id, builder.build()); } public void clearCertificateErrorNotifications(Context context, final Account account, boolean incoming, boolean outgoing) { final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (incoming) { nm.cancel(null, K9.CERTIFICATE_EXCEPTION_NOTIFICATION_INCOMING + account.getAccountNumber()); } if (outgoing) { nm.cancel(null, K9.CERTIFICATE_EXCEPTION_NOTIFICATION_OUTGOING + account.getAccountNumber()); } } static long uidfill = 0; static AtomicBoolean loopCatch = new AtomicBoolean(); public void addErrorMessage(Account account, String subject, Throwable t) { if (!loopCatch.compareAndSet(false, true)) { return; } try { if (t == null) { return; } CharArrayWriter baos = new CharArrayWriter(t.getStackTrace().length * 10); PrintWriter ps = new PrintWriter(baos); t.printStackTrace(ps); ps.close(); if (subject == null) { subject = getRootCauseMessage(t); } addErrorMessage(account, subject, baos.toString()); } catch (Throwable it) { Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it); } finally { loopCatch.set(false); } } public void addErrorMessage(Account account, String subject, String body) { if (!K9.ENABLE_ERROR_FOLDER) { return; } if (!loopCatch.compareAndSet(false, true)) { return; } try { if (body == null || body.length() < 1) { return; } Store localStore = account.getLocalStore(); LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName()); Message[] messages = new Message[1]; MimeMessage message = new MimeMessage(); message.setBody(new TextBody(body)); message.setFlag(Flag.X_DOWNLOADED_FULL, true); message.setSubject(subject); long nowTime = System.currentTimeMillis(); Date nowDate = new Date(nowTime); message.setInternalDate(nowDate); message.addSentDate(nowDate); message.setFrom(new Address(account.getEmail(), "K9mail internal")); messages[0] = message; localFolder.appendMessages(messages); localFolder.clearMessagesOlderThan(nowTime - (15 * 60 * 1000)); } catch (Throwable it) { Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it); } finally { loopCatch.set(false); } } public void markAllMessagesRead(final Account account, final String folder) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Marking all messages in " + account.getDescription() + ":" + folder + " as read"); List<String> args = new ArrayList<String>(); args.add(folder); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_MARK_ALL_AS_READ; command.arguments = args.toArray(EMPTY_STRING_ARRAY); queuePendingCommand(account, command); processPendingCommands(account); } public void setFlag(final Account account, final List<Long> messageIds, final Flag flag, final boolean newState) { setFlagInCache(account, messageIds, flag, newState); threadPool.execute(new Runnable() { @Override public void run() { setFlagSynchronous(account, messageIds, flag, newState, false); } }); } public void setFlagForThreads(final Account account, final List<Long> threadRootIds, final Flag flag, final boolean newState) { setFlagForThreadsInCache(account, threadRootIds, flag, newState); threadPool.execute(new Runnable() { @Override public void run() { setFlagSynchronous(account, threadRootIds, flag, newState, true); } }); } private void setFlagSynchronous(final Account account, final List<Long> ids, final Flag flag, final boolean newState, final boolean threadedList) { LocalStore localStore; try { localStore = account.getLocalStore(); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Couldn't get LocalStore instance", e); return; } // Update affected messages in the database. This should be as fast as possible so the UI // can be updated with the new state. try { if (threadedList) { localStore.setFlagForThreads(ids, flag, newState); removeFlagFromCache(account, ids, flag); } else { localStore.setFlag(ids, flag, newState); removeFlagForThreadsFromCache(account, ids, flag); } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Couldn't set flags in local database", e); } // Read folder name and UID of messages from the database Map<String, List<String>> folderMap; try { folderMap = localStore.getFoldersAndUids(ids, threadedList); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Couldn't get folder name and UID of messages", e); return; } // Loop over all folders for (Entry<String, List<String>> entry : folderMap.entrySet()) { String folderName = entry.getKey(); // Notify listeners of changed folder status LocalFolder localFolder = localStore.getFolder(folderName); try { int unreadMessageCount = localFolder.getUnreadMessageCount(); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folderName, unreadMessageCount); } } catch (MessagingException e) { Log.w(K9.LOG_TAG, "Couldn't get unread count for folder: " + folderName, e); } // The error folder is always a local folder // TODO: Skip the remote part for all local-only folders if (account.getErrorFolderName().equals(folderName)) { continue; } // Send flag change to server String[] uids = entry.getValue().toArray(EMPTY_STRING_ARRAY); queueSetFlag(account, folderName, Boolean.toString(newState), flag.toString(), uids); processPendingCommands(account); } } /** * Set or remove a flag for a set of messages in a specific folder. * * <p> * The {@link Message} objects passed in are updated to reflect the new flag state. * </p> * * @param account * The account the folder containing the messages belongs to. * @param folderName * The name of the folder. * @param messages * The messages to change the flag for. * @param flag * The flag to change. * @param newState * {@code true}, if the flag should be set. {@code false} if it should be removed. */ public void setFlag(Account account, String folderName, Message[] messages, Flag flag, boolean newState) { // TODO: Put this into the background, but right now some callers depend on the message // objects being modified right after this method returns. Folder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(folderName); localFolder.open(OpenMode.READ_WRITE); // Allows for re-allowing sending of messages that could not be sent if (flag == Flag.FLAGGED && !newState && account.getOutboxFolderName().equals(folderName)) { for (Message message : messages) { String uid = message.getUid(); if (uid != null) { sendCount.remove(uid); } } } // Update the messages in the local store localFolder.setFlags(messages, new Flag[] {flag}, newState); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folderName, localFolder.getUnreadMessageCount()); } /* * Handle the remote side */ // The error folder is always a local folder // TODO: Skip the remote part for all local-only folders if (account.getErrorFolderName().equals(folderName)) { return; } String[] uids = new String[messages.length]; for (int i = 0, end = uids.length; i < end; i++) { uids[i] = messages[i].getUid(); } queueSetFlag(account, folderName, Boolean.toString(newState), flag.toString(), uids); processPendingCommands(account); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException(me); } finally { closeFolder(localFolder); } } /** * Set or remove a flag for a message referenced by message UID. * * @param account * The account the folder containing the message belongs to. * @param folderName * The name of the folder. * @param uid * The UID of the message to change the flag for. * @param flag * The flag to change. * @param newState * {@code true}, if the flag should be set. {@code false} if it should be removed. */ public void setFlag(Account account, String folderName, String uid, Flag flag, boolean newState) { Folder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(folderName); localFolder.open(OpenMode.READ_WRITE); Message message = localFolder.getMessage(uid); if (message != null) { setFlag(account, folderName, new Message[] { message }, flag, newState); } } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException(me); } finally { closeFolder(localFolder); } } public void clearAllPending(final Account account) { try { Log.w(K9.LOG_TAG, "Clearing pending commands!"); LocalStore localStore = account.getLocalStore(); localStore.removePendingCommands(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to clear pending command", me); addErrorMessage(account, null, me); } } public void loadMessageForViewRemote(final Account account, final String folder, final String uid, final MessagingListener listener) { put("loadMessageForViewRemote", listener, new Runnable() { @Override public void run() { loadMessageForViewRemoteSynchronous(account, folder, uid, listener, false, false); } }); } public boolean loadMessageForViewRemoteSynchronous(final Account account, final String folder, final String uid, final MessagingListener listener, final boolean force, final boolean loadPartialFromSearch) { Folder remoteFolder = null; LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); Message message = localFolder.getMessage(uid); if (uid.startsWith(K9.LOCAL_UID_PREFIX)) { Log.w(K9.LOG_TAG, "Message has local UID so cannot download fully."); // ASH move toast android.widget.Toast.makeText(mApplication, "Message has local UID so cannot download fully", android.widget.Toast.LENGTH_LONG).show(); // TODO: Using X_DOWNLOADED_FULL is wrong because it's only a partial message. But // one we can't download completely. Maybe add a new flag; X_PARTIAL_MESSAGE ? message.setFlag(Flag.X_DOWNLOADED_FULL, true); message.setFlag(Flag.X_DOWNLOADED_PARTIAL, false); } /* commented out because this was pulled from another unmerged branch: } else if (localFolder.isLocalOnly() && !force) { Log.w(K9.LOG_TAG, "Message in local-only folder so cannot download fully."); // ASH move toast android.widget.Toast.makeText(mApplication, "Message in local-only folder so cannot download fully", android.widget.Toast.LENGTH_LONG).show(); message.setFlag(Flag.X_DOWNLOADED_FULL, true); message.setFlag(Flag.X_DOWNLOADED_PARTIAL, false); }*/ if (message.isSet(Flag.X_DOWNLOADED_FULL)) { /* * If the message has been synchronized since we were called we'll * just hand it back cause it's ready to go. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { message }, fp, null); } else { /* * At this point the message is not available, so we need to download it * fully if possible. */ Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); remoteFolder.open(OpenMode.READ_WRITE); // Get the remote message and fully download it Message remoteMessage = remoteFolder.getMessage(uid); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(new Message[] { remoteMessage }, fp, null); // Store the message locally and load the stored message into memory localFolder.appendMessages(new Message[] { remoteMessage }); if (loadPartialFromSearch) { fp.add(FetchProfile.Item.BODY); } fp.add(FetchProfile.Item.ENVELOPE); message = localFolder.getMessage(uid); localFolder.fetch(new Message[] { message }, fp, null); // Mark that this message is now fully synched if (account.isMarkMessageAsReadOnView()) { message.setFlag(Flag.SEEN, true); } message.setFlag(Flag.X_DOWNLOADED_FULL, true); } // now that we have the full message, refresh the headers for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewHeadersAvailable(account, folder, uid, message); } for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewBodyAvailable(account, folder, uid, message); } for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFinished(account, folder, uid, message); } return true; } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFailed(account, folder, uid, e); } notifyUserIfCertificateProblem(mApplication, e, account, true); addErrorMessage(account, null, e); return false; } finally { closeFolder(remoteFolder); closeFolder(localFolder); } } public void loadMessageForView(final Account account, final String folder, final String uid, final MessagingListener listener) { for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewStarted(account, folder, uid); } threadPool.execute(new Runnable() { @Override public void run() { try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); LocalMessage message = localFolder.getMessage(uid); if (message == null || message.getId() == 0) { throw new IllegalArgumentException("Message not found: folder=" + folder + ", uid=" + uid); } // IMAP search results will usually need to be downloaded before viewing. // TODO: limit by account.getMaximumAutoDownloadMessageSize(). if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL)) { if (loadMessageForViewRemoteSynchronous(account, folder, uid, listener, false, true)) { markMessageAsReadOnView(account, message); } return; } markMessageAsReadOnView(account, message); for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewHeadersAvailable(account, folder, uid, message); } FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { message }, fp, null); localFolder.close(); for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewBodyAvailable(account, folder, uid, message); } for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFinished(account, folder, uid, message); } } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFailed(account, folder, uid, e); } addErrorMessage(account, null, e); } } }); } /** * Mark the provided message as read if not disabled by the account setting. * * @param account * The account the message belongs to. * @param message * The message to mark as read. This {@link Message} instance will be modify by calling * {@link Message#setFlag(Flag, boolean)} on it. * * @throws MessagingException * * @see Account#isMarkMessageAsReadOnView() */ private void markMessageAsReadOnView(Account account, Message message) throws MessagingException { if (account.isMarkMessageAsReadOnView() && !message.isSet(Flag.SEEN)) { message.setFlag(Flag.SEEN, true); setFlagSynchronous(account, Collections.singletonList(Long.valueOf(message.getId())), Flag.SEEN, true, false); } } /** * Attempts to load the attachment specified by part from the given account and message. * @param account * @param message * @param part * @param listener */ public void loadAttachment( final Account account, final Message message, final Part part, final Object tag, final MessagingListener listener) { /* * Check if the attachment has already been downloaded. If it has there's no reason to * download it, so we just tell the listener that it's ready to go. */ if (part.getBody() != null) { for (MessagingListener l : getListeners(listener)) { l.loadAttachmentStarted(account, message, part, tag, false); } for (MessagingListener l : getListeners(listener)) { l.loadAttachmentFinished(account, message, part, tag); } return; } for (MessagingListener l : getListeners(listener)) { l.loadAttachmentStarted(account, message, part, tag, true); } put("loadAttachment", listener, new Runnable() { @Override public void run() { Folder remoteFolder = null; LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); List<Part> attachments = MimeUtility.collectAttachments(message); for (Part attachment : attachments) { attachment.setBody(null); } Store remoteStore = account.getRemoteStore(); localFolder = localStore.getFolder(message.getFolder().getName()); remoteFolder = remoteStore.getFolder(message.getFolder().getName()); remoteFolder.open(OpenMode.READ_WRITE); //FIXME: This is an ugly hack that won't be needed once the Message objects have been united. Message remoteMessage = remoteFolder.getMessage(message.getUid()); remoteMessage.setBody(message.getBody()); remoteFolder.fetchPart(remoteMessage, part, null); localFolder.updateMessage((LocalMessage)message); for (MessagingListener l : getListeners(listener)) { l.loadAttachmentFinished(account, message, part, tag); } } catch (MessagingException me) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Exception loading attachment", me); for (MessagingListener l : getListeners(listener)) { l.loadAttachmentFailed(account, message, part, tag, me.getMessage()); } notifyUserIfCertificateProblem(mApplication, me, account, true); addErrorMessage(account, null, me); } finally { closeFolder(localFolder); closeFolder(remoteFolder); } } }); } /** * Stores the given message in the Outbox and starts a sendPendingMessages command to * attempt to send the message. * @param account * @param message * @param listener */ public void sendMessage(final Account account, final Message message, MessagingListener listener) { try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(account.getOutboxFolderName()); localFolder.open(OpenMode.READ_WRITE); localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); localFolder.close(); sendPendingMessages(account, listener); } catch (Exception e) { /* for (MessagingListener l : getListeners()) { // TODO general failed } */ addErrorMessage(account, null, e); } } public void sendPendingMessages(MessagingListener listener) { final Preferences prefs = Preferences.getPreferences(mApplication.getApplicationContext()); for (Account account : prefs.getAvailableAccounts()) { sendPendingMessages(account, listener); } } /** * Attempt to send any messages that are sitting in the Outbox. * @param account * @param listener */ public void sendPendingMessages(final Account account, MessagingListener listener) { putBackground("sendPendingMessages", listener, new Runnable() { @Override public void run() { if (!account.isAvailable(mApplication)) { throw new UnavailableAccountException(); } if (messagesPendingSend(account)) { notifyWhileSending(account); try { sendPendingMessagesSynchronous(account); } finally { notifyWhileSendingDone(account); } } } }); } private void cancelNotification(int id) { NotificationManager notifMgr = (NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE); notifMgr.cancel(id); } private void notifyWhileSendingDone(Account account) { if (account.isShowOngoing()) { cancelNotification(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber()); } } /** * Display an ongoing notification while a message is being sent. * * @param account * The account the message is sent from. Never {@code null}. */ private void notifyWhileSending(Account account) { if (!account.isShowOngoing()) { return; } NotificationManager notifMgr = (NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationBuilder(mApplication); builder.setSmallIcon(R.drawable.ic_notify_check_mail); builder.setWhen(System.currentTimeMillis()); builder.setOngoing(true); builder.setTicker(mApplication.getString(R.string.notification_bg_send_ticker, account.getDescription())); builder.setContentTitle(mApplication.getString(R.string.notification_bg_send_title)); builder.setContentText(account.getDescription()); LocalSearch search = new LocalSearch(account.getInboxFolderName()); search.addAllowedFolder(account.getInboxFolderName()); search.addAccountUuid(account.getUuid()); Intent intent = MessageList.intentDisplaySearch(mApplication, search, false, true, true); PendingIntent pi = PendingIntent.getActivity(mApplication, 0, intent, 0); builder.setContentIntent(pi); if (K9.NOTIFICATION_LED_WHILE_SYNCING) { configureNotification(builder, null, null, account.getNotificationSetting().getLedColor(), K9.NOTIFICATION_LED_BLINK_FAST, true); } notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(), builder.build()); } private void notifySendTempFailed(Account account, Exception lastFailure) { notifySendFailed(account, lastFailure, account.getOutboxFolderName()); } private void notifySendPermFailed(Account account, Exception lastFailure) { notifySendFailed(account, lastFailure, account.getDraftsFolderName()); } /** * Display a notification when sending a message has failed. * * @param account * The account that was used to sent the message. * @param lastFailure * The {@link Exception} instance that indicated sending the message has failed. * @param openFolder * The name of the folder to open when the notification is clicked. */ private void notifySendFailed(Account account, Exception lastFailure, String openFolder) { NotificationManager notifMgr = (NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationBuilder(mApplication); builder.setSmallIcon(R.drawable.ic_notify_new_mail); builder.setWhen(System.currentTimeMillis()); builder.setAutoCancel(true); builder.setTicker(mApplication.getString(R.string.send_failure_subject)); builder.setContentTitle(mApplication.getString(R.string.send_failure_subject)); builder.setContentText(getRootCauseMessage(lastFailure)); Intent i = FolderList.actionHandleNotification(mApplication, account, openFolder); PendingIntent pi = PendingIntent.getActivity(mApplication, 0, i, 0); builder.setContentIntent(pi); configureNotification(builder, null, null, K9.NOTIFICATION_LED_FAILURE_COLOR, K9.NOTIFICATION_LED_BLINK_FAST, true); notifMgr.notify(K9.SEND_FAILED_NOTIFICATION - account.getAccountNumber(), builder.build()); } /** * Display an ongoing notification while checking for new messages on the server. * * @param account * The account that is checked for new messages. Never {@code null}. * @param folder * The folder that is being checked for new messages. Never {@code null}. */ private void notifyFetchingMail(final Account account, final Folder folder) { if (!account.isShowOngoing()) { return; } final NotificationManager notifMgr = (NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationBuilder(mApplication); builder.setSmallIcon(R.drawable.ic_notify_check_mail); builder.setWhen(System.currentTimeMillis()); builder.setOngoing(true); builder.setTicker(mApplication.getString( R.string.notification_bg_sync_ticker, account.getDescription(), folder.getName())); builder.setContentTitle(mApplication.getString(R.string.notification_bg_sync_title)); builder.setContentText(account.getDescription() + mApplication.getString(R.string.notification_bg_title_separator) + folder.getName()); LocalSearch search = new LocalSearch(account.getInboxFolderName()); search.addAllowedFolder(account.getInboxFolderName()); search.addAccountUuid(account.getUuid()); Intent intent = MessageList.intentDisplaySearch(mApplication, search, false, true, true); PendingIntent pi = PendingIntent.getActivity(mApplication, 0, intent, 0); builder.setContentIntent(pi); if (K9.NOTIFICATION_LED_WHILE_SYNCING) { configureNotification(builder, null, null, account.getNotificationSetting().getLedColor(), K9.NOTIFICATION_LED_BLINK_FAST, true); } notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(), builder.build()); } private void notifyFetchingMailCancel(final Account account) { if (account.isShowOngoing()) { cancelNotification(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber()); } } public boolean messagesPendingSend(final Account account) { Folder localFolder = null; try { localFolder = account.getLocalStore().getFolder( account.getOutboxFolderName()); if (!localFolder.exists()) { return false; } localFolder.open(OpenMode.READ_WRITE); if (localFolder.getMessageCount() > 0) { return true; } } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while checking for unsent messages", e); } finally { closeFolder(localFolder); } return false; } /** * Attempt to send any messages that are sitting in the Outbox. * @param account */ public void sendPendingMessagesSynchronous(final Account account) { Folder localFolder = null; Exception lastFailure = null; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder( account.getOutboxFolderName()); if (!localFolder.exists()) { return; } for (MessagingListener l : getListeners()) { l.sendPendingMessagesStarted(account); } localFolder.open(OpenMode.READ_WRITE); Message[] localMessages = localFolder.getMessages(null); int progress = 0; int todo = localMessages.length; for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo); } /* * The profile we will use to pull all of the content * for a given local message into memory for sending. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Scanning folder '" + account.getOutboxFolderName() + "' (" + ((LocalFolder)localFolder).getId() + ") for messages to send"); Transport transport = Transport.getInstance(account); for (Message message : localMessages) { if (message.isSet(Flag.DELETED)) { message.destroy(); continue; } try { AtomicInteger count = new AtomicInteger(0); AtomicInteger oldCount = sendCount.putIfAbsent(message.getUid(), count); if (oldCount != null) { count = oldCount; } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Send count for message " + message.getUid() + " is " + count.get()); if (count.incrementAndGet() > K9.MAX_SEND_ATTEMPTS) { Log.e(K9.LOG_TAG, "Send count for message " + message.getUid() + " can't be delivered after " + K9.MAX_SEND_ATTEMPTS + " attempts. Giving up until the user restarts the device"); notifySendTempFailed(account, new MessagingException(message.getSubject())); continue; } localFolder.fetch(new Message[] { message }, fp, null); try { if (message.getHeader(K9.IDENTITY_HEADER) != null) { Log.v(K9.LOG_TAG, "The user has set the Outbox and Drafts folder to the same thing. " + "This message appears to be a draft, so K-9 will not send it"); continue; } message.setFlag(Flag.X_SEND_IN_PROGRESS, true); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Sending message with UID " + message.getUid()); transport.sendMessage(message); message.setFlag(Flag.X_SEND_IN_PROGRESS, false); message.setFlag(Flag.SEEN, true); progress++; for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo); } if (!account.hasSentFolder()) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Account does not have a sent mail folder; deleting sent message"); message.setFlag(Flag.DELETED, true); } else { LocalFolder localSentFolder = (LocalFolder) localStore.getFolder(account.getSentFolderName()); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Moving sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") "); localFolder.moveMessages(new Message[] { message }, localSentFolder); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Moved sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") "); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; command.arguments = new String[] { localSentFolder.getName(), message.getUid() }; queuePendingCommand(account, command); processPendingCommands(account); } } catch (Exception e) { // 5.x.x errors from the SMTP server are "PERMFAIL" // move the message over to drafts rather than leaving it in the outbox // This is a complete hack, but is worlds better than the previous // "don't even bother" functionality if (getRootCauseMessage(e).startsWith("5")) { localFolder.moveMessages(new Message[] { message }, (LocalFolder) localStore.getFolder(account.getDraftsFolderName())); } notifyUserIfCertificateProblem(mApplication, e, account, false); message.setFlag(Flag.X_SEND_FAILED, true); Log.e(K9.LOG_TAG, "Failed to send message", e); for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed(account, localFolder.getName(), getRootCauseMessage(e)); } lastFailure = e; } } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to fetch message for sending", e); for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed(account, localFolder.getName(), getRootCauseMessage(e)); } lastFailure = e; } } for (MessagingListener l : getListeners()) { l.sendPendingMessagesCompleted(account); } if (lastFailure != null) { if (getRootCauseMessage(lastFailure).startsWith("5")) { notifySendPermFailed(account, lastFailure); } else { notifySendTempFailed(account, lastFailure); } } } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to send pending messages because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { for (MessagingListener l : getListeners()) { l.sendPendingMessagesFailed(account); } addErrorMessage(account, null, e); } finally { if (lastFailure == null) { cancelNotification(K9.SEND_FAILED_NOTIFICATION - account.getAccountNumber()); } closeFolder(localFolder); } } public void getAccountStats(final Context context, final Account account, final MessagingListener listener) { threadPool.execute(new Runnable() { @Override public void run() { try { AccountStats stats = account.getStats(context); listener.accountStatusChanged(account, stats); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me); } } }); } public void getSearchAccountStats(final SearchAccount searchAccount, final MessagingListener listener) { threadPool.execute(new Runnable() { @Override public void run() { getSearchAccountStatsSynchronous(searchAccount, listener); } }); } public AccountStats getSearchAccountStatsSynchronous(final SearchAccount searchAccount, final MessagingListener listener) { Preferences preferences = Preferences.getPreferences(mApplication); LocalSearch search = searchAccount.getRelatedSearch(); // Collect accounts that belong to the search String[] accountUuids = search.getAccountUuids(); Account[] accounts; if (search.searchAllAccounts()) { accounts = preferences.getAccounts(); } else { accounts = new Account[accountUuids.length]; for (int i = 0, len = accountUuids.length; i < len; i++) { String accountUuid = accountUuids[i]; accounts[i] = preferences.getAccount(accountUuid); } } ContentResolver cr = mApplication.getContentResolver(); int unreadMessageCount = 0; int flaggedMessageCount = 0; String[] projection = { StatsColumns.UNREAD_COUNT, StatsColumns.FLAGGED_COUNT }; for (Account account : accounts) { StringBuilder query = new StringBuilder(); List<String> queryArgs = new ArrayList<String>(); ConditionsTreeNode conditions = search.getConditions(); SqlQueryBuilder.buildWhereClause(account, conditions, query, queryArgs); String selection = query.toString(); String[] selectionArgs = queryArgs.toArray(EMPTY_STRING_ARRAY); Uri uri = Uri.withAppendedPath(EmailProvider.CONTENT_URI, "account/" + account.getUuid() + "/stats"); // Query content provider to get the account stats Cursor cursor = cr.query(uri, projection, selection, selectionArgs, null); try { if (cursor.moveToFirst()) { unreadMessageCount += cursor.getInt(0); flaggedMessageCount += cursor.getInt(1); } } finally { cursor.close(); } } // Create AccountStats instance... AccountStats stats = new AccountStats(); stats.unreadMessageCount = unreadMessageCount; stats.flaggedMessageCount = flaggedMessageCount; // ...and notify the listener if (listener != null) { listener.accountStatusChanged(searchAccount, stats); } return stats; } public void getFolderUnreadMessageCount(final Account account, final String folderName, final MessagingListener l) { Runnable unreadRunnable = new Runnable() { @Override public void run() { int unreadMessageCount = 0; try { Folder localFolder = account.getLocalStore().getFolder(folderName); unreadMessageCount = localFolder.getUnreadMessageCount(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me); } l.folderStatusChanged(account, folderName, unreadMessageCount); } }; put("getFolderUnread:" + account.getDescription() + ":" + folderName, l, unreadRunnable); } public boolean isMoveCapable(Message message) { return !message.getUid().startsWith(K9.LOCAL_UID_PREFIX); } public boolean isCopyCapable(Message message) { return isMoveCapable(message); } public boolean isMoveCapable(final Account account) { try { Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); return localStore.isMoveCapable() && remoteStore.isMoveCapable(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Exception while ascertaining move capability", me); return false; } } public boolean isCopyCapable(final Account account) { try { Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); return localStore.isCopyCapable() && remoteStore.isCopyCapable(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Exception while ascertaining copy capability", me); return false; } } public void moveMessages(final Account account, final String srcFolder, final List<Message> messages, final String destFolder, final MessagingListener listener) { suppressMessages(account, messages); putBackground("moveMessages", null, new Runnable() { @Override public void run() { moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, false, listener); } }); } public void moveMessagesInThread(final Account account, final String srcFolder, final List<Message> messages, final String destFolder) { suppressMessages(account, messages); putBackground("moveMessagesInThread", null, new Runnable() { @Override public void run() { try { List<Message> messagesInThreads = collectMessagesInThreads(account, messages); moveOrCopyMessageSynchronous(account, srcFolder, messagesInThreads, destFolder, false, null); } catch (MessagingException e) { addErrorMessage(account, "Exception while moving messages", e); } } }); } public void moveMessage(final Account account, final String srcFolder, final Message message, final String destFolder, final MessagingListener listener) { moveMessages(account, srcFolder, Collections.singletonList(message), destFolder, listener); } public void copyMessages(final Account account, final String srcFolder, final List<Message> messages, final String destFolder, final MessagingListener listener) { putBackground("copyMessages", null, new Runnable() { @Override public void run() { moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, true, listener); } }); } public void copyMessagesInThread(final Account account, final String srcFolder, final List<Message> messages, final String destFolder) { putBackground("copyMessagesInThread", null, new Runnable() { @Override public void run() { try { List<Message> messagesInThreads = collectMessagesInThreads(account, messages); moveOrCopyMessageSynchronous(account, srcFolder, messagesInThreads, destFolder, true, null); } catch (MessagingException e) { addErrorMessage(account, "Exception while copying messages", e); } } }); } public void copyMessage(final Account account, final String srcFolder, final Message message, final String destFolder, final MessagingListener listener) { copyMessages(account, srcFolder, Collections.singletonList(message), destFolder, listener); } private void moveOrCopyMessageSynchronous(final Account account, final String srcFolder, final List<Message> inMessages, final String destFolder, final boolean isCopy, MessagingListener listener) { try { Map<String, String> uidMap = new HashMap<String, String>(); Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); if (!isCopy && (!remoteStore.isMoveCapable() || !localStore.isMoveCapable())) { return; } if (isCopy && (!remoteStore.isCopyCapable() || !localStore.isCopyCapable())) { return; } Folder localSrcFolder = localStore.getFolder(srcFolder); Folder localDestFolder = localStore.getFolder(destFolder); boolean unreadCountAffected = false; List<String> uids = new LinkedList<String>(); for (Message message : inMessages) { String uid = message.getUid(); if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { uids.add(uid); } if (!unreadCountAffected && !message.isSet(Flag.SEEN)) { unreadCountAffected = true; } } Message[] messages = localSrcFolder.getMessages(uids.toArray(EMPTY_STRING_ARRAY), null); if (messages.length > 0) { Map<String, Message> origUidMap = new HashMap<String, Message>(); for (Message message : messages) { origUidMap.put(message.getUid(), message); } if (K9.DEBUG) Log.i(K9.LOG_TAG, "moveOrCopyMessageSynchronous: source folder = " + srcFolder + ", " + messages.length + " messages, " + ", destination folder = " + destFolder + ", isCopy = " + isCopy); if (isCopy) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localSrcFolder.fetch(messages, fp, null); uidMap = localSrcFolder.copyMessages(messages, localDestFolder); if (unreadCountAffected) { // If this copy operation changes the unread count in the destination // folder, notify the listeners. int unreadMessageCount = localDestFolder.getUnreadMessageCount(); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, destFolder, unreadMessageCount); } } } else { uidMap = localSrcFolder.moveMessages(messages, localDestFolder); for (Map.Entry<String, Message> entry : origUidMap.entrySet()) { String origUid = entry.getKey(); Message message = entry.getValue(); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, srcFolder, origUid, message.getUid()); } } unsuppressMessages(account, messages); if (unreadCountAffected) { // If this move operation changes the unread count, notify the listeners // that the unread count changed in both the source and destination folder. int unreadMessageCountSrc = localSrcFolder.getUnreadMessageCount(); int unreadMessageCountDest = localDestFolder.getUnreadMessageCount(); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, srcFolder, unreadMessageCountSrc); l.folderStatusChanged(account, destFolder, unreadMessageCountDest); } } } queueMoveOrCopy(account, srcFolder, destFolder, isCopy, origUidMap.keySet().toArray(EMPTY_STRING_ARRAY), uidMap); } processPendingCommands(account); } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to move/copy message because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Error moving message", me); } } public void expunge(final Account account, final String folder, final MessagingListener listener) { putBackground("expunge", null, new Runnable() { @Override public void run() { queueExpunge(account, folder); } }); } public void deleteDraft(final Account account, long id) { LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(account.getDraftsFolderName()); localFolder.open(OpenMode.READ_WRITE); String uid = localFolder.getMessageUidById(id); if (uid != null) { Message message = localFolder.getMessage(uid); if (message != null) { deleteMessages(Collections.singletonList(message), null); } } } catch (MessagingException me) { addErrorMessage(account, null, me); } finally { closeFolder(localFolder); } } public void deleteThreads(final List<Message> messages) { actOnMessages(messages, new MessageActor() { @Override public void act(final Account account, final Folder folder, final List<Message> accountMessages) { suppressMessages(account, messages); putBackground("deleteThreads", null, new Runnable() { @Override public void run() { deleteThreadsSynchronous(account, folder.getName(), accountMessages); } }); } }); } public void deleteThreadsSynchronous(Account account, String folderName, List<Message> messages) { try { List<Message> messagesToDelete = collectMessagesInThreads(account, messages); deleteMessagesSynchronous(account, folderName, messagesToDelete.toArray(EMPTY_MESSAGE_ARRAY), null); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Something went wrong while deleting threads", e); } } public List<Message> collectMessagesInThreads(Account account, List<Message> messages) throws MessagingException { LocalStore localStore = account.getLocalStore(); List<Message> messagesInThreads = new ArrayList<Message>(); for (Message message : messages) { LocalMessage localMessage = (LocalMessage) message; long rootId = localMessage.getRootId(); long threadId = (rootId == -1) ? localMessage.getThreadId() : rootId; Message[] messagesInThread = localStore.getMessagesInThread(threadId); Collections.addAll(messagesInThreads, messagesInThread); } return messagesInThreads; } public void deleteMessages(final List<Message> messages, final MessagingListener listener) { actOnMessages(messages, new MessageActor() { @Override public void act(final Account account, final Folder folder, final List<Message> accountMessages) { suppressMessages(account, messages); putBackground("deleteMessages", null, new Runnable() { @Override public void run() { deleteMessagesSynchronous(account, folder.getName(), accountMessages.toArray(EMPTY_MESSAGE_ARRAY), listener); } }); } }); } private void deleteMessagesSynchronous(final Account account, final String folder, final Message[] messages, MessagingListener listener) { Folder localFolder = null; Folder localTrashFolder = null; String[] uids = getUidsFromMessages(messages); try { //We need to make these callbacks before moving the messages to the trash //as messages get a new UID after being moved for (Message message : messages) { for (MessagingListener l : getListeners(listener)) { l.messageDeleted(account, folder, message); } } Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); Map<String, String> uidMap = null; if (folder.equals(account.getTrashFolderName()) || !account.hasTrashFolder()) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Deleting messages in trash folder or trash set to -None-, not copying"); localFolder.setFlags(messages, new Flag[] { Flag.DELETED }, true); } else { localTrashFolder = localStore.getFolder(account.getTrashFolderName()); if (!localTrashFolder.exists()) { localTrashFolder.create(Folder.FolderType.HOLDS_MESSAGES); } if (localTrashFolder.exists()) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Deleting messages in normal folder, moving"); uidMap = localFolder.moveMessages(messages, localTrashFolder); } } for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, localFolder.getUnreadMessageCount()); if (localTrashFolder != null) { l.folderStatusChanged(account, account.getTrashFolderName(), localTrashFolder.getUnreadMessageCount()); } } if (K9.DEBUG) Log.d(K9.LOG_TAG, "Delete policy for account " + account.getDescription() + " is " + account.getDeletePolicy()); if (folder.equals(account.getOutboxFolderName())) { for (Message message : messages) { // If the message was in the Outbox, then it has been copied to local Trash, and has // to be copied to remote trash PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; command.arguments = new String[] { account.getTrashFolderName(), message.getUid() }; queuePendingCommand(account, command); } processPendingCommands(account); } else if (account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE) { if (folder.equals(account.getTrashFolderName())) { queueSetFlag(account, folder, Boolean.toString(true), Flag.DELETED.toString(), uids); } else { queueMoveOrCopy(account, folder, account.getTrashFolderName(), false, uids, uidMap); } processPendingCommands(account); } else if (account.getDeletePolicy() == Account.DELETE_POLICY_MARK_AS_READ) { queueSetFlag(account, folder, Boolean.toString(true), Flag.SEEN.toString(), uids); processPendingCommands(account); } else { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Delete policy " + account.getDeletePolicy() + " prevents delete from server"); } unsuppressMessages(account, messages); } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to delete message because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Error deleting message from local store.", me); } finally { closeFolder(localFolder); closeFolder(localTrashFolder); } } private String[] getUidsFromMessages(Message[] messages) { String[] uids = new String[messages.length]; for (int i = 0; i < messages.length; i++) { uids[i] = messages[i].getUid(); } return uids; } private void processPendingEmptyTrash(PendingCommand command, Account account) throws MessagingException { Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(account.getTrashFolderName()); try { if (remoteFolder.exists()) { remoteFolder.open(OpenMode.READ_WRITE); remoteFolder.setFlags(new Flag [] { Flag.DELETED }, true); if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { remoteFolder.expunge(); } // When we empty trash, we need to actually synchronize the folder // or local deletes will never get cleaned up synchronizeFolder(account, remoteFolder, true, 0, null); compact(account, null); } } finally { closeFolder(remoteFolder); } } public void emptyTrash(final Account account, MessagingListener listener) { putBackground("emptyTrash", listener, new Runnable() { @Override public void run() { LocalFolder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = (LocalFolder) localStore.getFolder(account.getTrashFolderName()); localFolder.open(OpenMode.READ_WRITE); localFolder.setFlags(new Flag[] { Flag.DELETED }, true); for (MessagingListener l : getListeners()) { l.emptyTrashCompleted(account); } List<String> args = new ArrayList<String>(); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_EMPTY_TRASH; command.arguments = args.toArray(EMPTY_STRING_ARRAY); queuePendingCommand(account, command); processPendingCommands(account); } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to empty trash because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { Log.e(K9.LOG_TAG, "emptyTrash failed", e); addErrorMessage(account, null, e); } finally { closeFolder(localFolder); } } }); } public void sendAlternate(final Context context, Account account, Message message) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "About to load message " + account.getDescription() + ":" + message.getFolder().getName() + ":" + message.getUid() + " for sendAlternate"); loadMessageForView(account, message.getFolder().getName(), message.getUid(), new MessagingListener() { @Override public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, Message message) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got message " + account.getDescription() + ":" + folder + ":" + message.getUid() + " for sendAlternate"); try { Intent msg = new Intent(Intent.ACTION_SEND); String quotedText = null; Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain"); if (part == null) { part = MimeUtility.findFirstPartByMimeType(message, "text/html"); } if (part != null) { quotedText = MimeUtility.getTextFromPart(part); } if (quotedText != null) { msg.putExtra(Intent.EXTRA_TEXT, quotedText); } msg.putExtra(Intent.EXTRA_SUBJECT, message.getSubject()); Address[] from = message.getFrom(); String[] senders = new String[from.length]; for (int i = 0; i < from.length; i++) { senders[i] = from[i].toString(); } msg.putExtra(Intents.Share.EXTRA_FROM, senders); Address[] to = message.getRecipients(RecipientType.TO); String[] recipientsTo = new String[to.length]; for (int i = 0; i < to.length; i++) { recipientsTo[i] = to[i].toString(); } msg.putExtra(Intent.EXTRA_EMAIL, recipientsTo); Address[] cc = message.getRecipients(RecipientType.CC); String[] recipientsCc = new String[cc.length]; for (int i = 0; i < cc.length; i++) { recipientsCc[i] = cc[i].toString(); } msg.putExtra(Intent.EXTRA_CC, recipientsCc); msg.setType("text/plain"); context.startActivity(Intent.createChooser(msg, context.getString(R.string.send_alternate_chooser_title))); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to send email through alternate program", me); } } }); } /** * Checks mail for one or multiple accounts. If account is null all accounts * are checked. * * @param context * @param account * @param listener */ public void checkMail(final Context context, final Account account, final boolean ignoreLastCheckedTime, final boolean useManualWakeLock, final MessagingListener listener) { TracingWakeLock twakeLock = null; if (useManualWakeLock) { TracingPowerManager pm = TracingPowerManager.getPowerManager(context); twakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "K9 MessagingController.checkMail"); twakeLock.setReferenceCounted(false); twakeLock.acquire(K9.MANUAL_WAKE_LOCK_TIMEOUT); } final TracingWakeLock wakeLock = twakeLock; for (MessagingListener l : getListeners()) { l.checkMailStarted(context, account); } putBackground("checkMail", listener, new Runnable() { @Override public void run() { try { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Starting mail check"); Preferences prefs = Preferences.getPreferences(context); Collection<Account> accounts; if (account != null) { accounts = new ArrayList<Account>(1); accounts.add(account); } else { accounts = prefs.getAvailableAccounts(); } for (final Account account : accounts) { checkMailForAccount(context, account, ignoreLastCheckedTime, prefs, listener); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to synchronize mail", e); addErrorMessage(account, null, e); } putBackground("finalize sync", null, new Runnable() { @Override public void run() { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Finished mail sync"); if (wakeLock != null) { wakeLock.release(); } for (MessagingListener l : getListeners()) { l.checkMailFinished(context, account); } } } ); } }); } private void checkMailForAccount(final Context context, final Account account, final boolean ignoreLastCheckedTime, final Preferences prefs, final MessagingListener listener) { if (!account.isAvailable(context)) { if (K9.DEBUG) { Log.i(K9.LOG_TAG, "Skipping synchronizing unavailable account " + account.getDescription()); } return; } final long accountInterval = account.getAutomaticCheckIntervalMinutes() * 60 * 1000; if (!ignoreLastCheckedTime && accountInterval <= 0) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Skipping synchronizing account " + account.getDescription()); return; } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Synchronizing account " + account.getDescription()); account.setRingNotified(false); sendPendingMessages(account, listener); try { Account.FolderMode aDisplayMode = account.getFolderDisplayMode(); Account.FolderMode aSyncMode = account.getFolderSyncMode(); Store localStore = account.getLocalStore(); for (final Folder folder : localStore.getPersonalNamespaces(false)) { folder.open(Folder.OpenMode.READ_WRITE); folder.refresh(prefs); Folder.FolderClass fDisplayClass = folder.getDisplayClass(); Folder.FolderClass fSyncClass = folder.getSyncClass(); if (modeMismatch(aDisplayMode, fDisplayClass)) { // Never sync a folder that isn't displayed /* if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() + " which is in display mode " + fDisplayClass + " while account is in display mode " + aDisplayMode); */ continue; } if (modeMismatch(aSyncMode, fSyncClass)) { // Do not sync folders in the wrong class /* if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() + " which is in sync mode " + fSyncClass + " while account is in sync mode " + aSyncMode); */ continue; } synchronizeFolder(account, folder, ignoreLastCheckedTime, accountInterval, listener); } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to synchronize account " + account.getName(), e); addErrorMessage(account, null, e); } finally { putBackground("clear notification flag for " + account.getDescription(), null, new Runnable() { @Override public void run() { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Clearing notification flag for " + account.getDescription()); account.setRingNotified(false); try { AccountStats stats = account.getStats(context); if (stats == null || stats.unreadMessageCount == 0) { notifyAccountCancel(context, account); } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e); } } } ); } } private void synchronizeFolder( final Account account, final Folder folder, final boolean ignoreLastCheckedTime, final long accountInterval, final MessagingListener listener) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Folder " + folder.getName() + " was last synced @ " + new Date(folder.getLastChecked())); if (!ignoreLastCheckedTime && folder.getLastChecked() > (System.currentTimeMillis() - accountInterval)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() + ", previously synced @ " + new Date(folder.getLastChecked()) + " which would be too recent for the account period"); return; } putBackground("sync" + folder.getName(), null, new Runnable() { @Override public void run() { LocalFolder tLocalFolder = null; try { // In case multiple Commands get enqueued, don't run more than // once final LocalStore localStore = account.getLocalStore(); tLocalFolder = localStore.getFolder(folder.getName()); tLocalFolder.open(Folder.OpenMode.READ_WRITE); if (!ignoreLastCheckedTime && tLocalFolder.getLastChecked() > (System.currentTimeMillis() - accountInterval)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not running Command for folder " + folder.getName() + ", previously synced @ " + new Date(folder.getLastChecked()) + " which would be too recent for the account period"); return; } notifyFetchingMail(account, folder); try { synchronizeMailboxSynchronous(account, folder.getName(), listener, null); } finally { notifyFetchingMailCancel(account); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while processing folder " + account.getDescription() + ":" + folder.getName(), e); addErrorMessage(account, null, e); } finally { closeFolder(tLocalFolder); } } } ); } public void compact(final Account account, final MessagingListener ml) { putBackground("compact:" + account.getDescription(), ml, new Runnable() { @Override public void run() { try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.compact(); long newSize = localStore.getSize(); for (MessagingListener l : getListeners(ml)) { l.accountSizeChanged(account, oldSize, newSize); } } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to compact account because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to compact account " + account.getDescription(), e); } } }); } public void clear(final Account account, final MessagingListener ml) { putBackground("clear:" + account.getDescription(), ml, new Runnable() { @Override public void run() { try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.clear(); localStore.resetVisibleLimits(account.getDisplayCount()); long newSize = localStore.getSize(); AccountStats stats = new AccountStats(); stats.size = newSize; stats.unreadMessageCount = 0; stats.flaggedMessageCount = 0; for (MessagingListener l : getListeners(ml)) { l.accountSizeChanged(account, oldSize, newSize); l.accountStatusChanged(account, stats); } } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to clear account because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to clear account " + account.getDescription(), e); } } }); } public void recreate(final Account account, final MessagingListener ml) { putBackground("recreate:" + account.getDescription(), ml, new Runnable() { @Override public void run() { try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.recreate(); localStore.resetVisibleLimits(account.getDisplayCount()); long newSize = localStore.getSize(); AccountStats stats = new AccountStats(); stats.size = newSize; stats.unreadMessageCount = 0; stats.flaggedMessageCount = 0; for (MessagingListener l : getListeners(ml)) { l.accountSizeChanged(account, oldSize, newSize); l.accountStatusChanged(account, stats); } } catch (UnavailableStorageException e) { Log.i(K9.LOG_TAG, "Failed to recreate an account because storage is not available - trying again later."); throw new UnavailableAccountException(e); } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to recreate account " + account.getDescription(), e); } } }); } private boolean shouldNotifyForMessage(Account account, LocalFolder localFolder, Message message) { // If we don't even have an account name, don't show the notification. // (This happens during initial account setup) if (account.getName() == null) { return false; } // Do not notify if the user does not have notifications enabled or if the message has // been read. if (!account.isNotifyNewMail() || message.isSet(Flag.SEEN)) { return false; } // If the account is a POP3 account and the message is older than the oldest message we've // previously seen, then don't notify about it. if (account.getStoreUri().startsWith("pop3") && message.olderThan(new Date(account.getLatestOldMessageSeenTime()))) { return false; } // No notification for new messages in Trash, Drafts, Spam or Sent folder. // But do notify if it's the INBOX (see issue 1817). Folder folder = message.getFolder(); if (folder != null) { String folderName = folder.getName(); if (!account.getInboxFolderName().equals(folderName) && (account.getTrashFolderName().equals(folderName) || account.getDraftsFolderName().equals(folderName) || account.getSpamFolderName().equals(folderName) || account.getSentFolderName().equals(folderName))) { return false; } } if (message.getUid() != null && localFolder.getLastUid() != null) { try { Integer messageUid = Integer.parseInt(message.getUid()); if (messageUid <= localFolder.getLastUid()) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Message uid is " + messageUid + ", max message uid is " + localFolder.getLastUid() + ". Skipping notification."); return false; } } catch (NumberFormatException e) { // Nothing to be done here. } } // Don't notify if the sender address matches one of our identities and the user chose not // to be notified for such messages. if (account.isAnIdentity(message.getFrom()) && !account.isNotifySelfNewMail()) { return false; } return true; } /** * Get the pending notification data for an account. * See {@link NotificationData}. * * @param account The account to retrieve the pending data for * @param previousUnreadMessageCount The number of currently pending messages, which will be used * if there's no pending data yet. If passed as null, a new instance * won't be created if currently not existent. * @return A pending data instance, or null if one doesn't exist and * previousUnreadMessageCount was passed as null. */ private NotificationData getNotificationData(Account account, Integer previousUnreadMessageCount) { NotificationData data; synchronized (notificationData) { data = notificationData.get(account.getAccountNumber()); if (data == null && previousUnreadMessageCount != null) { data = new NotificationData(previousUnreadMessageCount); notificationData.put(account.getAccountNumber(), data); } } return data; } private CharSequence getMessageSender(Context context, Account account, Message message) { try { boolean isSelf = false; final Contacts contacts = K9.showContactName() ? Contacts.getInstance(context) : null; final Address[] fromAddrs = message.getFrom(); if (fromAddrs != null) { isSelf = account.isAnIdentity(fromAddrs); if (!isSelf && fromAddrs.length > 0) { return fromAddrs[0].toFriendly(contacts).toString(); } } if (isSelf) { // show To: if the message was sent from me Address[] rcpts = message.getRecipients(Message.RecipientType.TO); if (rcpts != null && rcpts.length > 0) { return context.getString(R.string.message_to_fmt, rcpts[0].toFriendly(contacts).toString()); } return context.getString(R.string.general_no_sender); } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to get sender information for notification.", e); } return null; } private CharSequence getMessageSubject(Context context, Message message) { String subject = message.getSubject(); if (!TextUtils.isEmpty(subject)) { return subject; } return context.getString(R.string.general_no_subject); } private static TextAppearanceSpan sEmphasizedSpan; private TextAppearanceSpan getEmphasizedSpan(Context context) { if (sEmphasizedSpan == null) { sEmphasizedSpan = new TextAppearanceSpan(context, R.style.TextAppearance_StatusBar_EventContent_Emphasized); } return sEmphasizedSpan; } private CharSequence getMessagePreview(Context context, Message message) { CharSequence subject = getMessageSubject(context, message); String snippet = message.getPreview(); if (TextUtils.isEmpty(subject)) { return snippet; } else if (TextUtils.isEmpty(snippet)) { return subject; } SpannableStringBuilder preview = new SpannableStringBuilder(); preview.append(subject); preview.append('\n'); preview.append(snippet); preview.setSpan(getEmphasizedSpan(context), 0, subject.length(), 0); return preview; } private CharSequence buildMessageSummary(Context context, CharSequence sender, CharSequence subject) { if (sender == null) { return subject; } SpannableStringBuilder summary = new SpannableStringBuilder(); summary.append(sender); summary.append(" "); summary.append(subject); summary.setSpan(getEmphasizedSpan(context), 0, sender.length(), 0); return summary; } private static final boolean platformShowsNumberInNotification() { // Honeycomb and newer don't show the number as overlay on the notification icon. // However, the number will appear in the detailed notification view. return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; } public static final boolean platformSupportsExtendedNotifications() { // supported in Jellybean // TODO: use constant once target SDK is set to >= 16 return Build.VERSION.SDK_INT >= 16; } private Message findNewestMessageForNotificationLocked(Context context, Account account, NotificationData data) { if (!data.messages.isEmpty()) { return data.messages.getFirst(); } if (!data.droppedMessages.isEmpty()) { return data.droppedMessages.getFirst().restoreToLocalMessage(context); } return null; } /** * Creates a notification of a newly received message. */ private void notifyAccount(Context context, Account account, Message message, int previousUnreadMessageCount) { final NotificationData data = getNotificationData(account, previousUnreadMessageCount); synchronized (data) { notifyAccountWithDataLocked(context, account, message, data); } } private void notifyAccountWithDataLocked(Context context, Account account, Message message, NotificationData data) { boolean updateSilently = false; if (message == null) { /* this can happen if a message we previously notified for is read or deleted remotely */ message = findNewestMessageForNotificationLocked(context, account, data); updateSilently = true; if (message == null) { // seemingly both the message list as well as the overflow list is empty; // it probably is a good idea to cancel the notification in that case notifyAccountCancel(context, account); return; } } else { data.addMessage(message); } final KeyguardManager keyguardService = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); final CharSequence sender = getMessageSender(context, account, message); final CharSequence subject = getMessageSubject(context, message); CharSequence summary = buildMessageSummary(context, sender, subject); // If privacy mode active and keyguard active // OR // GlobalPreference is ALWAYS hide subject // OR // If we could not set a per-message notification, revert to a default message if ((K9.getNotificationHideSubject() == NotificationHideSubject.WHEN_LOCKED && keyguardService.inKeyguardRestrictedInputMode()) || (K9.getNotificationHideSubject() == NotificationHideSubject.ALWAYS) || summary.length() == 0) { summary = context.getString(R.string.notification_new_title); } NotificationManager notifMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationBuilder(context); builder.setSmallIcon(R.drawable.ic_notify_new_mail); builder.setWhen(System.currentTimeMillis()); if (!updateSilently) { builder.setTicker(summary); } final int newMessages = data.getNewMessageCount(); final int unreadCount = data.unreadBeforeNotification + newMessages; if (account.isNotificationShowsUnreadCount() || platformShowsNumberInNotification()) { builder.setNumber(unreadCount); } String accountDescr = (account.getDescription() != null) ? account.getDescription() : account.getEmail(); final ArrayList<MessageReference> allRefs = data.getAllMessageRefs(); if (platformSupportsExtendedNotifications()) { if (newMessages > 1) { // multiple messages pending, show inbox style NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(builder); for (Message m : data.messages) { style.addLine(buildMessageSummary(context, getMessageSender(context, account, m), getMessageSubject(context, m))); } if (!data.droppedMessages.isEmpty()) { style.setSummaryText(context.getString(R.string.notification_additional_messages, data.droppedMessages.size(), accountDescr)); } String title = context.getString(R.string.notification_new_messages_title, newMessages); style.setBigContentTitle(title); builder.setContentTitle(title); builder.setSubText(accountDescr); builder.setStyle(style); } else { // single message pending, show big text NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle(builder); CharSequence preview = getMessagePreview(context, message); if (preview != null) { style.bigText(preview); } builder.setContentText(subject); builder.setSubText(accountDescr); builder.setContentTitle(sender); builder.setStyle(style); builder.addAction(R.drawable.ic_action_single_message_options_dark, context.getString(R.string.notification_action_reply), NotificationActionService.getReplyIntent(context, account, message.makeMessageReference())); } builder.addAction(R.drawable.ic_action_mark_as_read_dark, context.getString(R.string.notification_action_read), NotificationActionService.getReadAllMessagesIntent(context, account, allRefs)); NotificationQuickDelete deleteOption = K9.getNotificationQuickDeleteBehaviour(); boolean showDeleteAction = deleteOption == NotificationQuickDelete.ALWAYS || (deleteOption == NotificationQuickDelete.FOR_SINGLE_MSG && newMessages == 1); if (showDeleteAction) { // we need to pass the action directly to the activity, otherwise the // status bar won't be pulled up and we won't see the confirmation (if used) builder.addAction(R.drawable.ic_action_delete_dark, context.getString(R.string.notification_action_delete), NotificationDeleteConfirmation.getIntent(context, account, allRefs)); } } else { String accountNotice = context.getString(R.string.notification_new_one_account_fmt, unreadCount, accountDescr); builder.setContentTitle(accountNotice); builder.setContentText(summary); } for (Message m : data.messages) { if (m.isSet(Flag.FLAGGED)) { builder.setPriority(NotificationCompat.PRIORITY_HIGH); break; } } Intent targetIntent; boolean treatAsSingleMessageNotification; if (platformSupportsExtendedNotifications()) { // in the new-style notifications, we focus on the new messages, not the unread ones treatAsSingleMessageNotification = newMessages == 1; } else { // in the old-style notifications, we focus on unread messages, as we don't have a // good way to express the new message count treatAsSingleMessageNotification = unreadCount == 1; } if (treatAsSingleMessageNotification) { targetIntent = MessageList.actionHandleNotificationIntent( context, message.makeMessageReference()); } else { String initialFolder = message.getFolder().getName(); /* only go to folder if all messages are in the same folder, else go to folder list */ for (MessageReference ref : allRefs) { if (!TextUtils.equals(initialFolder, ref.folderName)) { initialFolder = null; break; } } targetIntent = FolderList.actionHandleNotification(context, account, initialFolder); } builder.setContentIntent(PendingIntent.getActivity(context, account.getAccountNumber(), targetIntent, PendingIntent.FLAG_UPDATE_CURRENT)); builder.setDeleteIntent(NotificationActionService.getAcknowledgeIntent(context, account)); // Only ring or vibrate if we have not done so already on this account and fetch boolean ringAndVibrate = false; if (!updateSilently && !account.isRingNotified()) { account.setRingNotified(true); ringAndVibrate = true; } NotificationSetting n = account.getNotificationSetting(); configureNotification( builder, (n.shouldRing()) ? n.getRingtone() : null, (n.shouldVibrate()) ? n.getVibration() : null, (n.isLed()) ? Integer.valueOf(n.getLedColor()) : null, K9.NOTIFICATION_LED_BLINK_SLOW, ringAndVibrate); notifMgr.notify(account.getAccountNumber(), builder.build()); } /** * Configure the notification sound and LED * * @param builder * {@link NotificationCompat.Builder} instance used to configure the notification. * Never {@code null}. * @param ringtone * String name of ringtone. {@code null}, if no ringtone should be played. * @param vibrationPattern * {@code long[]} vibration pattern. {@code null}, if no vibration should be played. * @param ledColor * Color to flash LED. {@code null}, if no LED flash should happen. * @param ledSpeed * Either {@link K9#NOTIFICATION_LED_BLINK_SLOW} or * {@link K9#NOTIFICATION_LED_BLINK_FAST}. * @param ringAndVibrate * {@code true}, if ringtone/vibration are allowed. {@code false}, otherwise. */ private void configureNotification(NotificationCompat.Builder builder, String ringtone, long[] vibrationPattern, Integer ledColor, int ledSpeed, boolean ringAndVibrate) { // if it's quiet time, then we shouldn't be ringing, buzzing or flashing if (K9.isQuietTime()) { return; } if (ringAndVibrate) { if (ringtone != null && !TextUtils.isEmpty(ringtone)) { builder.setSound(Uri.parse(ringtone)); } if (vibrationPattern != null) { builder.setVibrate(vibrationPattern); } } if (ledColor != null) { int ledOnMS; int ledOffMS; if (ledSpeed == K9.NOTIFICATION_LED_BLINK_SLOW) { ledOnMS = K9.NOTIFICATION_LED_ON_TIME; ledOffMS = K9.NOTIFICATION_LED_OFF_TIME; } else { ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME; ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME; } builder.setLights(ledColor, ledOnMS, ledOffMS); } } /** Cancel a notification of new email messages */ public void notifyAccountCancel(Context context, Account account) { NotificationManager notifMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); notifMgr.cancel(account.getAccountNumber()); notifMgr.cancel(-1000 - account.getAccountNumber()); notificationData.remove(account.getAccountNumber()); } /** * Save a draft message. * @param account Account we are saving for. * @param message Message to save. * @return Message representing the entry in the local store. */ public Message saveDraft(final Account account, final Message message, long existingDraftId) { Message localMessage = null; try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(account.getDraftsFolderName()); localFolder.open(OpenMode.READ_WRITE); if (existingDraftId != INVALID_MESSAGE_ID) { String uid = localFolder.getMessageUidById(existingDraftId); message.setUid(uid); } // Save the message to the store. localFolder.appendMessages(new Message[] { message }); // Fetch the message back from the store. This is the Message that's returned to the caller. localMessage = localFolder.getMessage(message.getUid()); localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; command.arguments = new String[] { localFolder.getName(), localMessage.getUid() }; queuePendingCommand(account, command); processPendingCommands(account); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to save message as draft.", e); addErrorMessage(account, null, e); } return localMessage; } public long getId(Message message) { long id; if (message instanceof LocalMessage) { id = ((LocalMessage) message).getId(); } else { Log.w(K9.LOG_TAG, "MessagingController.getId() called without a LocalMessage"); id = INVALID_MESSAGE_ID; } return id; } public boolean modeMismatch(Account.FolderMode aMode, Folder.FolderClass fMode) { if (aMode == Account.FolderMode.NONE || (aMode == Account.FolderMode.FIRST_CLASS && fMode != Folder.FolderClass.FIRST_CLASS) || (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS && fMode != Folder.FolderClass.FIRST_CLASS && fMode != Folder.FolderClass.SECOND_CLASS) || (aMode == Account.FolderMode.NOT_SECOND_CLASS && fMode == Folder.FolderClass.SECOND_CLASS)) { return true; } else { return false; } } static AtomicInteger sequencing = new AtomicInteger(0); static class Command implements Comparable<Command> { public Runnable runnable; public MessagingListener listener; public String description; boolean isForeground; int sequence = sequencing.getAndIncrement(); @Override public int compareTo(Command other) { if (other.isForeground && !isForeground) { return 1; } else if (!other.isForeground && isForeground) { return -1; } else { return (sequence - other.sequence); } } } public MessagingListener getCheckMailListener() { return checkMailListener; } public void setCheckMailListener(MessagingListener checkMailListener) { if (this.checkMailListener != null) { removeListener(this.checkMailListener); } this.checkMailListener = checkMailListener; if (this.checkMailListener != null) { addListener(this.checkMailListener); } } public Collection<Pusher> getPushers() { return pushers.values(); } public boolean setupPushing(final Account account) { try { Pusher previousPusher = pushers.remove(account); if (previousPusher != null) { previousPusher.stop(); } Preferences prefs = Preferences.getPreferences(mApplication); Account.FolderMode aDisplayMode = account.getFolderDisplayMode(); Account.FolderMode aPushMode = account.getFolderPushMode(); List<String> names = new ArrayList<String>(); Store localStore = account.getLocalStore(); for (final Folder folder : localStore.getPersonalNamespaces(false)) { if (folder.getName().equals(account.getErrorFolderName()) || folder.getName().equals(account.getOutboxFolderName())) { /* if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() + " which should never be pushed"); */ continue; } folder.open(Folder.OpenMode.READ_WRITE); folder.refresh(prefs); Folder.FolderClass fDisplayClass = folder.getDisplayClass(); Folder.FolderClass fPushClass = folder.getPushClass(); if (modeMismatch(aDisplayMode, fDisplayClass)) { // Never push a folder that isn't displayed /* if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() + " which is in display class " + fDisplayClass + " while account is in display mode " + aDisplayMode); */ continue; } if (modeMismatch(aPushMode, fPushClass)) { // Do not push folders in the wrong class /* if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() + " which is in push mode " + fPushClass + " while account is in push mode " + aPushMode); */ continue; } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Starting pusher for " + account.getDescription() + ":" + folder.getName()); names.add(folder.getName()); } if (!names.isEmpty()) { PushReceiver receiver = new MessagingControllerPushReceiver(mApplication, account, this); int maxPushFolders = account.getMaxPushFolders(); if (names.size() > maxPushFolders) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Count of folders to push for account " + account.getDescription() + " is " + names.size() + ", greater than limit of " + maxPushFolders + ", truncating"); names = names.subList(0, maxPushFolders); } try { Store store = account.getRemoteStore(); if (!store.isPushCapable()) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Account " + account.getDescription() + " is not push capable, skipping"); return false; } Pusher pusher = store.getPusher(receiver); if (pusher != null) { Pusher oldPusher = pushers.putIfAbsent(account, pusher); if (oldPusher == null) { pusher.start(names); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not get remote store", e); return false; } return true; } else { if (K9.DEBUG) Log.i(K9.LOG_TAG, "No folders are configured for pushing in account " + account.getDescription()); return false; } } catch (Exception e) { Log.e(K9.LOG_TAG, "Got exception while setting up pushing", e); } return false; } public void stopAllPushing() { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Stopping all pushers"); Iterator<Pusher> iter = pushers.values().iterator(); while (iter.hasNext()) { Pusher pusher = iter.next(); iter.remove(); pusher.stop(); } } public void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages, final boolean flagSyncOnly) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Got new pushed email messages for account " + account.getDescription() + ", folder " + remoteFolder.getName()); final CountDownLatch latch = new CountDownLatch(1); putBackground("Push messageArrived of account " + account.getDescription() + ", folder " + remoteFolder.getName(), null, new Runnable() { @Override public void run() { LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(remoteFolder.getName()); localFolder.open(OpenMode.READ_WRITE); account.setRingNotified(false); int newCount = downloadMessages(account, remoteFolder, localFolder, messages, flagSyncOnly); int unreadMessageCount = localFolder.getUnreadMessageCount(); localFolder.setLastPush(System.currentTimeMillis()); localFolder.setStatus(null); if (K9.DEBUG) Log.i(K9.LOG_TAG, "messagesArrived newCount = " + newCount + ", unread count = " + unreadMessageCount); if (unreadMessageCount == 0) { notifyAccountCancel(mApplication, account); } for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, remoteFolder.getName(), unreadMessageCount); } } catch (Exception e) { String rootMessage = getRootCauseMessage(e); String errorMessage = "Push failed: " + rootMessage; try { // Oddly enough, using a local variable gets rid of a // potential null pointer access warning with Eclipse. LocalFolder folder = localFolder; folder.setStatus(errorMessage); } catch (Exception se) { Log.e(K9.LOG_TAG, "Unable to set failed status on localFolder", se); } for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed(account, remoteFolder.getName(), errorMessage); } addErrorMessage(account, null, e); } finally { closeFolder(localFolder); latch.countDown(); } } }); try { latch.await(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Interrupted while awaiting latch release", e); } if (K9.DEBUG) Log.i(K9.LOG_TAG, "MessagingController.messagesArrivedLatch released"); } public void systemStatusChanged() { for (MessagingListener l : getListeners()) { l.systemStatusChanged(); } } enum MemorizingState { STARTED, FINISHED, FAILED } static class Memory { Account account; String folderName; MemorizingState syncingState = null; MemorizingState sendingState = null; MemorizingState pushingState = null; MemorizingState processingState = null; String failureMessage = null; int syncingTotalMessagesInMailbox; int syncingNumNewMessages; int folderCompleted = 0; int folderTotal = 0; String processingCommandTitle = null; Memory(Account nAccount, String nFolderName) { account = nAccount; folderName = nFolderName; } String getKey() { return getMemoryKey(account, folderName); } } static String getMemoryKey(Account taccount, String tfolderName) { return taccount.getDescription() + ":" + tfolderName; } static class MemorizingListener extends MessagingListener { HashMap<String, Memory> memories = new HashMap<String, Memory>(31); Memory getMemory(Account account, String folderName) { Memory memory = memories.get(getMemoryKey(account, folderName)); if (memory == null) { memory = new Memory(account, folderName); memories.put(memory.getKey(), memory); } return memory; } @Override public synchronized void synchronizeMailboxStarted(Account account, String folder) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.STARTED; memory.folderCompleted = 0; memory.folderTotal = 0; } @Override public synchronized void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.FINISHED; memory.syncingTotalMessagesInMailbox = totalMessagesInMailbox; memory.syncingNumNewMessages = numNewMessages; } @Override public synchronized void synchronizeMailboxFailed(Account account, String folder, String message) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.FAILED; memory.failureMessage = message; } synchronized void refreshOther(MessagingListener other) { if (other != null) { Memory syncStarted = null; Memory sendStarted = null; Memory processingStarted = null; for (Memory memory : memories.values()) { if (memory.syncingState != null) { switch (memory.syncingState) { case STARTED: syncStarted = memory; break; case FINISHED: other.synchronizeMailboxFinished(memory.account, memory.folderName, memory.syncingTotalMessagesInMailbox, memory.syncingNumNewMessages); break; case FAILED: other.synchronizeMailboxFailed(memory.account, memory.folderName, memory.failureMessage); break; } } if (memory.sendingState != null) { switch (memory.sendingState) { case STARTED: sendStarted = memory; break; case FINISHED: other.sendPendingMessagesCompleted(memory.account); break; case FAILED: other.sendPendingMessagesFailed(memory.account); break; } } if (memory.pushingState != null) { switch (memory.pushingState) { case STARTED: other.setPushActive(memory.account, memory.folderName, true); break; case FINISHED: other.setPushActive(memory.account, memory.folderName, false); break; case FAILED: break; } } if (memory.processingState != null) { switch (memory.processingState) { case STARTED: processingStarted = memory; break; case FINISHED: case FAILED: other.pendingCommandsFinished(memory.account); break; } } } Memory somethingStarted = null; if (syncStarted != null) { other.synchronizeMailboxStarted(syncStarted.account, syncStarted.folderName); somethingStarted = syncStarted; } if (sendStarted != null) { other.sendPendingMessagesStarted(sendStarted.account); somethingStarted = sendStarted; } if (processingStarted != null) { other.pendingCommandsProcessing(processingStarted.account); if (processingStarted.processingCommandTitle != null) { other.pendingCommandStarted(processingStarted.account, processingStarted.processingCommandTitle); } else { other.pendingCommandCompleted(processingStarted.account, processingStarted.processingCommandTitle); } somethingStarted = processingStarted; } if (somethingStarted != null && somethingStarted.folderTotal > 0) { other.synchronizeMailboxProgress(somethingStarted.account, somethingStarted.folderName, somethingStarted.folderCompleted, somethingStarted.folderTotal); } } } @Override public synchronized void setPushActive(Account account, String folderName, boolean active) { Memory memory = getMemory(account, folderName); memory.pushingState = (active ? MemorizingState.STARTED : MemorizingState.FINISHED); } @Override public synchronized void sendPendingMessagesStarted(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.STARTED; memory.folderCompleted = 0; memory.folderTotal = 0; } @Override public synchronized void sendPendingMessagesCompleted(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.FINISHED; } @Override public synchronized void sendPendingMessagesFailed(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.FAILED; } @Override public synchronized void synchronizeMailboxProgress(Account account, String folderName, int completed, int total) { Memory memory = getMemory(account, folderName); memory.folderCompleted = completed; memory.folderTotal = total; } @Override public synchronized void pendingCommandsProcessing(Account account) { Memory memory = getMemory(account, null); memory.processingState = MemorizingState.STARTED; memory.folderCompleted = 0; memory.folderTotal = 0; } @Override public synchronized void pendingCommandsFinished(Account account) { Memory memory = getMemory(account, null); memory.processingState = MemorizingState.FINISHED; } @Override public synchronized void pendingCommandStarted(Account account, String commandTitle) { Memory memory = getMemory(account, null); memory.processingCommandTitle = commandTitle; } @Override public synchronized void pendingCommandCompleted(Account account, String commandTitle) { Memory memory = getMemory(account, null); memory.processingCommandTitle = null; } } private void actOnMessages(List<Message> messages, MessageActor actor) { Map<Account, Map<Folder, List<Message>>> accountMap = new HashMap<Account, Map<Folder, List<Message>>>(); for (Message message : messages) { Folder folder = message.getFolder(); Account account = folder.getAccount(); Map<Folder, List<Message>> folderMap = accountMap.get(account); if (folderMap == null) { folderMap = new HashMap<Folder, List<Message>>(); accountMap.put(account, folderMap); } List<Message> messageList = folderMap.get(folder); if (messageList == null) { messageList = new LinkedList<Message>(); folderMap.put(folder, messageList); } messageList.add(message); } for (Map.Entry<Account, Map<Folder, List<Message>>> entry : accountMap.entrySet()) { Account account = entry.getKey(); //account.refresh(Preferences.getPreferences(K9.app)); Map<Folder, List<Message>> folderMap = entry.getValue(); for (Map.Entry<Folder, List<Message>> folderEntry : folderMap.entrySet()) { Folder folder = folderEntry.getKey(); List<Message> messageList = folderEntry.getValue(); actor.act(account, folder, messageList); } } } interface MessageActor { public void act(final Account account, final Folder folder, final List<Message> messages); } }
Fix "Empty trash" functionality for POP3 accounts Previously messages in the local Trash folder were marked as deleted, then deleted from the server. During the next sync the placeholders for deleted messages are removed from the database. Obviously this doesn't work for POP3 accounts because the Trash folder can't be synchronized with the server. So, for POP3, we now immediately clear out all messages in that folder.
src/com/fsck/k9/controller/MessagingController.java
Fix "Empty trash" functionality for POP3 accounts
Java
apache-2.0
8efe1af92b5b6a34d0446a705fa624fe939555c6
0
cs1331/checkstyle,universsky/checkstyle,jasonchaffee/checkstyle,jochenvdv/checkstyle,attatrol/checkstyle,nikhilgupta23/checkstyle,liscju/checkstyle,sirdis/checkstyle,MEZk/checkstyle,FeodorFitsner/checkstyle,jonmbake/checkstyle,checkstyle/checkstyle,philwebb/checkstyle,sharang108/checkstyle,another-dave/checkstyle,universsky/checkstyle,autermann/checkstyle,vboerchers/checkstyle,rnveach/checkstyle,rnveach/checkstyle,WilliamRen/checkstyle,zofuthan/checkstyle-1,sabaka/checkstyle,FeodorFitsner/checkstyle,rnveach/checkstyle,mkordas/checkstyle,WonderCsabo/checkstyle,rnveach/checkstyle,philwebb/checkstyle,sirdis/checkstyle,jochenvdv/checkstyle,jasonchaffee/checkstyle,AkshitaKukreja30/checkstyle,checkstyle/checkstyle,jochenvdv/checkstyle,ilanKeshet/checkstyle,bansalayush/checkstyle,ilanKeshet/checkstyle,StetsiukRoman/checkstyle,checkstyle/checkstyle,attatrol/checkstyle,beckerhd/checkstyle,ivanov-alex/checkstyle,designreuse/checkstyle,HubSpot/checkstyle,bansalayush/checkstyle,baratali/checkstyle,philwebb/checkstyle,rmswimkktt/checkstyle,FeodorFitsner/checkstyle,mkordas/checkstyle,designreuse/checkstyle,romani/checkstyle,izishared/checkstyle,rmswimkktt/checkstyle,WonderCsabo/checkstyle,baratali/checkstyle,bansalayush/checkstyle,autermann/checkstyle,cs1331/checkstyle,zofuthan/checkstyle-1,vboerchers/checkstyle,ivanov-alex/checkstyle,sabaka/checkstyle,gallandarakhneorg/checkstyle,beckerhd/checkstyle,Bhavik3/checkstyle,nikhilgupta23/checkstyle,rnveach/checkstyle,romani/checkstyle,gallandarakhneorg/checkstyle,baratali/checkstyle,checkstyle/checkstyle,rnveach/checkstyle,designreuse/checkstyle,StetsiukRoman/checkstyle,romani/checkstyle,izishared/checkstyle,jonmbake/checkstyle,checkstyle/checkstyle,pietern/checkstyle,AkshitaKukreja30/checkstyle,ivanov-alex/checkstyle,zofuthan/checkstyle-1,naver/checkstyle,attatrol/checkstyle,pietern/checkstyle,pietern/checkstyle,liscju/checkstyle,romani/checkstyle,WonderCsabo/checkstyle,ilanKeshet/checkstyle,another-dave/checkstyle,MEZk/checkstyle,llocc/checkstyle,cs1331/checkstyle,vboerchers/checkstyle,StetsiukRoman/checkstyle,jasonchaffee/checkstyle,mkordas/checkstyle,Bhavik3/checkstyle,beckerhd/checkstyle,gallandarakhneorg/checkstyle,naver/checkstyle,sirdis/checkstyle,llocc/checkstyle,sabaka/checkstyle,romani/checkstyle,nikhilgupta23/checkstyle,romani/checkstyle,jonmbake/checkstyle,Bhavik3/checkstyle,sharang108/checkstyle,HubSpot/checkstyle,checkstyle/checkstyle,WilliamRen/checkstyle,naver/checkstyle,izishared/checkstyle,AkshitaKukreja30/checkstyle,sharang108/checkstyle,llocc/checkstyle,rmswimkktt/checkstyle,Godin/checkstyle,Godin/checkstyle,Godin/checkstyle,universsky/checkstyle,WilliamRen/checkstyle,another-dave/checkstyle,HubSpot/checkstyle,autermann/checkstyle,MEZk/checkstyle,liscju/checkstyle
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2015 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import java.lang.reflect.Field; import java.util.ResourceBundle; import com.google.common.collect.ImmutableMap; import com.puppycrawl.tools.checkstyle.grammars.GeneratedJavaTokenTypes; /** * Contains the constants for all the tokens contained in the Abstract * Syntax Tree. * * <p>Implementation detail: This class has been introduced to break * the circular dependency between packages.</p> * * @author Oliver Burn * @author <a href="mailto:[email protected]">Peter Dobratz</a> */ public final class TokenTypes { /** prevent instantiation */ private TokenTypes() { } // The following three types are never part of an AST, // left here as a reminder so nobody will read them accidentally /* * token representing a NULL_TREE_LOOKAHEAD */ // public static final int NULL_TREE_LOOKAHEAD = 3; /* * token representing a BLOCK */ // public static final int BLOCK = 4; /* * token representing a VOCAB */ // public static final int VOCAB = 149; // These are the types that can actually occur in an AST // it makes sense to register Checks for these types /** * The end of file token. This is the root node for the source * file. It's children are an optional package definition, zero * or more import statements, and one or more class or interface * definitions. * * @see #PACKAGE_DEF * @see #IMPORT * @see #CLASS_DEF * @see #INTERFACE_DEF **/ public static final int EOF = GeneratedJavaTokenTypes.EOF; /** * Modifiers for type, method, and field declarations. The * modifiers element is always present even though it may have no * children. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html">Java * Language Specification, &sect;8</a> * @see #LITERAL_PUBLIC * @see #LITERAL_PROTECTED * @see #LITERAL_PRIVATE * @see #ABSTRACT * @see #LITERAL_STATIC * @see #FINAL * @see #LITERAL_TRANSIENT * @see #LITERAL_VOLATILE * @see #LITERAL_SYNCHRONIZED * @see #LITERAL_NATIVE * @see #STRICTFP * @see #ANNOTATION * @see #LITERAL_DEFAULT **/ public static final int MODIFIERS = GeneratedJavaTokenTypes.MODIFIERS; /** * An object block. These are children of class, interface, enum, * annotation and enum constant declarations. * Also, object blocks are children of the new keyword when defining * anonymous inner types. * * @see #LCURLY * @see #INSTANCE_INIT * @see #STATIC_INIT * @see #CLASS_DEF * @see #CTOR_DEF * @see #METHOD_DEF * @see #VARIABLE_DEF * @see #RCURLY * @see #INTERFACE_DEF * @see #LITERAL_NEW * @see #ENUM_DEF * @see #ENUM_CONSTANT_DEF * @see #ANNOTATION_DEF **/ public static final int OBJBLOCK = GeneratedJavaTokenTypes.OBJBLOCK; /** * A list of statements. * * @see #RCURLY * @see #EXPR * @see #LABELED_STAT * @see #LITERAL_THROWS * @see #LITERAL_RETURN * @see #SEMI * @see #METHOD_DEF * @see #CTOR_DEF * @see #LITERAL_FOR * @see #LITERAL_WHILE * @see #LITERAL_IF * @see #LITERAL_ELSE * @see #CASE_GROUP **/ public static final int SLIST = GeneratedJavaTokenTypes.SLIST; /** * A constructor declaration. * * <p>For example:</p> * <pre> * public SpecialEntry(int value, String text) * { * this.value = value; * this.text = text; * } * </pre> * <p>parses as:</p> * <pre> * +--CTOR_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--IDENT (SpecialEntry) * +--LPAREN (() * +--PARAMETERS * | * +--PARAMETER_DEF * | * +--MODIFIERS * +--TYPE * | * +--LITERAL_INT (int) * +--IDENT (value) * +--COMMA (,) * +--PARAMETER_DEF * | * +--MODIFIERS * +--TYPE * | * +--IDENT (String) * +--IDENT (text) * +--RPAREN ()) * +--SLIST ({) * | * +--EXPR * | * +--ASSIGN (=) * | * +--DOT (.) * | * +--LITERAL_THIS (this) * +--IDENT (value) * +--IDENT (value) * +--SEMI (;) * +--EXPR * | * +--ASSIGN (=) * | * +--DOT (.) * | * +--LITERAL_THIS (this) * +--IDENT (text) * +--IDENT (text) * +--SEMI (;) * +--RCURLY (}) * </pre> * * @see #OBJBLOCK * @see #CLASS_DEF **/ public static final int CTOR_DEF = GeneratedJavaTokenTypes.CTOR_DEF; /** * A method declaration. The children are modifiers, type parameters, * return type, method name, parameter list, an optional throws list, and * statement list. The statement list is omitted if the method * declaration appears in an interface declaration. Method * declarations may appear inside object blocks of class * declarations, interface declarations, enum declarations, * enum constant declarations or anonymous inner-class declarations. * * <p>For example:</p> * * <pre> * public static int square(int x) * { * return x*x; * } * </pre> * * <p>parses as:</p> * * <pre> * +--METHOD_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--LITERAL_STATIC (static) * +--TYPE * | * +--LITERAL_INT (int) * +--IDENT (square) * +--PARAMETERS * | * +--PARAMETER_DEF * | * +--MODIFIERS * +--TYPE * | * +--LITERAL_INT (int) * +--IDENT (x) * +--SLIST ({) * | * +--LITERAL_RETURN (return) * | * +--EXPR * | * +--STAR (*) * | * +--IDENT (x) * +--IDENT (x) * +--SEMI (;) * +--RCURLY (}) * </pre> * * @see #MODIFIERS * @see #TYPE_PARAMETERS * @see #TYPE * @see #IDENT * @see #PARAMETERS * @see #LITERAL_THROWS * @see #SLIST * @see #OBJBLOCK **/ public static final int METHOD_DEF = GeneratedJavaTokenTypes.METHOD_DEF; /** * A field or local variable declaration. The children are * modifiers, type, the identifier name, and an optional * assignment statement. * * @see #MODIFIERS * @see #TYPE * @see #IDENT * @see #ASSIGN **/ public static final int VARIABLE_DEF = GeneratedJavaTokenTypes.VARIABLE_DEF; /** * An instance initializer. Zero or more instance initializers * may appear in class and enum definitions. This token will be a child * of the object block of the declaring type. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.6">Java * Language Specification&sect;8.6</a> * @see #SLIST * @see #OBJBLOCK **/ public static final int INSTANCE_INIT = GeneratedJavaTokenTypes.INSTANCE_INIT; /** * A static initialization block. Zero or more static * initializers may be children of the object block of a class * or enum declaration (interfaces cannot have static initializers). The * first and only child is a statement list. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.7">Java * Language Specification, &sect;8.7</a> * @see #SLIST * @see #OBJBLOCK **/ public static final int STATIC_INIT = GeneratedJavaTokenTypes.STATIC_INIT; /** * A type. This is either a return type of a method or a type of * a variable or field. The first child of this element is the * actual type. This may be a primitive type, an identifier, a * dot which is the root of a fully qualified type, or an array of * any of these. The second child may be type arguments to the type. * * @see #VARIABLE_DEF * @see #METHOD_DEF * @see #PARAMETER_DEF * @see #IDENT * @see #DOT * @see #LITERAL_VOID * @see #LITERAL_BOOLEAN * @see #LITERAL_BYTE * @see #LITERAL_CHAR * @see #LITERAL_SHORT * @see #LITERAL_INT * @see #LITERAL_FLOAT * @see #LITERAL_LONG * @see #LITERAL_DOUBLE * @see #ARRAY_DECLARATOR * @see #TYPE_ARGUMENTS **/ public static final int TYPE = GeneratedJavaTokenTypes.TYPE; /** * A class declaration. * * <p>For example:</p> * <pre> * public class MyClass * implements Serializable * { * } * </pre> * <p>parses as:</p> * <pre> * +--CLASS_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--LITERAL_CLASS (class) * +--IDENT (MyClass) * +--EXTENDS_CLAUSE * +--IMPLEMENTS_CLAUSE * | * +--IDENT (Serializable) * +--OBJBLOCK * | * +--LCURLY ({) * +--RCURLY (}) * </pre> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html">Java * Language Specification, &sect;8</a> * @see #MODIFIERS * @see #IDENT * @see #EXTENDS_CLAUSE * @see #IMPLEMENTS_CLAUSE * @see #OBJBLOCK * @see #LITERAL_NEW **/ public static final int CLASS_DEF = GeneratedJavaTokenTypes.CLASS_DEF; /** * An interface declaration. * * <p>For example:</p> * * <pre> * public interface MyInterface * { * } * * </pre> * * <p>parses as:</p> * * <pre> * +--INTERFACE_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--LITERAL_INTERFACE (interface) * +--IDENT (MyInterface) * +--EXTENDS_CLAUSE * +--OBJBLOCK * | * +--LCURLY ({) * +--RCURLY (}) * </pre> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html">Java * Language Specification, &sect;9</a> * @see #MODIFIERS * @see #IDENT * @see #EXTENDS_CLAUSE * @see #OBJBLOCK **/ public static final int INTERFACE_DEF = GeneratedJavaTokenTypes.INTERFACE_DEF; /** * The package declaration. This is optional, but if it is * included, then there is only one package declaration per source * file and it must be the first non-comment in the file. A package * declaration may be annotated in which case the annotations comes * before the rest of the declaration (and are the first children). * * <p>For example:</p> * * <pre> * package com.puppycrawl.tools.checkstyle.api; * </pre> * * <p>parses as:</p> * * <pre> * +--PACKAGE_DEF (package) * | * +--ANNOTATIONS * +--DOT (.) * | * +--DOT (.) * | * +--DOT (.) * | * +--DOT (.) * | * +--IDENT (com) * +--IDENT (puppycrawl) * +--IDENT (tools) * +--IDENT (checkstyle) * +--IDENT (api) * +--SEMI (;) * </pre> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.4">Java * Language Specification &sect;7.4</a> * @see #DOT * @see #IDENT * @see #SEMI * @see #ANNOTATIONS * @see FullIdent **/ public static final int PACKAGE_DEF = GeneratedJavaTokenTypes.PACKAGE_DEF; /** * An array declaration. * * <p>If the array declaration represents a type, then the type of * the array elements is the first child. Multidimensional arrays * may be regarded as arrays of arrays. In other words, the first * child of the array declaration is another array * declaration.</p> * * <p>For example:</p> * <pre> * int[] x; * </pre> * <p>parses as:</p> * <pre> * +--VARIABLE_DEF * | * +--MODIFIERS * +--TYPE * | * +--ARRAY_DECLARATOR ([) * | * +--LITERAL_INT (int) * +--IDENT (x) * +--SEMI (;) * </pre> * * <p>The array declaration may also represent an inline array * definition. In this case, the first child will be either an * expression specifying the length of the array or an array * initialization block.</p> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html">Java * Language Specification &sect;10</a> * @see #TYPE * @see #ARRAY_INIT **/ public static final int ARRAY_DECLARATOR = GeneratedJavaTokenTypes.ARRAY_DECLARATOR; /** * An extends clause. This appear as part of class and interface * definitions. This element appears even if the * <code>extends</code> keyword is not explicitly used. The child * is an optional identifier. * * <p>For example:</p> * * * <p>parses as:</p> * <pre> * +--EXTENDS_CLAUSE * | * +--DOT (.) * | * +--DOT (.) * | * +--IDENT (java) * +--IDENT (util) * +--IDENT (LinkedList) * </pre> * * @see #IDENT * @see #DOT * @see #CLASS_DEF * @see #INTERFACE_DEF * @see FullIdent **/ public static final int EXTENDS_CLAUSE = GeneratedJavaTokenTypes.EXTENDS_CLAUSE; /** * An implements clause. This always appears in a class or enum * declaration, even if there are no implemented interfaces. The * children are a comma separated list of zero or more * identifiers. * * <p>For example:</p> * <pre> * implements Serializable, Comparable * </pre> * <p>parses as:</p> * <pre> * +--IMPLEMENTS_CLAUSE * | * +--IDENT (Serializable) * +--COMMA (,) * +--IDENT (Comparable) * </pre> * * @see #IDENT * @see #DOT * @see #COMMA * @see #CLASS_DEF * @see #ENUM_DEF **/ public static final int IMPLEMENTS_CLAUSE = GeneratedJavaTokenTypes.IMPLEMENTS_CLAUSE; /** * A list of parameters to a method or constructor. The children * are zero or more parameter declarations separated by commas. * * <p>For example</p> * <pre> * int start, int end * </pre> * <p>parses as:</p> * <pre> * +--PARAMETERS * | * +--PARAMETER_DEF * | * +--MODIFIERS * +--TYPE * | * +--LITERAL_INT (int) * +--IDENT (start) * +--COMMA (,) * +--PARAMETER_DEF * | * +--MODIFIERS * +--TYPE * | * +--LITERAL_INT (int) * +--IDENT (end) * </pre> * * @see #PARAMETER_DEF * @see #COMMA * @see #METHOD_DEF * @see #CTOR_DEF **/ public static final int PARAMETERS = GeneratedJavaTokenTypes.PARAMETERS; /** * A parameter declaration. The last parameter in a list of parameters may * be variable length (indicated by the ELLIPSIS child node immediately * after the TYPE child). * * @see #MODIFIERS * @see #TYPE * @see #IDENT * @see #PARAMETERS * @see #ELLIPSIS **/ public static final int PARAMETER_DEF = GeneratedJavaTokenTypes.PARAMETER_DEF; /** * A labeled statement. * * <p>For example:</p> * <pre> * outside: ; * </pre> * <p>parses as:</p> * <pre> * +--LABELED_STAT (:) * | * +--IDENT (outside) * +--EMPTY_STAT (;) * </pre> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.7">Java * Language Specification, &sect;14.7</a> * @see #SLIST **/ public static final int LABELED_STAT = GeneratedJavaTokenTypes.LABELED_STAT; /** * A type-cast. * * <p>For example:</p> * <pre> * (String)it.next() * </pre> * <p>parses as:</p> * <pre> * +--TYPECAST (() * | * +--TYPE * | * +--IDENT (String) * +--RPAREN ()) * +--METHOD_CALL (() * | * +--DOT (.) * | * +--IDENT (it) * +--IDENT (next) * +--ELIST * +--RPAREN ()) * </pre> * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.16">Java * Language Specification, &sect;15.16</a> * @see #EXPR * @see #TYPE * @see #TYPE_ARGUMENTS * @see #RPAREN **/ public static final int TYPECAST = GeneratedJavaTokenTypes.TYPECAST; /** * The array index operator. * * <p>For example:</p> * <pre> * ar[2] = 5; * </pre> * <p>parses as:</p> * <pre> * +--EXPR * | * +--ASSIGN (=) * | * +--INDEX_OP ([) * | * +--IDENT (ar) * +--EXPR * | * +--NUM_INT (2) * +--NUM_INT (5) * +--SEMI (;) * </pre> * * @see #EXPR **/ public static final int INDEX_OP = GeneratedJavaTokenTypes.INDEX_OP; /** * The <code>++</code> (postfix increment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.14.1">Java * Language Specification, &sect;15.14.1</a> * @see #EXPR * @see #INC **/ public static final int POST_INC = GeneratedJavaTokenTypes.POST_INC; /** * The <code>--</code> (postfix decrement) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.14.2">Java * Language Specification, &sect;15.14.2</a> * @see #EXPR * @see #DEC **/ public static final int POST_DEC = GeneratedJavaTokenTypes.POST_DEC; /** * A method call. A method call may have type arguments however these * are attached to the appropriate node in the qualified method name. * * <p>For example:</p> * <pre> * Math.random() * </pre> * <p>parses as: * <pre> * +--METHOD_CALL (() * | * +--DOT (.) * | * +--IDENT (Math) * +--IDENT (random) * +--ELIST * +--RPAREN ()) * </pre> * * * @see #IDENT * @see #TYPE_ARGUMENTS * @see #DOT * @see #ELIST * @see #RPAREN * @see FullIdent **/ public static final int METHOD_CALL = GeneratedJavaTokenTypes.METHOD_CALL; /** * Part of Java 8 syntax. Method or constructor call without arguments. * @see #DOUBLE_COLON */ public static final int METHOD_REF = GeneratedJavaTokenTypes.METHOD_REF; /** * An expression. Operators with lower precedence appear at a * higher level in the tree than operators with higher precedence. * Parentheses are siblings to the operator they enclose. * * <p>For example:</p> * <pre> * x = 4 + 3 * 5 + (30 + 26) / 4 + 5 % 4 + (1&lt;&lt;3); * </pre> * <p>parses as:</p> * <pre> * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (x) * +--PLUS (+) * | * +--PLUS (+) * | * +--PLUS (+) * | * +--PLUS (+) * | * +--NUM_INT (4) * +--STAR (*) * | * +--NUM_INT (3) * +--NUM_INT (5) * +--DIV (/) * | * +--LPAREN (() * +--PLUS (+) * | * +--NUM_INT (30) * +--NUM_INT (26) * +--RPAREN ()) * +--NUM_INT (4) * +--MOD (%) * | * +--NUM_INT (5) * +--NUM_INT (4) * +--LPAREN (() * +--SL (&lt;&lt;) * | * +--NUM_INT (1) * +--NUM_INT (3) * +--RPAREN ()) * +--SEMI (;) * </pre> * * @see #ELIST * @see #ASSIGN * @see #LPAREN * @see #RPAREN **/ public static final int EXPR = GeneratedJavaTokenTypes.EXPR; /** * An array initialization. This may occur as part of an array * declaration or inline with <code>new</code>. * * <p>For example:</p> * <pre> * int[] y = * { * 1, * 2, * }; * </pre> * <p>parses as:</p> * <pre> * +--VARIABLE_DEF * | * +--MODIFIERS * +--TYPE * | * +--ARRAY_DECLARATOR ([) * | * +--LITERAL_INT (int) * +--IDENT (y) * +--ASSIGN (=) * | * +--ARRAY_INIT ({) * | * +--EXPR * | * +--NUM_INT (1) * +--COMMA (,) * +--EXPR * | * +--NUM_INT (2) * +--COMMA (,) * +--RCURLY (}) * +--SEMI (;) * </pre> * * <p>Also consider:</p> * <pre> * int[] z = new int[] * { * 1, * 2, * }; * </pre> * <p>which parses as:</p> * <pre> * +--VARIABLE_DEF * | * +--MODIFIERS * +--TYPE * | * +--ARRAY_DECLARATOR ([) * | * +--LITERAL_INT (int) * +--IDENT (z) * +--ASSIGN (=) * | * +--EXPR * | * +--LITERAL_NEW (new) * | * +--LITERAL_INT (int) * +--ARRAY_DECLARATOR ([) * +--ARRAY_INIT ({) * | * +--EXPR * | * +--NUM_INT (1) * +--COMMA (,) * +--EXPR * | * +--NUM_INT (2) * +--COMMA (,) * +--RCURLY (}) * </pre> * * @see #ARRAY_DECLARATOR * @see #TYPE * @see #LITERAL_NEW * @see #COMMA **/ public static final int ARRAY_INIT = GeneratedJavaTokenTypes.ARRAY_INIT; /** * An import declaration. Import declarations are option, but * must appear after the package declaration and before the first type * declaration. * * <p>For example:</p> * * <pre> * import java.io.IOException; * </pre> * * <p>parses as:</p> * * <pre> * +--IMPORT (import) * | * +--DOT (.) * | * +--DOT (.) * | * +--IDENT (java) * +--IDENT (io) * +--IDENT (IOException) * +--SEMI (;) * </pre> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.5">Java * Language Specification &sect;7.5</a> * @see #DOT * @see #IDENT * @see #STAR * @see #SEMI * @see FullIdent **/ public static final int IMPORT = GeneratedJavaTokenTypes.IMPORT; /** * The <code>-</code> (unary minus) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.4">Java * Language Specification, &sect;15.15.4</a> * @see #EXPR **/ public static final int UNARY_MINUS = GeneratedJavaTokenTypes.UNARY_MINUS; /** * The <code>+</code> (unary plus) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.3">Java * Language Specification, &sect;15.15.3</a> * @see #EXPR **/ public static final int UNARY_PLUS = GeneratedJavaTokenTypes.UNARY_PLUS; /** * A group of case clauses. Case clauses with no associated * statements are grouped together into a case group. The last * child is a statement list containing the statements to execute * upon a match. * * <p>For example:</p> * <pre> * case 0: * case 1: * case 2: * x = 3; * break; * </pre> * <p>parses as:</p> * <pre> * +--CASE_GROUP * | * +--LITERAL_CASE (case) * | * +--EXPR * | * +--NUM_INT (0) * +--LITERAL_CASE (case) * | * +--EXPR * | * +--NUM_INT (1) * +--LITERAL_CASE (case) * | * +--EXPR * | * +--NUM_INT (2) * +--SLIST * | * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (x) * +--NUM_INT (3) * +--SEMI (;) * +--LITERAL_BREAK (break) * | * +--SEMI (;) * </pre> * * @see #LITERAL_CASE * @see #LITERAL_DEFAULT * @see #LITERAL_SWITCH **/ public static final int CASE_GROUP = GeneratedJavaTokenTypes.CASE_GROUP; /** * An expression list. The children are a comma separated list of * expressions. * * @see #LITERAL_NEW * @see #FOR_INIT * @see #FOR_ITERATOR * @see #EXPR * @see #METHOD_CALL * @see #CTOR_CALL * @see #SUPER_CTOR_CALL **/ public static final int ELIST = GeneratedJavaTokenTypes.ELIST; /** * A for loop initializer. This is a child of * <code>LITERAL_FOR</code>. The children of this element may be * a comma separated list of variable declarations, an expression * list, or empty. * * @see #VARIABLE_DEF * @see #ELIST * @see #LITERAL_FOR **/ public static final int FOR_INIT = GeneratedJavaTokenTypes.FOR_INIT; /** * A for loop condition. This is a child of * <code>LITERAL_FOR</code>. The child of this element is an * optional expression. * * @see #EXPR * @see #LITERAL_FOR **/ public static final int FOR_CONDITION = GeneratedJavaTokenTypes.FOR_CONDITION; /** * A for loop iterator. This is a child of * <code>LITERAL_FOR</code>. The child of this element is an * optional expression list. * * @see #ELIST * @see #LITERAL_FOR **/ public static final int FOR_ITERATOR = GeneratedJavaTokenTypes.FOR_ITERATOR; /** * The empty statement. This goes in place of an * <code>SLIST</code> for a <code>for</code> or <code>while</code> * loop body. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.6">Java * Language Specification, &sect;14.6</a> * @see #LITERAL_FOR * @see #LITERAL_WHILE **/ public static final int EMPTY_STAT = GeneratedJavaTokenTypes.EMPTY_STAT; /** * The <code>final</code> keyword. * * @see #MODIFIERS **/ public static final int FINAL = GeneratedJavaTokenTypes.FINAL; /** * The <code>abstract</code> keyword. * * @see #MODIFIERS **/ public static final int ABSTRACT = GeneratedJavaTokenTypes.ABSTRACT; /** * The <code>strictfp</code> keyword. * * @see #MODIFIERS **/ public static final int STRICTFP = GeneratedJavaTokenTypes.STRICTFP; /** * A super constructor call. * * @see #ELIST * @see #RPAREN * @see #SEMI * @see #CTOR_CALL **/ public static final int SUPER_CTOR_CALL = GeneratedJavaTokenTypes.SUPER_CTOR_CALL; /** * A constructor call. * * <p>For example:</p> * <pre> * this(1); * </pre> * <p>parses as:</p> * <pre> * +--CTOR_CALL (this) * | * +--LPAREN (() * +--ELIST * | * +--EXPR * | * +--NUM_INT (1) * +--RPAREN ()) * +--SEMI (;) * </pre> * * @see #ELIST * @see #RPAREN * @see #SEMI * @see #SUPER_CTOR_CALL **/ public static final int CTOR_CALL = GeneratedJavaTokenTypes.CTOR_CALL; /* * * This token does not appear in the tree. * * @see #PACKAGE_DEF **/ //public static final int LITERAL_PACKAGE = // GeneratedJavaTokenTypes.LITERAL_package; /** * The statement terminator (<code>;</code>). Depending on the * context, this make occur as a sibling, a child, or not at all. * * @see #PACKAGE_DEF * @see #IMPORT * @see #SLIST * @see #ARRAY_INIT * @see #LITERAL_FOR **/ public static final int SEMI = GeneratedJavaTokenTypes.SEMI; /* * * This token does not appear in the tree. * * @see #IMPORT **/ // public static final int LITERAL_IMPORT = // GeneratedJavaTokenTypes.LITERAL_import; /* * * This token does not appear in the tree. * * @see #INDEX_OP * @see #ARRAY_DECLARATOR **/ //public static final int LBRACK = GeneratedJavaTokenTypes.LBRACK; /** * The <code>]</code> symbol. * * @see #INDEX_OP * @see #ARRAY_DECLARATOR **/ public static final int RBRACK = GeneratedJavaTokenTypes.RBRACK; /** * The <code>void</code> keyword. * * @see #TYPE **/ public static final int LITERAL_VOID = GeneratedJavaTokenTypes.LITERAL_void; /** * The <code>boolean</code> keyword. * * @see #TYPE **/ public static final int LITERAL_BOOLEAN = GeneratedJavaTokenTypes.LITERAL_boolean; /** * The <code>byte</code> keyword. * * @see #TYPE **/ public static final int LITERAL_BYTE = GeneratedJavaTokenTypes.LITERAL_byte; /** * The <code>char</code> keyword. * * @see #TYPE **/ public static final int LITERAL_CHAR = GeneratedJavaTokenTypes.LITERAL_char; /** * The <code>short</code> keyword. * * @see #TYPE **/ public static final int LITERAL_SHORT = GeneratedJavaTokenTypes.LITERAL_short; /** * The <code>int</code> keyword. * * @see #TYPE **/ public static final int LITERAL_INT = GeneratedJavaTokenTypes.LITERAL_int; /** * The <code>float</code> keyword. * * @see #TYPE **/ public static final int LITERAL_FLOAT = GeneratedJavaTokenTypes.LITERAL_float; /** * The <code>long</code> keyword. * * @see #TYPE **/ public static final int LITERAL_LONG = GeneratedJavaTokenTypes.LITERAL_long; /** * The <code>double</code> keyword. * * @see #TYPE **/ public static final int LITERAL_DOUBLE = GeneratedJavaTokenTypes.LITERAL_double; /** * An identifier. These can be names of types, subpackages, * fields, methods, parameters, and local variables. **/ public static final int IDENT = GeneratedJavaTokenTypes.IDENT; /** * The <code>&#46;</code> (dot) operator. * * @see FullIdent **/ public static final int DOT = GeneratedJavaTokenTypes.DOT; /** * The <code>*</code> (multiplication or wildcard) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.5.2">Java * Language Specification, &sect;7.5.2</a> * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.1">Java * Language Specification, &sect;15.17.1</a> * @see #EXPR * @see #IMPORT **/ public static final int STAR = GeneratedJavaTokenTypes.STAR; /** * The <code>private</code> keyword. * * @see #MODIFIERS **/ public static final int LITERAL_PRIVATE = GeneratedJavaTokenTypes.LITERAL_private; /** * The <code>public</code> keyword. * * @see #MODIFIERS **/ public static final int LITERAL_PUBLIC = GeneratedJavaTokenTypes.LITERAL_public; /** * The <code>protected</code> keyword. * * @see #MODIFIERS **/ public static final int LITERAL_PROTECTED = GeneratedJavaTokenTypes.LITERAL_protected; /** * The <code>static</code> keyword. * * @see #MODIFIERS **/ public static final int LITERAL_STATIC = GeneratedJavaTokenTypes.LITERAL_static; /** * The <code>transient</code> keyword. * * @see #MODIFIERS **/ public static final int LITERAL_TRANSIENT = GeneratedJavaTokenTypes.LITERAL_transient; /** * The <code>native</code> keyword. * * @see #MODIFIERS **/ public static final int LITERAL_NATIVE = GeneratedJavaTokenTypes.LITERAL_native; /** * The <code>synchronized</code> keyword. This may be used as a * modifier of a method or in the definition of a synchronized * block. * * <p>For example:</p> * * <pre> * synchronized(this) * { * x++; * } * </pre> * * <p>parses as:</p> * * <pre> * +--LITERAL_SYNCHRONIZED (synchronized) * | * +--LPAREN (() * +--EXPR * | * +--LITERAL_THIS (this) * +--RPAREN ()) * +--SLIST ({) * | * +--EXPR * | * +--POST_INC (++) * | * +--IDENT (x) * +--SEMI (;) * +--RCURLY (}) * +--RCURLY (}) * </pre> * * @see #MODIFIERS * @see #LPAREN * @see #EXPR * @see #RPAREN * @see #SLIST * @see #RCURLY **/ public static final int LITERAL_SYNCHRONIZED = GeneratedJavaTokenTypes.LITERAL_synchronized; /** * The <code>volatile</code> keyword. * * @see #MODIFIERS **/ public static final int LITERAL_VOLATILE = GeneratedJavaTokenTypes.LITERAL_volatile; /** * The <code>class</code> keyword. This element appears both * as part of a class declaration, and inline to reference a * class object. * * <p>For example:</p> * * <pre> * int.class * </pre> * <p>parses as:</p> * <pre> * +--EXPR * | * +--DOT (.) * | * +--LITERAL_INT (int) * +--LITERAL_CLASS (class) * </pre> * * @see #DOT * @see #IDENT * @see #CLASS_DEF * @see FullIdent **/ public static final int LITERAL_CLASS = GeneratedJavaTokenTypes.LITERAL_class; /* * * This token does not appear in the tree. * * @see #EXTENDS_CLAUSE **/ //public static final int LITERAL_EXTENDS = // GeneratedJavaTokenTypes.LITERAL_extends; /** * The <code>interface</code> keyword. This token appears in * interface definition. * * @see #INTERFACE_DEF **/ public static final int LITERAL_INTERFACE = GeneratedJavaTokenTypes.LITERAL_interface; /** * A left (curly) brace (<code>{</code>). * * @see #OBJBLOCK * @see #ARRAY_INIT * @see #SLIST **/ public static final int LCURLY = GeneratedJavaTokenTypes.LCURLY; /** * A right (curly) brace (<code>}</code>). * * @see #OBJBLOCK * @see #ARRAY_INIT * @see #SLIST **/ public static final int RCURLY = GeneratedJavaTokenTypes.RCURLY; /** * The <code>,</code> (comma) operator. * * @see #ARRAY_INIT * @see #FOR_INIT * @see #FOR_ITERATOR * @see #LITERAL_THROWS * @see #IMPLEMENTS_CLAUSE **/ public static final int COMMA = GeneratedJavaTokenTypes.COMMA; /* * * This token does not appear in the tree. * * @see #IMPLEMENTS_CLAUSE **/ // public static final int LITERAL_IMPLEMENTS = // GeneratedJavaTokenTypes.LITERAL_implements; /** * A left parenthesis (<code>(</code>). * * @see #LITERAL_FOR * @see #LITERAL_NEW * @see #EXPR * @see #LITERAL_SWITCH * @see #LITERAL_CATCH **/ public static final int LPAREN = GeneratedJavaTokenTypes.LPAREN; /** * A right parenthesis (<code>)</code>). * * @see #LITERAL_FOR * @see #LITERAL_NEW * @see #METHOD_CALL * @see #TYPECAST * @see #EXPR * @see #LITERAL_SWITCH * @see #LITERAL_CATCH **/ public static final int RPAREN = GeneratedJavaTokenTypes.RPAREN; /** * The <code>this</code> keyword. * * @see #EXPR * @see #CTOR_CALL **/ public static final int LITERAL_THIS = GeneratedJavaTokenTypes.LITERAL_this; /** * The <code>super</code> keyword. * * @see #EXPR * @see #SUPER_CTOR_CALL **/ public static final int LITERAL_SUPER = GeneratedJavaTokenTypes.LITERAL_super; /** * The <code>=</code> (assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.1">Java * Language Specification, &sect;15.26.1</a> * @see #EXPR **/ public static final int ASSIGN = GeneratedJavaTokenTypes.ASSIGN; /** * The <code>throws</code> keyword. The children are a number of * one or more identifiers separated by commas. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.4">Java * Language Specification, &sect;8.4.4</a> * @see #IDENT * @see #DOT * @see #COMMA * @see #METHOD_DEF * @see #CTOR_DEF * @see FullIdent **/ public static final int LITERAL_THROWS = GeneratedJavaTokenTypes.LITERAL_throws; /** * The <code>:</code> (colon) operator. This will appear as part * of the conditional operator (<code>? :</code>). * * @see #QUESTION * @see #LABELED_STAT * @see #CASE_GROUP **/ public static final int COLON = GeneratedJavaTokenTypes.COLON; /** * The <code>::</code> (double colon) operator. * It is part of Java 8 syntax that is used for method reference. * @see #METHOD_REF */ public static final int DOUBLE_COLON = GeneratedJavaTokenTypes.DOUBLE_COLON; /** * The <code>if</code> keyword. * * <p>For example:</p> * <pre> * if(optimistic) * { * message = "half full"; * } * else * { * message = "half empty"; * } * </pre> * <p>parses as:</p> * <pre> * +--LITERAL_IF (if) * | * +--LPAREN (() * +--EXPR * | * +--IDENT (optimistic) * +--RPAREN ()) * +--SLIST ({) * | * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (message) * +--STRING_LITERAL ("half full") * +--SEMI (;) * +--RCURLY (}) * +--LITERAL_ELSE (else) * | * +--SLIST ({) * | * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (message) * +--STRING_LITERAL ("half empty") * +--SEMI (;) * +--RCURLY (}) * </pre> * * @see #LPAREN * @see #EXPR * @see #RPAREN * @see #SLIST * @see #EMPTY_STAT * @see #LITERAL_ELSE **/ public static final int LITERAL_IF = GeneratedJavaTokenTypes.LITERAL_if; /** * The <code>for</code> keyword. The children are <code>(</code>, * an initializer, a condition, an iterator, a <code>)</code> and * either a statement list, a single expression, or an empty * statement. * * <p>For example:</p> * <pre> * for(int i = 0, n = myArray.length; i &lt; n; i++) * { * } * </pre> * * <p>parses as:</p> * <pre> * +--LITERAL_FOR (for) * | * +--LPAREN (() * +--FOR_INIT * | * +--VARIABLE_DEF * | * +--MODIFIERS * +--TYPE * | * +--LITERAL_INT (int) * +--IDENT (i) * +--ASSIGN (=) * | * +--EXPR * | * +--NUM_INT (0) * +--COMMA (,) * +--VARIABLE_DEF * | * +--MODIFIERS * +--TYPE * | * +--LITERAL_INT (int) * +--IDENT (n) * +--ASSIGN (=) * | * +--EXPR * | * +--DOT (.) * | * +--IDENT (myArray) * +--IDENT (length) * +--SEMI (;) * +--FOR_CONDITION * | * +--EXPR * | * +--LT (&lt;) * | * +--IDENT (i) * +--IDENT (n) * +--SEMI (;) * +--FOR_ITERATOR * | * +--ELIST * | * +--EXPR * | * +--POST_INC (++) * | * +--IDENT (i) * +--RPAREN ()) * +--SLIST ({) * | * +--RCURLY (}) * </pre> * * @see #LPAREN * @see #FOR_INIT * @see #SEMI * @see #FOR_CONDITION * @see #FOR_ITERATOR * @see #RPAREN * @see #SLIST * @see #EMPTY_STAT * @see #EXPR **/ public static final int LITERAL_FOR = GeneratedJavaTokenTypes.LITERAL_for; /** * The <code>while</code> keyword. * * <p>For example:</p> * <pre> * while(line != null) * { * process(line); * line = in.readLine(); * } * </pre> * <p>parses as:</p> * <pre> * +--LITERAL_WHILE (while) * | * +--LPAREN (() * +--EXPR * | * +--NOT_EQUAL (!=) * | * +--IDENT (line) * +--LITERAL_NULL (null) * +--RPAREN ()) * +--SLIST ({) * | * +--EXPR * | * +--METHOD_CALL (() * | * +--IDENT (process) * +--ELIST * | * +--EXPR * | * +--IDENT (line) * +--RPAREN ()) * +--SEMI (;) * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (line) * +--METHOD_CALL (() * | * +--DOT (.) * | * +--IDENT (in) * +--IDENT (readLine) * +--ELIST * +--RPAREN ()) * +--SEMI (;) * +--RCURLY (}) * </pre> **/ public static final int LITERAL_WHILE = GeneratedJavaTokenTypes.LITERAL_while; /** * The <code>do</code> keyword. Note the the while token does not * appear as part of the do-while construct. * * <p>For example:</p> * <pre> * do * { * x = rand.nextInt(10); * } * while(x &lt; 5); * </pre> * <p>parses as:</p> * <pre> * +--LITERAL_DO (do) * | * +--SLIST ({) * | * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (x) * +--METHOD_CALL (() * | * +--DOT (.) * | * +--IDENT (rand) * +--IDENT (nextInt) * +--ELIST * | * +--EXPR * | * +--NUM_INT (10) * +--RPAREN ()) * +--SEMI (;) * +--RCURLY (}) * +--LPAREN (() * +--EXPR * | * +--LT (&lt;) * | * +--IDENT (x) * +--NUM_INT (5) * +--RPAREN ()) * +--SEMI (;) * </pre> * * @see #SLIST * @see #EXPR * @see #EMPTY_STAT * @see #LPAREN * @see #RPAREN * @see #SEMI **/ public static final int LITERAL_DO = GeneratedJavaTokenTypes.LITERAL_do; /** * Literal <code>while</code> in do-while loop. * @see #LITERAL_DO */ public static final int DO_WHILE = GeneratedJavaTokenTypes.DO_WHILE; /** * The <code>break</code> keyword. The first child is an optional * identifier and the last child is a semicolon. * * @see #IDENT * @see #SEMI * @see #SLIST **/ public static final int LITERAL_BREAK = GeneratedJavaTokenTypes.LITERAL_break; /** * The <code>continue</code> keyword. The first child is an * optional identifier and the last child is a semicolon. * * @see #IDENT * @see #SEMI * @see #SLIST **/ public static final int LITERAL_CONTINUE = GeneratedJavaTokenTypes.LITERAL_continue; /** * The <code>return</code> keyword. The first child is an * optional expression for the return value. The last child is a * semi colon. * * @see #EXPR * @see #SEMI * @see #SLIST **/ public static final int LITERAL_RETURN = GeneratedJavaTokenTypes.LITERAL_return; /** * The <code>switch</code> keyword. * * <p>For example:</p> * <pre> * switch(type) * { * case 0: * background = Color.blue; * break; * case 1: * background = Color.red; * break; * default: * background = Color.green; * break; * } * </pre> * <p>parses as:</p> * <pre> * +--LITERAL_SWITCH (switch) * | * +--LPAREN (() * +--EXPR * | * +--IDENT (type) * +--RPAREN ()) * +--LCURLY ({) * +--CASE_GROUP * | * +--LITERAL_CASE (case) * | * +--EXPR * | * +--NUM_INT (0) * +--SLIST * | * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (background) * +--DOT (.) * | * +--IDENT (Color) * +--IDENT (blue) * +--SEMI (;) * +--LITERAL_BREAK (break) * | * +--SEMI (;) * +--CASE_GROUP * | * +--LITERAL_CASE (case) * | * +--EXPR * | * +--NUM_INT (1) * +--SLIST * | * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (background) * +--DOT (.) * | * +--IDENT (Color) * +--IDENT (red) * +--SEMI (;) * +--LITERAL_BREAK (break) * | * +--SEMI (;) * +--CASE_GROUP * | * +--LITERAL_DEFAULT (default) * +--SLIST * | * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (background) * +--DOT (.) * | * +--IDENT (Color) * +--IDENT (green) * +--SEMI (;) * +--LITERAL_BREAK (break) * | * +--SEMI (;) * +--RCURLY (}) * </pre> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.10">Java * Language Specification, &sect;14.10</a> * @see #LPAREN * @see #EXPR * @see #RPAREN * @see #LCURLY * @see #CASE_GROUP * @see #RCURLY * @see #SLIST **/ public static final int LITERAL_SWITCH = GeneratedJavaTokenTypes.LITERAL_switch; /** * The <code>throw</code> keyword. The first child is an * expression that evaluates to a <code>Throwable</code> instance. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.17">Java * Language Specification, &sect;14.17</a> * @see #SLIST * @see #EXPR **/ public static final int LITERAL_THROW = GeneratedJavaTokenTypes.LITERAL_throw; /** * The <code>else</code> keyword. This appears as a child of an * <code>if</code> statement. * * @see #SLIST * @see #EXPR * @see #EMPTY_STAT * @see #LITERAL_IF **/ public static final int LITERAL_ELSE = GeneratedJavaTokenTypes.LITERAL_else; /** * The <code>case</code> keyword. The first child is a constant * expression that evaluates to a integer. * * @see #CASE_GROUP * @see #EXPR **/ public static final int LITERAL_CASE = GeneratedJavaTokenTypes.LITERAL_case; /** * The <code>default</code> keyword. This element has no * children. * * @see #CASE_GROUP * @see #MODIFIERS **/ public static final int LITERAL_DEFAULT = GeneratedJavaTokenTypes.LITERAL_default; /** * The <code>try</code> keyword. The children are a statement * list, zero or more catch blocks and then an optional finally * block. * * <p>For example:</p> * <pre> * try * { * FileReader in = new FileReader("abc.txt"); * } * catch(IOException ioe) * { * } * finally * { * } * </pre> * <p>parses as:</p> * <pre> * +--LITERAL_TRY (try) * | * +--SLIST ({) * | * +--VARIABLE_DEF * | * +--MODIFIERS * +--TYPE * | * +--IDENT (FileReader) * +--IDENT (in) * +--ASSIGN (=) * | * +--EXPR * | * +--LITERAL_NEW (new) * | * +--IDENT (FileReader) * +--LPAREN (() * +--ELIST * | * +--EXPR * | * +--STRING_LITERAL ("abc.txt") * +--RPAREN ()) * +--SEMI (;) * +--RCURLY (}) * +--LITERAL_CATCH (catch) * | * +--LPAREN (() * +--PARAMETER_DEF * | * +--MODIFIERS * +--TYPE * | * +--IDENT (IOException) * +--IDENT (ioe) * +--RPAREN ()) * +--SLIST ({) * | * +--RCURLY (}) * +--LITERAL_FINALLY (finally) * | * +--SLIST ({) * | * +--RCURLY (}) * +--RCURLY (}) * </pre> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.19">Java * Language Specification, &sect;14.19</a> * @see #SLIST * @see #LITERAL_CATCH * @see #LITERAL_FINALLY **/ public static final int LITERAL_TRY = GeneratedJavaTokenTypes.LITERAL_try; /** * Java 7 try-with-resources construct. * * <p>For example:</p> * <pre> * try (Foo foo = new Foo(); Bar bar = new Bar()) { } * </pre> * <p>parses as:</p> * <pre> * +--LITERAL_TRY (try) * | * +--RESOURCE_SPECIFICATION * | * +--LPAREN (() * +--RESOURCES * | * +--RESOURCE * | * +--MODIFIERS * +--TYPE * | * +--IDENT (Foo) * +--IDENT (foo) * +--ASSIGN (=) * +--EXPR * | * +--LITERAL_NEW (new) * | * +--IDENT (Foo) * +--LPAREN (() * +--ELIST * +--RPAREN ()) * +--SEMI (;) * +--RESOURCE * | * +--MODIFIERS * +--TYPE * | * +--IDENT (Bar) * +--IDENT (bar) * +--ASSIGN (=) * +--EXPR * | * +--LITERAL_NEW (new) * | * +--IDENT (Bar) * +--LPAREN (() * +--ELIST * +--RPAREN ()) * +--RPAREN ()) * +--SLIST ({) * +--RCURLY (}) * </pre> * * @see #LPAREN * @see #RESOURCES * @see #RESOURCE * @see #SEMI * @see #RPAREN * @see #LITERAL_TRY **/ public static final int RESOURCE_SPECIFICATION = GeneratedJavaTokenTypes.RESOURCE_SPECIFICATION; /** * Java 7 try-with-resources construct. * * @see #RESOURCE_SPECIFICATION **/ public static final int RESOURCES = GeneratedJavaTokenTypes.RESOURCES; /** * Java 7 try-with-resources construct. * * @see #RESOURCE_SPECIFICATION **/ public static final int RESOURCE = GeneratedJavaTokenTypes.RESOURCE; /** * The <code>catch</code> keyword. * * @see #LPAREN * @see #PARAMETER_DEF * @see #RPAREN * @see #SLIST * @see #LITERAL_TRY **/ public static final int LITERAL_CATCH = GeneratedJavaTokenTypes.LITERAL_catch; /** * The <code>finally</code> keyword. * * @see #SLIST * @see #LITERAL_TRY **/ public static final int LITERAL_FINALLY = GeneratedJavaTokenTypes.LITERAL_finally; /** * The <code>+=</code> (addition assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int PLUS_ASSIGN = GeneratedJavaTokenTypes.PLUS_ASSIGN; /** * The <code>-=</code> (subtraction assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int MINUS_ASSIGN = GeneratedJavaTokenTypes.MINUS_ASSIGN; /** * The <code>*=</code> (multiplication assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int STAR_ASSIGN = GeneratedJavaTokenTypes.STAR_ASSIGN; /** * The <code>/=</code> (division assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int DIV_ASSIGN = GeneratedJavaTokenTypes.DIV_ASSIGN; /** * The <code>%=</code> (remainder assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int MOD_ASSIGN = GeneratedJavaTokenTypes.MOD_ASSIGN; /** * The <code>&gt;&gt;=</code> (signed right shift assignment) * operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int SR_ASSIGN = GeneratedJavaTokenTypes.SR_ASSIGN; /** * The <code>&gt;&gt;&gt;=</code> (unsigned right shift assignment) * operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int BSR_ASSIGN = GeneratedJavaTokenTypes.BSR_ASSIGN; /** * The <code>&lt;&lt;=</code> (left shift assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int SL_ASSIGN = GeneratedJavaTokenTypes.SL_ASSIGN; /** * The <code>&amp;=</code> (bitwise AND assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int BAND_ASSIGN = GeneratedJavaTokenTypes.BAND_ASSIGN; /** * The <code>^=</code> (bitwise exclusive OR assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int BXOR_ASSIGN = GeneratedJavaTokenTypes.BXOR_ASSIGN; /** * The <code>|=</code> (bitwise OR assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int BOR_ASSIGN = GeneratedJavaTokenTypes.BOR_ASSIGN; /** * The <code>&#63;</code> (conditional) operator. Technically, * the colon is also part of this operator, but it appears as a * separate token. * * <p>For example:</p> * <pre> * (quantity == 1) ? "": "s" * </pre> * <p> * parses as: * </p> * <pre> * +--QUESTION (?) * | * +--LPAREN (() * +--EQUAL (==) * | * +--IDENT (quantity) * +--NUM_INT (1) * +--RPAREN ()) * +--STRING_LITERAL ("") * +--COLON (:) * +--STRING_LITERAL ("s") * </pre> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25">Java * Language Specification, &sect;15.25</a> * @see #EXPR * @see #COLON **/ public static final int QUESTION = GeneratedJavaTokenTypes.QUESTION; /** * The <code>||</code> (conditional OR) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.24">Java * Language Specification, &sect;15.24</a> * @see #EXPR **/ public static final int LOR = GeneratedJavaTokenTypes.LOR; /** * The <code>&amp;&amp;</code> (conditional AND) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.23">Java * Language Specification, &sect;15.23</a> * @see #EXPR **/ public static final int LAND = GeneratedJavaTokenTypes.LAND; /** * The <code>|</code> (bitwise OR) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.22.1">Java * Language Specification, &sect;15.22.1</a> * @see #EXPR **/ public static final int BOR = GeneratedJavaTokenTypes.BOR; /** * The <code>^</code> (bitwise exclusive OR) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.22.1">Java * Language Specification, &sect;15.22.1</a> * @see #EXPR **/ public static final int BXOR = GeneratedJavaTokenTypes.BXOR; /** * The <code>&amp;</code> (bitwise AND) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.22.1">Java * Language Specification, &sect;15.22.1</a> * @see #EXPR **/ public static final int BAND = GeneratedJavaTokenTypes.BAND; /** * The <code>&#33;=</code> (not equal) operator. * * @see #EXPR **/ public static final int NOT_EQUAL = GeneratedJavaTokenTypes.NOT_EQUAL; /** * The <code>==</code> (equal) operator. * * @see #EXPR **/ public static final int EQUAL = GeneratedJavaTokenTypes.EQUAL; /** * The <code>&lt;</code> (less than) operator. * * @see #EXPR **/ public static final int LT = GeneratedJavaTokenTypes.LT; /** * The <code>&gt;</code> (greater than) operator. * * @see #EXPR **/ public static final int GT = GeneratedJavaTokenTypes.GT; /** * The <code>&lt;=</code> (less than or equal) operator. * * @see #EXPR **/ public static final int LE = GeneratedJavaTokenTypes.LE; /** * The <code>&gt;=</code> (greater than or equal) operator. * * @see #EXPR **/ public static final int GE = GeneratedJavaTokenTypes.GE; /** * The <code>instanceof</code> operator. The first child is an * object reference or something that evaluates to an object * reference. The second child is a reference type. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.20.2">Java * Language Specification, &sect;15.20.2</a> * @see #EXPR * @see #METHOD_CALL * @see #IDENT * @see #DOT * @see #TYPE * @see FullIdent **/ public static final int LITERAL_INSTANCEOF = GeneratedJavaTokenTypes.LITERAL_instanceof; /** * The <code>&lt;&lt;</code> (shift left) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19">Java * Language Specification, &sect;15.19</a> * @see #EXPR **/ public static final int SL = GeneratedJavaTokenTypes.SL; /** * The <code>&gt;&gt;</code> (signed shift right) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19">Java * Language Specification, &sect;15.19</a> * @see #EXPR **/ public static final int SR = GeneratedJavaTokenTypes.SR; /** * The <code>&gt;&gt;&gt;</code> (unsigned shift right) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19">Java * Language Specification, &sect;15.19</a> * @see #EXPR **/ public static final int BSR = GeneratedJavaTokenTypes.BSR; /** * The <code>+</code> (addition) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18">Java * Language Specification, &sect;15.18</a> * @see #EXPR **/ public static final int PLUS = GeneratedJavaTokenTypes.PLUS; /** * The <code>-</code> (subtraction) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18">Java * Language Specification, &sect;15.18</a> * @see #EXPR **/ public static final int MINUS = GeneratedJavaTokenTypes.MINUS; /** * The <code>/</code> (division) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.2">Java * Language Specification, &sect;15.17.2</a> * @see #EXPR **/ public static final int DIV = GeneratedJavaTokenTypes.DIV; /** * The <code>%</code> (remainder) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.3">Java * Language Specification, &sect;15.17.3</a> * @see #EXPR **/ public static final int MOD = GeneratedJavaTokenTypes.MOD; /** * The <code>++</code> (prefix increment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.1">Java * Language Specification, &sect;15.15.1</a> * @see #EXPR * @see #POST_INC **/ public static final int INC = GeneratedJavaTokenTypes.INC; /** * The <code>--</code> (prefix decrement) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.2">Java * Language Specification, &sect;15.15.2</a> * @see #EXPR * @see #POST_DEC **/ public static final int DEC = GeneratedJavaTokenTypes.DEC; /** * The <code>~</code> (bitwise complement) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.5">Java * Language Specification, &sect;15.15.5</a> * @see #EXPR **/ public static final int BNOT = GeneratedJavaTokenTypes.BNOT; /** * The <code>&#33;</code> (logical complement) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.6">Java * Language Specification, &sect;15.15.6</a> * @see #EXPR **/ public static final int LNOT = GeneratedJavaTokenTypes.LNOT; /** * The <code>true</code> keyword. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.3">Java * Language Specification, &sect;3.10.3</a> * @see #EXPR * @see #LITERAL_FALSE **/ public static final int LITERAL_TRUE = GeneratedJavaTokenTypes.LITERAL_true; /** * The <code>false</code> keyword. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.3">Java * Language Specification, &sect;3.10.3</a> * @see #EXPR * @see #LITERAL_TRUE **/ public static final int LITERAL_FALSE = GeneratedJavaTokenTypes.LITERAL_false; /** * The <code>null</code> keyword. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.7">Java * Language Specification, &sect;3.10.7</a> * @see #EXPR **/ public static final int LITERAL_NULL = GeneratedJavaTokenTypes.LITERAL_null; /** * The <code>new</code> keyword. This element is used to define * new instances of objects, new arrays, and new anonymous inner * classes. * * <p>For example:</p> * * <pre> * new ArrayList(50) * </pre> * * <p>parses as:</p> * <pre> * +--LITERAL_NEW (new) * | * +--IDENT (ArrayList) * +--LPAREN (() * +--ELIST * | * +--EXPR * | * +--NUM_INT (50) * +--RPAREN ()) * </pre> * * <p>For example:</p> * <pre> * new float[] * { * 3.0f, * 4.0f * }; * </pre> * * <p>parses as:</p> * <pre> * +--LITERAL_NEW (new) * | * +--LITERAL_FLOAT (float) * +--ARRAY_DECLARATOR ([) * +--ARRAY_INIT ({) * | * +--EXPR * | * +--NUM_FLOAT (3.0f) * +--COMMA (,) * +--EXPR * | * +--NUM_FLOAT (4.0f) * +--RCURLY (}) * </pre> * * <p>For example:</p> * <pre> * new FilenameFilter() * { * public boolean accept(File dir, String name) * { * return name.endsWith(".java"); * } * } * </pre> * * <p>parses as:</p> * <pre> * +--LITERAL_NEW (new) * | * +--IDENT (FilenameFilter) * +--LPAREN (() * +--ELIST * +--RPAREN ()) * +--OBJBLOCK * | * +--LCURLY ({) * +--METHOD_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--TYPE * | * +--LITERAL_BOOLEAN (boolean) * +--IDENT (accept) * +--PARAMETERS * | * +--PARAMETER_DEF * | * +--MODIFIERS * +--TYPE * | * +--IDENT (File) * +--IDENT (dir) * +--COMMA (,) * +--PARAMETER_DEF * | * +--MODIFIERS * +--TYPE * | * +--IDENT (String) * +--IDENT (name) * +--SLIST ({) * | * +--LITERAL_RETURN (return) * | * +--EXPR * | * +--METHOD_CALL (() * | * +--DOT (.) * | * +--IDENT (name) * +--IDENT (endsWith) * +--ELIST * | * +--EXPR * | * +--STRING_LITERAL (".java") * +--RPAREN ()) * +--SEMI (;) * +--RCURLY (}) * +--RCURLY (}) * </pre> * * @see #IDENT * @see #DOT * @see #LPAREN * @see #ELIST * @see #RPAREN * @see #OBJBLOCK * @see #ARRAY_INIT * @see FullIdent **/ public static final int LITERAL_NEW = GeneratedJavaTokenTypes.LITERAL_new; /** * An integer literal. These may be specified in decimal, * hexadecimal, or octal form. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.1">Java * Language Specification, &sect;3.10.1</a> * @see #EXPR * @see #NUM_LONG **/ public static final int NUM_INT = GeneratedJavaTokenTypes.NUM_INT; /** * A character literal. This is a (possibly escaped) character * enclosed in single quotes. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.4">Java * Language Specification, &sect;3.10.4</a> * @see #EXPR **/ public static final int CHAR_LITERAL = GeneratedJavaTokenTypes.CHAR_LITERAL; /** * A string literal. This is a sequence of (possibly escaped) * characters enclosed in double quotes. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.5">Java * Language Specification, &sect;3.10.5</a> * @see #EXPR **/ public static final int STRING_LITERAL = GeneratedJavaTokenTypes.STRING_LITERAL; /** * A single precision floating point literal. This is a floating * point number with an <code>F</code> or <code>f</code> suffix. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.2">Java * Language Specification, &sect;3.10.2</a> * @see #EXPR * @see #NUM_DOUBLE **/ public static final int NUM_FLOAT = GeneratedJavaTokenTypes.NUM_FLOAT; /** * A long integer literal. These are almost the same as integer * literals, but they have an <code>L</code> or <code>l</code> * (ell) suffix. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.1">Java * Language Specification, &sect;3.10.1</a> * @see #EXPR * @see #NUM_INT **/ public static final int NUM_LONG = GeneratedJavaTokenTypes.NUM_LONG; /** * A double precision floating point literal. This is a floating * point number with an optional <code>D</code> or <code>d</code> * suffix. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.2">Java * Language Specification, &sect;3.10.2</a> * @see #EXPR * @see #NUM_FLOAT **/ public static final int NUM_DOUBLE = GeneratedJavaTokenTypes.NUM_DOUBLE; /* * * This token does not appear in the tree. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.6">Java * Language Specification, &sect;3.6</a> * @see FileContents **/ //public static final int WS = GeneratedJavaTokenTypes.WS; /* * * This token does not appear in the tree. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.7">Java * Language Specification, &sect;3.7</a> * @see FileContents **/ //public static final int SL_COMMENT = GeneratedJavaTokenTypes.SL_COMMENT; /* * * This token does not appear in the tree. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.7">Java * Language Specification, &sect;3.7</a> * @see FileContents **/ //public static final int ML_COMMENT = GeneratedJavaTokenTypes.ML_COMMENT; /* * * This token does not appear in the tree. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.6">Java * Language Specification, &sect;3.10.6</a> * @see #CHAR_LITERAL * @see #STRING_LITERAL **/ //public static final int ESC = GeneratedJavaTokenTypes.ESC; /* * * This token does not appear in the tree. * * @see #NUM_INT * @see #NUM_LONG **/ //public static final int HEX_DIGIT = GeneratedJavaTokenTypes.HEX_DIGIT; /* * * This token does not appear in the tree. * * @see #NUM_FLOAT * @see #NUM_DOUBLE **/ //public static final int EXPONENT = GeneratedJavaTokenTypes.EXPONENT; /* * * This token does not appear in the tree. * * @see #NUM_FLOAT * @see #NUM_DOUBLE **/ // public static final int FLOAT_SUFFIX = // GeneratedJavaTokenTypes.FLOAT_SUFFIX; /** * The <code>assert</code> keyword. This is only for Java 1.4 and * later. * * <p>For example:</p> * <pre> * assert(x==4); * </pre> * <p>parses as:</p> * <pre> * +--LITERAL_ASSERT (assert) * | * +--EXPR * | * +--LPAREN (() * +--EQUAL (==) * | * +--IDENT (x) * +--NUM_INT (4) * +--RPAREN ()) * +--SEMI (;) * </pre> **/ public static final int LITERAL_ASSERT = GeneratedJavaTokenTypes.ASSERT; /** * A static import declaration. Static import declarations are optional, * but must appear after the package declaration and before the type * declaration. * * <p>For example:</p> * * <pre> * import static java.io.IOException; * </pre> * * <p>parses as:</p> * * <pre> * +--STATIC_IMPORT (import) * | * +--LITERAL_STATIC * +--DOT (.) * | * +--DOT (.) * | * +--IDENT (java) * +--IDENT (io) * +--IDENT (IOException) * +--SEMI (;) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #LITERAL_STATIC * @see #DOT * @see #IDENT * @see #STAR * @see #SEMI * @see FullIdent **/ public static final int STATIC_IMPORT = GeneratedJavaTokenTypes.STATIC_IMPORT; /** * An enum declaration. Its notable children are * enum constant declarations followed by * any construct that may be expected in a class body. * * <p>For example:</p> * <pre> * public enum MyEnum * implements Serializable * { * FIRST_CONSTANT, * SECOND_CONSTANT; * * public void someMethod() * { * } * } * </pre> * <p>parses as:</p> * <pre> * +--ENUM_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--ENUM (enum) * +--IDENT (MyEnum) * +--EXTENDS_CLAUSE * +--IMPLEMENTS_CLAUSE * | * +--IDENT (Serializable) * +--OBJBLOCK * | * +--LCURLY ({) * +--ENUM_CONSTANT_DEF * | * +--IDENT (FIRST_CONSTANT) * +--COMMA (,) * +--ENUM_CONSTANT_DEF * | * +--IDENT (SECOND_CONSTANT) * +--SEMI (;) * +--METHOD_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--TYPE * | * +--LITERAL_void (void) * +--IDENT (someMethod) * +--LPAREN (() * +--PARAMETERS * +--RPAREN ()) * +--SLIST ({) * | * +--RCURLY (}) * +--RCURLY (}) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #MODIFIERS * @see #ENUM * @see #IDENT * @see #EXTENDS_CLAUSE * @see #IMPLEMENTS_CLAUSE * @see #OBJBLOCK * @see #LITERAL_NEW * @see #ENUM_CONSTANT_DEF **/ public static final int ENUM_DEF = GeneratedJavaTokenTypes.ENUM_DEF; /** * The <code>enum</code> keyword. This element appears * as part of an enum declaration. **/ public static final int ENUM = GeneratedJavaTokenTypes.ENUM; /** * An enum constant declaration. Its notable children are annotations, * arguments and object block akin to an anonymous * inner class' body. * * <p>For example:</p> * <pre> * SOME_CONSTANT(1) * { * public void someMethodOverridenFromMainBody() * { * } * } * </pre> * <p>parses as:</p> * <pre> * +--ENUM_CONSTANT_DEF * | * +--ANNOTATIONS * +--IDENT (SOME_CONSTANT) * +--LPAREN (() * +--ELIST * | * +--EXPR * | * +--NUM_INT (1) * +--RPAREN ()) * +--OBJBLOCK * | * +--LCURLY ({) * | * +--METHOD_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--TYPE * | * +--LITERAL_void (void) * +--IDENT (someMethodOverridenFromMainBody) * +--LPAREN (() * +--PARAMETERS * +--RPAREN ()) * +--SLIST ({) * | * +--RCURLY (}) * +--RCURLY (}) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #ANNOTATIONS * @see #MODIFIERS * @see #IDENT * @see #ELIST * @see #OBJBLOCK **/ public static final int ENUM_CONSTANT_DEF = GeneratedJavaTokenTypes.ENUM_CONSTANT_DEF; /** * A for-each clause. This is a child of * <code>LITERAL_FOR</code>. The children of this element may be * a parameter definition, the colon literal and an expression. * * @see #VARIABLE_DEF * @see #ELIST * @see #LITERAL_FOR **/ public static final int FOR_EACH_CLAUSE = GeneratedJavaTokenTypes.FOR_EACH_CLAUSE; /** * An annotation declaration. The notable children are the name of the * annotation type, annotation field declarations and (constant) fields. * * <p>For example:</p> * <pre> * public @interface MyAnnotation * { * int someValue(); * } * </pre> * <p>parses as:</p> * <pre> * +--ANNOTATION_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--AT (@) * +--LITERAL_INTERFACE (interface) * +--IDENT (MyAnnotation) * +--OBJBLOCK * | * +--LCURLY ({) * +--ANNOTATION_FIELD_DEF * | * +--MODIFIERS * +--TYPE * | * +--LITERAL_INT (int) * +--IDENT (someValue) * +--LPAREN (() * +--RPAREN ()) * +--SEMI (;) * +--RCURLY (}) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #MODIFIERS * @see #LITERAL_INTERFACE * @see #IDENT * @see #OBJBLOCK * @see #ANNOTATION_FIELD_DEF **/ public static final int ANNOTATION_DEF = GeneratedJavaTokenTypes.ANNOTATION_DEF; /** * An annotation field declaration. The notable children are modifiers, * field type, field name and an optional default value (a conditional * compile-time constant expression). Default values may also by * annotations. * * <p>For example:</p> * * <pre> * String someField() default "Hello world"; * </pre> * * <p>parses as:</p> * * <pre> * +--ANNOTATION_FIELD_DEF * | * +--MODIFIERS * +--TYPE * | * +--IDENT (String) * +--IDENT (someField) * +--LPAREN (() * +--RPAREN ()) * +--LITERAL_DEFAULT (default) * +--STRING_LITERAL ("Hello world") * +--SEMI (;) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #MODIFIERS * @see #TYPE * @see #LITERAL_DEFAULT */ public static final int ANNOTATION_FIELD_DEF = GeneratedJavaTokenTypes.ANNOTATION_FIELD_DEF; // note: &#064; is the html escape for '@', // used here to avoid confusing the javadoc tool /** * A collection of annotations on a package or enum constant. * A collections of annotations will only occur on these nodes * as all other nodes that may be qualified with an annotation can * be qualified with any other modifier and hence these annotations * would be contained in a {@link #MODIFIERS} node. * * <p>For example:</p> * * <pre> * &#064;MyAnnotation package blah; * </pre> * * <p>parses as:</p> * * <pre> * +--PACKAGE_DEF (package) * | * +--ANNOTATIONS * | * +--ANNOTATION * | * +--AT (&#064;) * +--IDENT (MyAnnotation) * +--IDENT (blah) * +--SEMI (;) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #ANNOTATION * @see #AT * @see #IDENT */ public static final int ANNOTATIONS = GeneratedJavaTokenTypes.ANNOTATIONS; // note: &#064; is the html escape for '@', // used here to avoid confusing the javadoc tool /** * An annotation of a package, type, field, parameter or variable. * An annotation may occur anywhere modifiers occur (it is a * type of modifier) and may also occur prior to a package definition. * The notable children are: The annotation name and either a single * default annotation value or a sequence of name value pairs. * Annotation values may also be annotations themselves. * * <p>For example:</p> * * <pre> * &#064;MyAnnotation(someField1 = "Hello", * someField2 = &#064;SomeOtherAnnotation) * </pre> * * <p>parses as:</p> * * <pre> * +--ANNOTATION * | * +--AT (&#064;) * +--IDENT (MyAnnotation) * +--LPAREN (() * +--ANNOTATION_MEMBER_VALUE_PAIR * | * +--IDENT (someField1) * +--ASSIGN (=) * +--ANNOTATION * | * +--AT (&#064;) * +--IDENT (SomeOtherAnnotation) * +--ANNOTATION_MEMBER_VALUE_PAIR * | * +--IDENT (someField2) * +--ASSIGN (=) * +--STRING_LITERAL ("Hello") * +--RPAREN ()) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #MODIFIERS * @see #IDENT * @see #ANNOTATION_MEMBER_VALUE_PAIR */ public static final int ANNOTATION = GeneratedJavaTokenTypes.ANNOTATION; /** * An initialisation of an annotation member with a value. * Its children are the name of the member, the assignment literal * and the (compile-time constant conditional expression) value. * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #ANNOTATION * @see #IDENT */ public static final int ANNOTATION_MEMBER_VALUE_PAIR = GeneratedJavaTokenTypes.ANNOTATION_MEMBER_VALUE_PAIR; /** * An annotation array member initialisation. * Initializers can not be nested. * Am initializer may be present as a default to a annotation * member, as the single default value to an annotation * (e.g. @Annotation({1,2})) or as the value of an annotation * member value pair. * * <p>For example:</p> * * <pre> * { 1, 2 } * </pre> * * <p>parses as:</p> * * <pre> * +--ANNOTATION_ARRAY_INIT ({) * | * +--NUM_INT (1) * +--COMMA (,) * +--NUM_INT (2) * +--RCURLY (}) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #ANNOTATION * @see #IDENT * @see #ANNOTATION_MEMBER_VALUE_PAIR */ public static final int ANNOTATION_ARRAY_INIT = GeneratedJavaTokenTypes.ANNOTATION_ARRAY_INIT; /** * A list of type parameters to a class, interface or * method definition. Children are LT, at least one * TYPE_PARAMETER, zero or more of: a COMMAs followed by a single * TYPE_PARAMETER and a final GT. * * <p>For example:</p> * * <pre> * public class Blah&lt;A, B&gt; * { * } * </pre> * * <p>parses as:</p> * * <pre> * +--CLASS_DEF ({) * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--LITERAL_CLASS (class) * +--IDENT (Blah) * +--TYPE_PARAMETERS * | * +--GENERIC_START (&lt;) * +--TYPE_PARAMETER * | * +--IDENT (A) * +--COMMA (,) * +--TYPE_PARAMETER * | * +--IDENT (B) * +--GENERIC_END (&gt;) * +--OBJBLOCK * | * +--LCURLY ({) * +--NUM_INT (1) * +--COMMA (,) * +--NUM_INT (2) * +--RCURLY (}) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=14"> * JSR14</a> * @see #GENERIC_START * @see #GENERIC_END * @see #TYPE_PARAMETER * @see #COMMA */ public static final int TYPE_PARAMETERS = GeneratedJavaTokenTypes.TYPE_PARAMETERS; /** * A type parameter to a class, interface or method definition. * Children are the type name and an optional TYPE_UPPER_BOUNDS. * * <p>For example:</p> * * <pre> * A extends Collection * </pre> * * <p>parses as:</p> * * <pre> * +--TYPE_PARAMETER * | * +--IDENT (A) * +--TYPE_UPPER_BOUNDS * | * +--IDENT (Collection) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=14"> * JSR14</a> * @see #IDENT * @see #WILDCARD_TYPE * @see #TYPE_UPPER_BOUNDS */ public static final int TYPE_PARAMETER = GeneratedJavaTokenTypes.TYPE_PARAMETER; /** * A list of type arguments to a type reference or * a method/ctor invocation. Children are GENERIC_START, at least one * TYPE_ARGUMENT, zero or more of a COMMAs followed by a single * TYPE_ARGUMENT, and a final GENERIC_END. * * <p>For example:</p> * * <pre> * public Collection&lt;?&gt; a; * </pre> * * <p>parses as:</p> * * <pre> * +--VARIABLE_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--TYPE * | * +--IDENT (Collection) * | * +--TYPE_ARGUMENTS * | * +--GENERIC_START (&lt;) * +--TYPE_ARGUMENT * | * +--WILDCARD_TYPE (?) * +--GENERIC_END (&gt;) * +--IDENT (a) * +--SEMI (;) * </pre> * * @see #GENERIC_START * @see #GENERIC_END * @see #TYPE_ARGUMENT * @see #COMMA */ public static final int TYPE_ARGUMENTS = GeneratedJavaTokenTypes.TYPE_ARGUMENTS; /** * A type arguments to a type reference or a method/ctor invocation. * Children are either: type name or wildcard type with possible type * upper or lower bounds. * * <p>For example:</p> * * <pre> * ? super List * </pre> * * <p>parses as:</p> * * <pre> * +--TYPE_ARGUMENT * | * +--WILDCARD_TYPE (?) * +--TYPE_LOWER_BOUNDS * | * +--IDENT (List) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=14"> * JSR14</a> * @see #WILDCARD_TYPE * @see #TYPE_UPPER_BOUNDS * @see #TYPE_LOWER_BOUNDS */ public static final int TYPE_ARGUMENT = GeneratedJavaTokenTypes.TYPE_ARGUMENT; /** * The type that refers to all types. This node has no children. * * @see <a href="http://www.jcp.org/en/jsr/detail?id=14"> * JSR14</a> * @see #TYPE_ARGUMENT * @see #TYPE_UPPER_BOUNDS * @see #TYPE_LOWER_BOUNDS */ public static final int WILDCARD_TYPE = GeneratedJavaTokenTypes.WILDCARD_TYPE; /** * An upper bounds on a wildcard type argument or type parameter. * This node has one child - the type that is being used for * the bounding. * * @see <a href="http://www.jcp.org/en/jsr/detail?id=14"> * JSR14</a> * @see #TYPE_PARAMETER * @see #TYPE_ARGUMENT * @see #WILDCARD_TYPE */ public static final int TYPE_UPPER_BOUNDS = GeneratedJavaTokenTypes.TYPE_UPPER_BOUNDS; /** * A lower bounds on a wildcard type argument. This node has one child * - the type that is being used for the bounding. * * @see <a href="http://www.jcp.org/en/jsr/detail?id=14"> * JSR14</a> * @see #TYPE_ARGUMENT * @see #WILDCARD_TYPE */ public static final int TYPE_LOWER_BOUNDS = GeneratedJavaTokenTypes.TYPE_LOWER_BOUNDS; /** * An 'at' symbol - signifying an annotation instance or the prefix * to the interface literal signifying the definition of an annotation * declaration. * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> */ public static final int AT = GeneratedJavaTokenTypes.AT; /** * A triple dot for variable-length parameters. This token only ever occurs * in a parameter declaration immediately after the type of the parameter. * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> */ public static final int ELLIPSIS = GeneratedJavaTokenTypes.ELLIPSIS; /** * '&amp;' symbol when used in a generic upper or lower bounds constrain * e.g. {@code Comparable&lt;<? extends Serializable, CharSequence>}. */ public static final int TYPE_EXTENSION_AND = GeneratedJavaTokenTypes.TYPE_EXTENSION_AND; /** * '&lt;' symbol signifying the start of type arguments or type * parameters. */ public static final int GENERIC_START = GeneratedJavaTokenTypes.GENERIC_START; /** * '&gt;' symbol signifying the end of type arguments or type parameters. */ public static final int GENERIC_END = GeneratedJavaTokenTypes.GENERIC_END; /** * Special lambda symbol '-&gt;'. */ public static final int LAMBDA = GeneratedJavaTokenTypes.LAMBDA; /** * Begining of single line comment: '//'. * * <pre> * +--SINLE_LINE_COMMENT * | * +--COMMENT_CONTENT * </pre> */ public static final int SINGLE_LINE_COMMENT = GeneratedJavaTokenTypes.SINGLE_LINE_COMMENT; /** * Begining of block comment: '/*'. * * <pre> * +--BLOCK_COMMENT_BEGIN * | * +--COMMENT_CONTENT * +--BLOCK_COMMENT_END * </pre> */ public static final int BLOCK_COMMENT_BEGIN = GeneratedJavaTokenTypes.BLOCK_COMMENT_BEGIN; /** * End of block comment: '* /'. * * <pre> * +--BLOCK_COMMENT_BEGIN * | * +--COMMENT_CONTENT * +--BLOCK_COMMENT_END * </pre> */ public static final int BLOCK_COMMENT_END = GeneratedJavaTokenTypes.BLOCK_COMMENT_END; /** * Text of single-line or block comment. * *<pre> * +--SINLE_LINE_COMMENT * | * +--COMMENT_CONTENT * </pre> * * <pre> * +--BLOCK_COMMENT_BEGIN * | * +--COMMENT_CONTENT * +--BLOCK_COMMENT_END * </pre> */ public static final int COMMENT_CONTENT = GeneratedJavaTokenTypes.COMMENT_CONTENT; //////////////////////////////////////////////////////////////////////// // The interesting code goes here //////////////////////////////////////////////////////////////////////// /** maps from a token name to value */ private static final ImmutableMap<String, Integer> TOKEN_NAME_TO_VALUE; /** maps from a token value to name */ private static final String[] TOKEN_VALUE_TO_NAME; // initialise the constants static { final ImmutableMap.Builder<String, Integer> builder = ImmutableMap.builder(); final Field[] fields = TokenTypes.class.getDeclaredFields(); String[] tempTokenValueToName = new String[0]; for (final Field f : fields) { // Only process the int declarations. if (f.getType() != Integer.TYPE) { continue; } final String name = f.getName(); try { final int tokenValue = f.getInt(name); builder.put(name, tokenValue); if (tokenValue > tempTokenValueToName.length - 1) { final String[] temp = new String[tokenValue + 1]; System.arraycopy(tempTokenValueToName, 0, temp, 0, tempTokenValueToName.length); tempTokenValueToName = temp; } tempTokenValueToName[tokenValue] = name; } catch (final IllegalArgumentException e) { System.exit(1); } catch (final IllegalAccessException e) { System.exit(1); } } TOKEN_NAME_TO_VALUE = builder.build(); TOKEN_VALUE_TO_NAME = tempTokenValueToName; } /** * Returns the name of a token for a given ID. * @param iD the ID of the token name to get * @return a token name */ public static String getTokenName(int iD) { if (iD > TOKEN_VALUE_TO_NAME.length - 1) { throw new IllegalArgumentException("given id " + iD); } final String name = TOKEN_VALUE_TO_NAME[iD]; if (name == null) { throw new IllegalArgumentException("given id " + iD); } return name; } /** * Returns the ID of a token for a given name. * @param name the name of the token ID to get * @return a token ID */ public static int getTokenId(String name) { final Integer id = TOKEN_NAME_TO_VALUE.get(name); if (id == null) { throw new IllegalArgumentException("given name " + name); } return id.intValue(); } /** * Returns the short description of a token for a given name. * @param name the name of the token ID to get * @return a short description */ public static String getShortDescription(String name) { if (!TOKEN_NAME_TO_VALUE.containsKey(name)) { throw new IllegalArgumentException("given name " + name); } final String tokentypes = "com.puppycrawl.tools.checkstyle.api.tokentypes"; final ResourceBundle bundle = ResourceBundle.getBundle(tokentypes); return bundle.getString(name); } /** * Is argument comment-related type (SINGLE_LINE_COMMENT, * BLOCK_COMMENT_BEGIN, BLOCK_COMMENT_END, COMMENT_CONTENT). * @param type * token type. * @return true if type is comment-related type. */ public static boolean isCommentType(int type) { return type == TokenTypes.SINGLE_LINE_COMMENT || type == TokenTypes.BLOCK_COMMENT_BEGIN || type == TokenTypes.BLOCK_COMMENT_END || type == TokenTypes.COMMENT_CONTENT; } /** * Is argument comment-related type name (SINGLE_LINE_COMMENT, * BLOCK_COMMENT_BEGIN, BLOCK_COMMENT_END, COMMENT_CONTENT). * @param type * token type name. * @return true if type is comment-related type name. */ public static boolean isCommentType(String type) { return isCommentType(getTokenId(type)); } }
src/main/java/com/puppycrawl/tools/checkstyle/api/TokenTypes.java
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2015 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import java.lang.reflect.Field; import java.util.ResourceBundle; import com.google.common.collect.ImmutableMap; import com.puppycrawl.tools.checkstyle.grammars.GeneratedJavaTokenTypes; /** * Contains the constants for all the tokens contained in the Abstract * Syntax Tree. * * <p>Implementation detail: This class has been introduced to break * the circular dependency between packages.</p> * * @author Oliver Burn * @author <a href="mailto:[email protected]">Peter Dobratz</a> */ public final class TokenTypes { ///CLOVER:OFF /** prevent instantiation */ private TokenTypes() { } ///CLOVER:ON // The following three types are never part of an AST, // left here as a reminder so nobody will read them accidentally /* * token representing a NULL_TREE_LOOKAHEAD */ // public static final int NULL_TREE_LOOKAHEAD = 3; /* * token representing a BLOCK */ // public static final int BLOCK = 4; /* * token representing a VOCAB */ // public static final int VOCAB = 149; // These are the types that can actually occur in an AST // it makes sense to register Checks for these types /** * The end of file token. This is the root node for the source * file. It's children are an optional package definition, zero * or more import statements, and one or more class or interface * definitions. * * @see #PACKAGE_DEF * @see #IMPORT * @see #CLASS_DEF * @see #INTERFACE_DEF **/ public static final int EOF = GeneratedJavaTokenTypes.EOF; /** * Modifiers for type, method, and field declarations. The * modifiers element is always present even though it may have no * children. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html">Java * Language Specification, &sect;8</a> * @see #LITERAL_PUBLIC * @see #LITERAL_PROTECTED * @see #LITERAL_PRIVATE * @see #ABSTRACT * @see #LITERAL_STATIC * @see #FINAL * @see #LITERAL_TRANSIENT * @see #LITERAL_VOLATILE * @see #LITERAL_SYNCHRONIZED * @see #LITERAL_NATIVE * @see #STRICTFP * @see #ANNOTATION * @see #LITERAL_DEFAULT **/ public static final int MODIFIERS = GeneratedJavaTokenTypes.MODIFIERS; /** * An object block. These are children of class, interface, enum, * annotation and enum constant declarations. * Also, object blocks are children of the new keyword when defining * anonymous inner types. * * @see #LCURLY * @see #INSTANCE_INIT * @see #STATIC_INIT * @see #CLASS_DEF * @see #CTOR_DEF * @see #METHOD_DEF * @see #VARIABLE_DEF * @see #RCURLY * @see #INTERFACE_DEF * @see #LITERAL_NEW * @see #ENUM_DEF * @see #ENUM_CONSTANT_DEF * @see #ANNOTATION_DEF **/ public static final int OBJBLOCK = GeneratedJavaTokenTypes.OBJBLOCK; /** * A list of statements. * * @see #RCURLY * @see #EXPR * @see #LABELED_STAT * @see #LITERAL_THROWS * @see #LITERAL_RETURN * @see #SEMI * @see #METHOD_DEF * @see #CTOR_DEF * @see #LITERAL_FOR * @see #LITERAL_WHILE * @see #LITERAL_IF * @see #LITERAL_ELSE * @see #CASE_GROUP **/ public static final int SLIST = GeneratedJavaTokenTypes.SLIST; /** * A constructor declaration. * * <p>For example:</p> * <pre> * public SpecialEntry(int value, String text) * { * this.value = value; * this.text = text; * } * </pre> * <p>parses as:</p> * <pre> * +--CTOR_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--IDENT (SpecialEntry) * +--LPAREN (() * +--PARAMETERS * | * +--PARAMETER_DEF * | * +--MODIFIERS * +--TYPE * | * +--LITERAL_INT (int) * +--IDENT (value) * +--COMMA (,) * +--PARAMETER_DEF * | * +--MODIFIERS * +--TYPE * | * +--IDENT (String) * +--IDENT (text) * +--RPAREN ()) * +--SLIST ({) * | * +--EXPR * | * +--ASSIGN (=) * | * +--DOT (.) * | * +--LITERAL_THIS (this) * +--IDENT (value) * +--IDENT (value) * +--SEMI (;) * +--EXPR * | * +--ASSIGN (=) * | * +--DOT (.) * | * +--LITERAL_THIS (this) * +--IDENT (text) * +--IDENT (text) * +--SEMI (;) * +--RCURLY (}) * </pre> * * @see #OBJBLOCK * @see #CLASS_DEF **/ public static final int CTOR_DEF = GeneratedJavaTokenTypes.CTOR_DEF; /** * A method declaration. The children are modifiers, type parameters, * return type, method name, parameter list, an optional throws list, and * statement list. The statement list is omitted if the method * declaration appears in an interface declaration. Method * declarations may appear inside object blocks of class * declarations, interface declarations, enum declarations, * enum constant declarations or anonymous inner-class declarations. * * <p>For example:</p> * * <pre> * public static int square(int x) * { * return x*x; * } * </pre> * * <p>parses as:</p> * * <pre> * +--METHOD_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--LITERAL_STATIC (static) * +--TYPE * | * +--LITERAL_INT (int) * +--IDENT (square) * +--PARAMETERS * | * +--PARAMETER_DEF * | * +--MODIFIERS * +--TYPE * | * +--LITERAL_INT (int) * +--IDENT (x) * +--SLIST ({) * | * +--LITERAL_RETURN (return) * | * +--EXPR * | * +--STAR (*) * | * +--IDENT (x) * +--IDENT (x) * +--SEMI (;) * +--RCURLY (}) * </pre> * * @see #MODIFIERS * @see #TYPE_PARAMETERS * @see #TYPE * @see #IDENT * @see #PARAMETERS * @see #LITERAL_THROWS * @see #SLIST * @see #OBJBLOCK **/ public static final int METHOD_DEF = GeneratedJavaTokenTypes.METHOD_DEF; /** * A field or local variable declaration. The children are * modifiers, type, the identifier name, and an optional * assignment statement. * * @see #MODIFIERS * @see #TYPE * @see #IDENT * @see #ASSIGN **/ public static final int VARIABLE_DEF = GeneratedJavaTokenTypes.VARIABLE_DEF; /** * An instance initializer. Zero or more instance initializers * may appear in class and enum definitions. This token will be a child * of the object block of the declaring type. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.6">Java * Language Specification&sect;8.6</a> * @see #SLIST * @see #OBJBLOCK **/ public static final int INSTANCE_INIT = GeneratedJavaTokenTypes.INSTANCE_INIT; /** * A static initialization block. Zero or more static * initializers may be children of the object block of a class * or enum declaration (interfaces cannot have static initializers). The * first and only child is a statement list. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.7">Java * Language Specification, &sect;8.7</a> * @see #SLIST * @see #OBJBLOCK **/ public static final int STATIC_INIT = GeneratedJavaTokenTypes.STATIC_INIT; /** * A type. This is either a return type of a method or a type of * a variable or field. The first child of this element is the * actual type. This may be a primitive type, an identifier, a * dot which is the root of a fully qualified type, or an array of * any of these. The second child may be type arguments to the type. * * @see #VARIABLE_DEF * @see #METHOD_DEF * @see #PARAMETER_DEF * @see #IDENT * @see #DOT * @see #LITERAL_VOID * @see #LITERAL_BOOLEAN * @see #LITERAL_BYTE * @see #LITERAL_CHAR * @see #LITERAL_SHORT * @see #LITERAL_INT * @see #LITERAL_FLOAT * @see #LITERAL_LONG * @see #LITERAL_DOUBLE * @see #ARRAY_DECLARATOR * @see #TYPE_ARGUMENTS **/ public static final int TYPE = GeneratedJavaTokenTypes.TYPE; /** * A class declaration. * * <p>For example:</p> * <pre> * public class MyClass * implements Serializable * { * } * </pre> * <p>parses as:</p> * <pre> * +--CLASS_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--LITERAL_CLASS (class) * +--IDENT (MyClass) * +--EXTENDS_CLAUSE * +--IMPLEMENTS_CLAUSE * | * +--IDENT (Serializable) * +--OBJBLOCK * | * +--LCURLY ({) * +--RCURLY (}) * </pre> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html">Java * Language Specification, &sect;8</a> * @see #MODIFIERS * @see #IDENT * @see #EXTENDS_CLAUSE * @see #IMPLEMENTS_CLAUSE * @see #OBJBLOCK * @see #LITERAL_NEW **/ public static final int CLASS_DEF = GeneratedJavaTokenTypes.CLASS_DEF; /** * An interface declaration. * * <p>For example:</p> * * <pre> * public interface MyInterface * { * } * * </pre> * * <p>parses as:</p> * * <pre> * +--INTERFACE_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--LITERAL_INTERFACE (interface) * +--IDENT (MyInterface) * +--EXTENDS_CLAUSE * +--OBJBLOCK * | * +--LCURLY ({) * +--RCURLY (}) * </pre> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html">Java * Language Specification, &sect;9</a> * @see #MODIFIERS * @see #IDENT * @see #EXTENDS_CLAUSE * @see #OBJBLOCK **/ public static final int INTERFACE_DEF = GeneratedJavaTokenTypes.INTERFACE_DEF; /** * The package declaration. This is optional, but if it is * included, then there is only one package declaration per source * file and it must be the first non-comment in the file. A package * declaration may be annotated in which case the annotations comes * before the rest of the declaration (and are the first children). * * <p>For example:</p> * * <pre> * package com.puppycrawl.tools.checkstyle.api; * </pre> * * <p>parses as:</p> * * <pre> * +--PACKAGE_DEF (package) * | * +--ANNOTATIONS * +--DOT (.) * | * +--DOT (.) * | * +--DOT (.) * | * +--DOT (.) * | * +--IDENT (com) * +--IDENT (puppycrawl) * +--IDENT (tools) * +--IDENT (checkstyle) * +--IDENT (api) * +--SEMI (;) * </pre> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.4">Java * Language Specification &sect;7.4</a> * @see #DOT * @see #IDENT * @see #SEMI * @see #ANNOTATIONS * @see FullIdent **/ public static final int PACKAGE_DEF = GeneratedJavaTokenTypes.PACKAGE_DEF; /** * An array declaration. * * <p>If the array declaration represents a type, then the type of * the array elements is the first child. Multidimensional arrays * may be regarded as arrays of arrays. In other words, the first * child of the array declaration is another array * declaration.</p> * * <p>For example:</p> * <pre> * int[] x; * </pre> * <p>parses as:</p> * <pre> * +--VARIABLE_DEF * | * +--MODIFIERS * +--TYPE * | * +--ARRAY_DECLARATOR ([) * | * +--LITERAL_INT (int) * +--IDENT (x) * +--SEMI (;) * </pre> * * <p>The array declaration may also represent an inline array * definition. In this case, the first child will be either an * expression specifying the length of the array or an array * initialization block.</p> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html">Java * Language Specification &sect;10</a> * @see #TYPE * @see #ARRAY_INIT **/ public static final int ARRAY_DECLARATOR = GeneratedJavaTokenTypes.ARRAY_DECLARATOR; /** * An extends clause. This appear as part of class and interface * definitions. This element appears even if the * <code>extends</code> keyword is not explicitly used. The child * is an optional identifier. * * <p>For example:</p> * * * <p>parses as:</p> * <pre> * +--EXTENDS_CLAUSE * | * +--DOT (.) * | * +--DOT (.) * | * +--IDENT (java) * +--IDENT (util) * +--IDENT (LinkedList) * </pre> * * @see #IDENT * @see #DOT * @see #CLASS_DEF * @see #INTERFACE_DEF * @see FullIdent **/ public static final int EXTENDS_CLAUSE = GeneratedJavaTokenTypes.EXTENDS_CLAUSE; /** * An implements clause. This always appears in a class or enum * declaration, even if there are no implemented interfaces. The * children are a comma separated list of zero or more * identifiers. * * <p>For example:</p> * <pre> * implements Serializable, Comparable * </pre> * <p>parses as:</p> * <pre> * +--IMPLEMENTS_CLAUSE * | * +--IDENT (Serializable) * +--COMMA (,) * +--IDENT (Comparable) * </pre> * * @see #IDENT * @see #DOT * @see #COMMA * @see #CLASS_DEF * @see #ENUM_DEF **/ public static final int IMPLEMENTS_CLAUSE = GeneratedJavaTokenTypes.IMPLEMENTS_CLAUSE; /** * A list of parameters to a method or constructor. The children * are zero or more parameter declarations separated by commas. * * <p>For example</p> * <pre> * int start, int end * </pre> * <p>parses as:</p> * <pre> * +--PARAMETERS * | * +--PARAMETER_DEF * | * +--MODIFIERS * +--TYPE * | * +--LITERAL_INT (int) * +--IDENT (start) * +--COMMA (,) * +--PARAMETER_DEF * | * +--MODIFIERS * +--TYPE * | * +--LITERAL_INT (int) * +--IDENT (end) * </pre> * * @see #PARAMETER_DEF * @see #COMMA * @see #METHOD_DEF * @see #CTOR_DEF **/ public static final int PARAMETERS = GeneratedJavaTokenTypes.PARAMETERS; /** * A parameter declaration. The last parameter in a list of parameters may * be variable length (indicated by the ELLIPSIS child node immediately * after the TYPE child). * * @see #MODIFIERS * @see #TYPE * @see #IDENT * @see #PARAMETERS * @see #ELLIPSIS **/ public static final int PARAMETER_DEF = GeneratedJavaTokenTypes.PARAMETER_DEF; /** * A labeled statement. * * <p>For example:</p> * <pre> * outside: ; * </pre> * <p>parses as:</p> * <pre> * +--LABELED_STAT (:) * | * +--IDENT (outside) * +--EMPTY_STAT (;) * </pre> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.7">Java * Language Specification, &sect;14.7</a> * @see #SLIST **/ public static final int LABELED_STAT = GeneratedJavaTokenTypes.LABELED_STAT; /** * A type-cast. * * <p>For example:</p> * <pre> * (String)it.next() * </pre> * <p>parses as:</p> * <pre> * +--TYPECAST (() * | * +--TYPE * | * +--IDENT (String) * +--RPAREN ()) * +--METHOD_CALL (() * | * +--DOT (.) * | * +--IDENT (it) * +--IDENT (next) * +--ELIST * +--RPAREN ()) * </pre> * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.16">Java * Language Specification, &sect;15.16</a> * @see #EXPR * @see #TYPE * @see #TYPE_ARGUMENTS * @see #RPAREN **/ public static final int TYPECAST = GeneratedJavaTokenTypes.TYPECAST; /** * The array index operator. * * <p>For example:</p> * <pre> * ar[2] = 5; * </pre> * <p>parses as:</p> * <pre> * +--EXPR * | * +--ASSIGN (=) * | * +--INDEX_OP ([) * | * +--IDENT (ar) * +--EXPR * | * +--NUM_INT (2) * +--NUM_INT (5) * +--SEMI (;) * </pre> * * @see #EXPR **/ public static final int INDEX_OP = GeneratedJavaTokenTypes.INDEX_OP; /** * The <code>++</code> (postfix increment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.14.1">Java * Language Specification, &sect;15.14.1</a> * @see #EXPR * @see #INC **/ public static final int POST_INC = GeneratedJavaTokenTypes.POST_INC; /** * The <code>--</code> (postfix decrement) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.14.2">Java * Language Specification, &sect;15.14.2</a> * @see #EXPR * @see #DEC **/ public static final int POST_DEC = GeneratedJavaTokenTypes.POST_DEC; /** * A method call. A method call may have type arguments however these * are attached to the appropriate node in the qualified method name. * * <p>For example:</p> * <pre> * Math.random() * </pre> * <p>parses as: * <pre> * +--METHOD_CALL (() * | * +--DOT (.) * | * +--IDENT (Math) * +--IDENT (random) * +--ELIST * +--RPAREN ()) * </pre> * * * @see #IDENT * @see #TYPE_ARGUMENTS * @see #DOT * @see #ELIST * @see #RPAREN * @see FullIdent **/ public static final int METHOD_CALL = GeneratedJavaTokenTypes.METHOD_CALL; /** * Part of Java 8 syntax. Method or constructor call without arguments. * @see #DOUBLE_COLON */ public static final int METHOD_REF = GeneratedJavaTokenTypes.METHOD_REF; /** * An expression. Operators with lower precedence appear at a * higher level in the tree than operators with higher precedence. * Parentheses are siblings to the operator they enclose. * * <p>For example:</p> * <pre> * x = 4 + 3 * 5 + (30 + 26) / 4 + 5 % 4 + (1&lt;&lt;3); * </pre> * <p>parses as:</p> * <pre> * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (x) * +--PLUS (+) * | * +--PLUS (+) * | * +--PLUS (+) * | * +--PLUS (+) * | * +--NUM_INT (4) * +--STAR (*) * | * +--NUM_INT (3) * +--NUM_INT (5) * +--DIV (/) * | * +--LPAREN (() * +--PLUS (+) * | * +--NUM_INT (30) * +--NUM_INT (26) * +--RPAREN ()) * +--NUM_INT (4) * +--MOD (%) * | * +--NUM_INT (5) * +--NUM_INT (4) * +--LPAREN (() * +--SL (&lt;&lt;) * | * +--NUM_INT (1) * +--NUM_INT (3) * +--RPAREN ()) * +--SEMI (;) * </pre> * * @see #ELIST * @see #ASSIGN * @see #LPAREN * @see #RPAREN **/ public static final int EXPR = GeneratedJavaTokenTypes.EXPR; /** * An array initialization. This may occur as part of an array * declaration or inline with <code>new</code>. * * <p>For example:</p> * <pre> * int[] y = * { * 1, * 2, * }; * </pre> * <p>parses as:</p> * <pre> * +--VARIABLE_DEF * | * +--MODIFIERS * +--TYPE * | * +--ARRAY_DECLARATOR ([) * | * +--LITERAL_INT (int) * +--IDENT (y) * +--ASSIGN (=) * | * +--ARRAY_INIT ({) * | * +--EXPR * | * +--NUM_INT (1) * +--COMMA (,) * +--EXPR * | * +--NUM_INT (2) * +--COMMA (,) * +--RCURLY (}) * +--SEMI (;) * </pre> * * <p>Also consider:</p> * <pre> * int[] z = new int[] * { * 1, * 2, * }; * </pre> * <p>which parses as:</p> * <pre> * +--VARIABLE_DEF * | * +--MODIFIERS * +--TYPE * | * +--ARRAY_DECLARATOR ([) * | * +--LITERAL_INT (int) * +--IDENT (z) * +--ASSIGN (=) * | * +--EXPR * | * +--LITERAL_NEW (new) * | * +--LITERAL_INT (int) * +--ARRAY_DECLARATOR ([) * +--ARRAY_INIT ({) * | * +--EXPR * | * +--NUM_INT (1) * +--COMMA (,) * +--EXPR * | * +--NUM_INT (2) * +--COMMA (,) * +--RCURLY (}) * </pre> * * @see #ARRAY_DECLARATOR * @see #TYPE * @see #LITERAL_NEW * @see #COMMA **/ public static final int ARRAY_INIT = GeneratedJavaTokenTypes.ARRAY_INIT; /** * An import declaration. Import declarations are option, but * must appear after the package declaration and before the first type * declaration. * * <p>For example:</p> * * <pre> * import java.io.IOException; * </pre> * * <p>parses as:</p> * * <pre> * +--IMPORT (import) * | * +--DOT (.) * | * +--DOT (.) * | * +--IDENT (java) * +--IDENT (io) * +--IDENT (IOException) * +--SEMI (;) * </pre> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.5">Java * Language Specification &sect;7.5</a> * @see #DOT * @see #IDENT * @see #STAR * @see #SEMI * @see FullIdent **/ public static final int IMPORT = GeneratedJavaTokenTypes.IMPORT; /** * The <code>-</code> (unary minus) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.4">Java * Language Specification, &sect;15.15.4</a> * @see #EXPR **/ public static final int UNARY_MINUS = GeneratedJavaTokenTypes.UNARY_MINUS; /** * The <code>+</code> (unary plus) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.3">Java * Language Specification, &sect;15.15.3</a> * @see #EXPR **/ public static final int UNARY_PLUS = GeneratedJavaTokenTypes.UNARY_PLUS; /** * A group of case clauses. Case clauses with no associated * statements are grouped together into a case group. The last * child is a statement list containing the statements to execute * upon a match. * * <p>For example:</p> * <pre> * case 0: * case 1: * case 2: * x = 3; * break; * </pre> * <p>parses as:</p> * <pre> * +--CASE_GROUP * | * +--LITERAL_CASE (case) * | * +--EXPR * | * +--NUM_INT (0) * +--LITERAL_CASE (case) * | * +--EXPR * | * +--NUM_INT (1) * +--LITERAL_CASE (case) * | * +--EXPR * | * +--NUM_INT (2) * +--SLIST * | * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (x) * +--NUM_INT (3) * +--SEMI (;) * +--LITERAL_BREAK (break) * | * +--SEMI (;) * </pre> * * @see #LITERAL_CASE * @see #LITERAL_DEFAULT * @see #LITERAL_SWITCH **/ public static final int CASE_GROUP = GeneratedJavaTokenTypes.CASE_GROUP; /** * An expression list. The children are a comma separated list of * expressions. * * @see #LITERAL_NEW * @see #FOR_INIT * @see #FOR_ITERATOR * @see #EXPR * @see #METHOD_CALL * @see #CTOR_CALL * @see #SUPER_CTOR_CALL **/ public static final int ELIST = GeneratedJavaTokenTypes.ELIST; /** * A for loop initializer. This is a child of * <code>LITERAL_FOR</code>. The children of this element may be * a comma separated list of variable declarations, an expression * list, or empty. * * @see #VARIABLE_DEF * @see #ELIST * @see #LITERAL_FOR **/ public static final int FOR_INIT = GeneratedJavaTokenTypes.FOR_INIT; /** * A for loop condition. This is a child of * <code>LITERAL_FOR</code>. The child of this element is an * optional expression. * * @see #EXPR * @see #LITERAL_FOR **/ public static final int FOR_CONDITION = GeneratedJavaTokenTypes.FOR_CONDITION; /** * A for loop iterator. This is a child of * <code>LITERAL_FOR</code>. The child of this element is an * optional expression list. * * @see #ELIST * @see #LITERAL_FOR **/ public static final int FOR_ITERATOR = GeneratedJavaTokenTypes.FOR_ITERATOR; /** * The empty statement. This goes in place of an * <code>SLIST</code> for a <code>for</code> or <code>while</code> * loop body. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.6">Java * Language Specification, &sect;14.6</a> * @see #LITERAL_FOR * @see #LITERAL_WHILE **/ public static final int EMPTY_STAT = GeneratedJavaTokenTypes.EMPTY_STAT; /** * The <code>final</code> keyword. * * @see #MODIFIERS **/ public static final int FINAL = GeneratedJavaTokenTypes.FINAL; /** * The <code>abstract</code> keyword. * * @see #MODIFIERS **/ public static final int ABSTRACT = GeneratedJavaTokenTypes.ABSTRACT; /** * The <code>strictfp</code> keyword. * * @see #MODIFIERS **/ public static final int STRICTFP = GeneratedJavaTokenTypes.STRICTFP; /** * A super constructor call. * * @see #ELIST * @see #RPAREN * @see #SEMI * @see #CTOR_CALL **/ public static final int SUPER_CTOR_CALL = GeneratedJavaTokenTypes.SUPER_CTOR_CALL; /** * A constructor call. * * <p>For example:</p> * <pre> * this(1); * </pre> * <p>parses as:</p> * <pre> * +--CTOR_CALL (this) * | * +--LPAREN (() * +--ELIST * | * +--EXPR * | * +--NUM_INT (1) * +--RPAREN ()) * +--SEMI (;) * </pre> * * @see #ELIST * @see #RPAREN * @see #SEMI * @see #SUPER_CTOR_CALL **/ public static final int CTOR_CALL = GeneratedJavaTokenTypes.CTOR_CALL; /* * * This token does not appear in the tree. * * @see #PACKAGE_DEF **/ //public static final int LITERAL_PACKAGE = // GeneratedJavaTokenTypes.LITERAL_package; /** * The statement terminator (<code>;</code>). Depending on the * context, this make occur as a sibling, a child, or not at all. * * @see #PACKAGE_DEF * @see #IMPORT * @see #SLIST * @see #ARRAY_INIT * @see #LITERAL_FOR **/ public static final int SEMI = GeneratedJavaTokenTypes.SEMI; /* * * This token does not appear in the tree. * * @see #IMPORT **/ // public static final int LITERAL_IMPORT = // GeneratedJavaTokenTypes.LITERAL_import; /* * * This token does not appear in the tree. * * @see #INDEX_OP * @see #ARRAY_DECLARATOR **/ //public static final int LBRACK = GeneratedJavaTokenTypes.LBRACK; /** * The <code>]</code> symbol. * * @see #INDEX_OP * @see #ARRAY_DECLARATOR **/ public static final int RBRACK = GeneratedJavaTokenTypes.RBRACK; /** * The <code>void</code> keyword. * * @see #TYPE **/ public static final int LITERAL_VOID = GeneratedJavaTokenTypes.LITERAL_void; /** * The <code>boolean</code> keyword. * * @see #TYPE **/ public static final int LITERAL_BOOLEAN = GeneratedJavaTokenTypes.LITERAL_boolean; /** * The <code>byte</code> keyword. * * @see #TYPE **/ public static final int LITERAL_BYTE = GeneratedJavaTokenTypes.LITERAL_byte; /** * The <code>char</code> keyword. * * @see #TYPE **/ public static final int LITERAL_CHAR = GeneratedJavaTokenTypes.LITERAL_char; /** * The <code>short</code> keyword. * * @see #TYPE **/ public static final int LITERAL_SHORT = GeneratedJavaTokenTypes.LITERAL_short; /** * The <code>int</code> keyword. * * @see #TYPE **/ public static final int LITERAL_INT = GeneratedJavaTokenTypes.LITERAL_int; /** * The <code>float</code> keyword. * * @see #TYPE **/ public static final int LITERAL_FLOAT = GeneratedJavaTokenTypes.LITERAL_float; /** * The <code>long</code> keyword. * * @see #TYPE **/ public static final int LITERAL_LONG = GeneratedJavaTokenTypes.LITERAL_long; /** * The <code>double</code> keyword. * * @see #TYPE **/ public static final int LITERAL_DOUBLE = GeneratedJavaTokenTypes.LITERAL_double; /** * An identifier. These can be names of types, subpackages, * fields, methods, parameters, and local variables. **/ public static final int IDENT = GeneratedJavaTokenTypes.IDENT; /** * The <code>&#46;</code> (dot) operator. * * @see FullIdent **/ public static final int DOT = GeneratedJavaTokenTypes.DOT; /** * The <code>*</code> (multiplication or wildcard) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.5.2">Java * Language Specification, &sect;7.5.2</a> * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.1">Java * Language Specification, &sect;15.17.1</a> * @see #EXPR * @see #IMPORT **/ public static final int STAR = GeneratedJavaTokenTypes.STAR; /** * The <code>private</code> keyword. * * @see #MODIFIERS **/ public static final int LITERAL_PRIVATE = GeneratedJavaTokenTypes.LITERAL_private; /** * The <code>public</code> keyword. * * @see #MODIFIERS **/ public static final int LITERAL_PUBLIC = GeneratedJavaTokenTypes.LITERAL_public; /** * The <code>protected</code> keyword. * * @see #MODIFIERS **/ public static final int LITERAL_PROTECTED = GeneratedJavaTokenTypes.LITERAL_protected; /** * The <code>static</code> keyword. * * @see #MODIFIERS **/ public static final int LITERAL_STATIC = GeneratedJavaTokenTypes.LITERAL_static; /** * The <code>transient</code> keyword. * * @see #MODIFIERS **/ public static final int LITERAL_TRANSIENT = GeneratedJavaTokenTypes.LITERAL_transient; /** * The <code>native</code> keyword. * * @see #MODIFIERS **/ public static final int LITERAL_NATIVE = GeneratedJavaTokenTypes.LITERAL_native; /** * The <code>synchronized</code> keyword. This may be used as a * modifier of a method or in the definition of a synchronized * block. * * <p>For example:</p> * * <pre> * synchronized(this) * { * x++; * } * </pre> * * <p>parses as:</p> * * <pre> * +--LITERAL_SYNCHRONIZED (synchronized) * | * +--LPAREN (() * +--EXPR * | * +--LITERAL_THIS (this) * +--RPAREN ()) * +--SLIST ({) * | * +--EXPR * | * +--POST_INC (++) * | * +--IDENT (x) * +--SEMI (;) * +--RCURLY (}) * +--RCURLY (}) * </pre> * * @see #MODIFIERS * @see #LPAREN * @see #EXPR * @see #RPAREN * @see #SLIST * @see #RCURLY **/ public static final int LITERAL_SYNCHRONIZED = GeneratedJavaTokenTypes.LITERAL_synchronized; /** * The <code>volatile</code> keyword. * * @see #MODIFIERS **/ public static final int LITERAL_VOLATILE = GeneratedJavaTokenTypes.LITERAL_volatile; /** * The <code>class</code> keyword. This element appears both * as part of a class declaration, and inline to reference a * class object. * * <p>For example:</p> * * <pre> * int.class * </pre> * <p>parses as:</p> * <pre> * +--EXPR * | * +--DOT (.) * | * +--LITERAL_INT (int) * +--LITERAL_CLASS (class) * </pre> * * @see #DOT * @see #IDENT * @see #CLASS_DEF * @see FullIdent **/ public static final int LITERAL_CLASS = GeneratedJavaTokenTypes.LITERAL_class; /* * * This token does not appear in the tree. * * @see #EXTENDS_CLAUSE **/ //public static final int LITERAL_EXTENDS = // GeneratedJavaTokenTypes.LITERAL_extends; /** * The <code>interface</code> keyword. This token appears in * interface definition. * * @see #INTERFACE_DEF **/ public static final int LITERAL_INTERFACE = GeneratedJavaTokenTypes.LITERAL_interface; /** * A left (curly) brace (<code>{</code>). * * @see #OBJBLOCK * @see #ARRAY_INIT * @see #SLIST **/ public static final int LCURLY = GeneratedJavaTokenTypes.LCURLY; /** * A right (curly) brace (<code>}</code>). * * @see #OBJBLOCK * @see #ARRAY_INIT * @see #SLIST **/ public static final int RCURLY = GeneratedJavaTokenTypes.RCURLY; /** * The <code>,</code> (comma) operator. * * @see #ARRAY_INIT * @see #FOR_INIT * @see #FOR_ITERATOR * @see #LITERAL_THROWS * @see #IMPLEMENTS_CLAUSE **/ public static final int COMMA = GeneratedJavaTokenTypes.COMMA; /* * * This token does not appear in the tree. * * @see #IMPLEMENTS_CLAUSE **/ // public static final int LITERAL_IMPLEMENTS = // GeneratedJavaTokenTypes.LITERAL_implements; /** * A left parenthesis (<code>(</code>). * * @see #LITERAL_FOR * @see #LITERAL_NEW * @see #EXPR * @see #LITERAL_SWITCH * @see #LITERAL_CATCH **/ public static final int LPAREN = GeneratedJavaTokenTypes.LPAREN; /** * A right parenthesis (<code>)</code>). * * @see #LITERAL_FOR * @see #LITERAL_NEW * @see #METHOD_CALL * @see #TYPECAST * @see #EXPR * @see #LITERAL_SWITCH * @see #LITERAL_CATCH **/ public static final int RPAREN = GeneratedJavaTokenTypes.RPAREN; /** * The <code>this</code> keyword. * * @see #EXPR * @see #CTOR_CALL **/ public static final int LITERAL_THIS = GeneratedJavaTokenTypes.LITERAL_this; /** * The <code>super</code> keyword. * * @see #EXPR * @see #SUPER_CTOR_CALL **/ public static final int LITERAL_SUPER = GeneratedJavaTokenTypes.LITERAL_super; /** * The <code>=</code> (assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.1">Java * Language Specification, &sect;15.26.1</a> * @see #EXPR **/ public static final int ASSIGN = GeneratedJavaTokenTypes.ASSIGN; /** * The <code>throws</code> keyword. The children are a number of * one or more identifiers separated by commas. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.4">Java * Language Specification, &sect;8.4.4</a> * @see #IDENT * @see #DOT * @see #COMMA * @see #METHOD_DEF * @see #CTOR_DEF * @see FullIdent **/ public static final int LITERAL_THROWS = GeneratedJavaTokenTypes.LITERAL_throws; /** * The <code>:</code> (colon) operator. This will appear as part * of the conditional operator (<code>? :</code>). * * @see #QUESTION * @see #LABELED_STAT * @see #CASE_GROUP **/ public static final int COLON = GeneratedJavaTokenTypes.COLON; /** * The <code>::</code> (double colon) operator. * It is part of Java 8 syntax that is used for method reference. * @see #METHOD_REF */ public static final int DOUBLE_COLON = GeneratedJavaTokenTypes.DOUBLE_COLON; /** * The <code>if</code> keyword. * * <p>For example:</p> * <pre> * if(optimistic) * { * message = "half full"; * } * else * { * message = "half empty"; * } * </pre> * <p>parses as:</p> * <pre> * +--LITERAL_IF (if) * | * +--LPAREN (() * +--EXPR * | * +--IDENT (optimistic) * +--RPAREN ()) * +--SLIST ({) * | * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (message) * +--STRING_LITERAL ("half full") * +--SEMI (;) * +--RCURLY (}) * +--LITERAL_ELSE (else) * | * +--SLIST ({) * | * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (message) * +--STRING_LITERAL ("half empty") * +--SEMI (;) * +--RCURLY (}) * </pre> * * @see #LPAREN * @see #EXPR * @see #RPAREN * @see #SLIST * @see #EMPTY_STAT * @see #LITERAL_ELSE **/ public static final int LITERAL_IF = GeneratedJavaTokenTypes.LITERAL_if; /** * The <code>for</code> keyword. The children are <code>(</code>, * an initializer, a condition, an iterator, a <code>)</code> and * either a statement list, a single expression, or an empty * statement. * * <p>For example:</p> * <pre> * for(int i = 0, n = myArray.length; i &lt; n; i++) * { * } * </pre> * * <p>parses as:</p> * <pre> * +--LITERAL_FOR (for) * | * +--LPAREN (() * +--FOR_INIT * | * +--VARIABLE_DEF * | * +--MODIFIERS * +--TYPE * | * +--LITERAL_INT (int) * +--IDENT (i) * +--ASSIGN (=) * | * +--EXPR * | * +--NUM_INT (0) * +--COMMA (,) * +--VARIABLE_DEF * | * +--MODIFIERS * +--TYPE * | * +--LITERAL_INT (int) * +--IDENT (n) * +--ASSIGN (=) * | * +--EXPR * | * +--DOT (.) * | * +--IDENT (myArray) * +--IDENT (length) * +--SEMI (;) * +--FOR_CONDITION * | * +--EXPR * | * +--LT (&lt;) * | * +--IDENT (i) * +--IDENT (n) * +--SEMI (;) * +--FOR_ITERATOR * | * +--ELIST * | * +--EXPR * | * +--POST_INC (++) * | * +--IDENT (i) * +--RPAREN ()) * +--SLIST ({) * | * +--RCURLY (}) * </pre> * * @see #LPAREN * @see #FOR_INIT * @see #SEMI * @see #FOR_CONDITION * @see #FOR_ITERATOR * @see #RPAREN * @see #SLIST * @see #EMPTY_STAT * @see #EXPR **/ public static final int LITERAL_FOR = GeneratedJavaTokenTypes.LITERAL_for; /** * The <code>while</code> keyword. * * <p>For example:</p> * <pre> * while(line != null) * { * process(line); * line = in.readLine(); * } * </pre> * <p>parses as:</p> * <pre> * +--LITERAL_WHILE (while) * | * +--LPAREN (() * +--EXPR * | * +--NOT_EQUAL (!=) * | * +--IDENT (line) * +--LITERAL_NULL (null) * +--RPAREN ()) * +--SLIST ({) * | * +--EXPR * | * +--METHOD_CALL (() * | * +--IDENT (process) * +--ELIST * | * +--EXPR * | * +--IDENT (line) * +--RPAREN ()) * +--SEMI (;) * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (line) * +--METHOD_CALL (() * | * +--DOT (.) * | * +--IDENT (in) * +--IDENT (readLine) * +--ELIST * +--RPAREN ()) * +--SEMI (;) * +--RCURLY (}) * </pre> **/ public static final int LITERAL_WHILE = GeneratedJavaTokenTypes.LITERAL_while; /** * The <code>do</code> keyword. Note the the while token does not * appear as part of the do-while construct. * * <p>For example:</p> * <pre> * do * { * x = rand.nextInt(10); * } * while(x &lt; 5); * </pre> * <p>parses as:</p> * <pre> * +--LITERAL_DO (do) * | * +--SLIST ({) * | * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (x) * +--METHOD_CALL (() * | * +--DOT (.) * | * +--IDENT (rand) * +--IDENT (nextInt) * +--ELIST * | * +--EXPR * | * +--NUM_INT (10) * +--RPAREN ()) * +--SEMI (;) * +--RCURLY (}) * +--LPAREN (() * +--EXPR * | * +--LT (&lt;) * | * +--IDENT (x) * +--NUM_INT (5) * +--RPAREN ()) * +--SEMI (;) * </pre> * * @see #SLIST * @see #EXPR * @see #EMPTY_STAT * @see #LPAREN * @see #RPAREN * @see #SEMI **/ public static final int LITERAL_DO = GeneratedJavaTokenTypes.LITERAL_do; /** * Literal <code>while</code> in do-while loop. * @see #LITERAL_DO */ public static final int DO_WHILE = GeneratedJavaTokenTypes.DO_WHILE; /** * The <code>break</code> keyword. The first child is an optional * identifier and the last child is a semicolon. * * @see #IDENT * @see #SEMI * @see #SLIST **/ public static final int LITERAL_BREAK = GeneratedJavaTokenTypes.LITERAL_break; /** * The <code>continue</code> keyword. The first child is an * optional identifier and the last child is a semicolon. * * @see #IDENT * @see #SEMI * @see #SLIST **/ public static final int LITERAL_CONTINUE = GeneratedJavaTokenTypes.LITERAL_continue; /** * The <code>return</code> keyword. The first child is an * optional expression for the return value. The last child is a * semi colon. * * @see #EXPR * @see #SEMI * @see #SLIST **/ public static final int LITERAL_RETURN = GeneratedJavaTokenTypes.LITERAL_return; /** * The <code>switch</code> keyword. * * <p>For example:</p> * <pre> * switch(type) * { * case 0: * background = Color.blue; * break; * case 1: * background = Color.red; * break; * default: * background = Color.green; * break; * } * </pre> * <p>parses as:</p> * <pre> * +--LITERAL_SWITCH (switch) * | * +--LPAREN (() * +--EXPR * | * +--IDENT (type) * +--RPAREN ()) * +--LCURLY ({) * +--CASE_GROUP * | * +--LITERAL_CASE (case) * | * +--EXPR * | * +--NUM_INT (0) * +--SLIST * | * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (background) * +--DOT (.) * | * +--IDENT (Color) * +--IDENT (blue) * +--SEMI (;) * +--LITERAL_BREAK (break) * | * +--SEMI (;) * +--CASE_GROUP * | * +--LITERAL_CASE (case) * | * +--EXPR * | * +--NUM_INT (1) * +--SLIST * | * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (background) * +--DOT (.) * | * +--IDENT (Color) * +--IDENT (red) * +--SEMI (;) * +--LITERAL_BREAK (break) * | * +--SEMI (;) * +--CASE_GROUP * | * +--LITERAL_DEFAULT (default) * +--SLIST * | * +--EXPR * | * +--ASSIGN (=) * | * +--IDENT (background) * +--DOT (.) * | * +--IDENT (Color) * +--IDENT (green) * +--SEMI (;) * +--LITERAL_BREAK (break) * | * +--SEMI (;) * +--RCURLY (}) * </pre> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.10">Java * Language Specification, &sect;14.10</a> * @see #LPAREN * @see #EXPR * @see #RPAREN * @see #LCURLY * @see #CASE_GROUP * @see #RCURLY * @see #SLIST **/ public static final int LITERAL_SWITCH = GeneratedJavaTokenTypes.LITERAL_switch; /** * The <code>throw</code> keyword. The first child is an * expression that evaluates to a <code>Throwable</code> instance. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.17">Java * Language Specification, &sect;14.17</a> * @see #SLIST * @see #EXPR **/ public static final int LITERAL_THROW = GeneratedJavaTokenTypes.LITERAL_throw; /** * The <code>else</code> keyword. This appears as a child of an * <code>if</code> statement. * * @see #SLIST * @see #EXPR * @see #EMPTY_STAT * @see #LITERAL_IF **/ public static final int LITERAL_ELSE = GeneratedJavaTokenTypes.LITERAL_else; /** * The <code>case</code> keyword. The first child is a constant * expression that evaluates to a integer. * * @see #CASE_GROUP * @see #EXPR **/ public static final int LITERAL_CASE = GeneratedJavaTokenTypes.LITERAL_case; /** * The <code>default</code> keyword. This element has no * children. * * @see #CASE_GROUP * @see #MODIFIERS **/ public static final int LITERAL_DEFAULT = GeneratedJavaTokenTypes.LITERAL_default; /** * The <code>try</code> keyword. The children are a statement * list, zero or more catch blocks and then an optional finally * block. * * <p>For example:</p> * <pre> * try * { * FileReader in = new FileReader("abc.txt"); * } * catch(IOException ioe) * { * } * finally * { * } * </pre> * <p>parses as:</p> * <pre> * +--LITERAL_TRY (try) * | * +--SLIST ({) * | * +--VARIABLE_DEF * | * +--MODIFIERS * +--TYPE * | * +--IDENT (FileReader) * +--IDENT (in) * +--ASSIGN (=) * | * +--EXPR * | * +--LITERAL_NEW (new) * | * +--IDENT (FileReader) * +--LPAREN (() * +--ELIST * | * +--EXPR * | * +--STRING_LITERAL ("abc.txt") * +--RPAREN ()) * +--SEMI (;) * +--RCURLY (}) * +--LITERAL_CATCH (catch) * | * +--LPAREN (() * +--PARAMETER_DEF * | * +--MODIFIERS * +--TYPE * | * +--IDENT (IOException) * +--IDENT (ioe) * +--RPAREN ()) * +--SLIST ({) * | * +--RCURLY (}) * +--LITERAL_FINALLY (finally) * | * +--SLIST ({) * | * +--RCURLY (}) * +--RCURLY (}) * </pre> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.19">Java * Language Specification, &sect;14.19</a> * @see #SLIST * @see #LITERAL_CATCH * @see #LITERAL_FINALLY **/ public static final int LITERAL_TRY = GeneratedJavaTokenTypes.LITERAL_try; /** * Java 7 try-with-resources construct. * * <p>For example:</p> * <pre> * try (Foo foo = new Foo(); Bar bar = new Bar()) { } * </pre> * <p>parses as:</p> * <pre> * +--LITERAL_TRY (try) * | * +--RESOURCE_SPECIFICATION * | * +--LPAREN (() * +--RESOURCES * | * +--RESOURCE * | * +--MODIFIERS * +--TYPE * | * +--IDENT (Foo) * +--IDENT (foo) * +--ASSIGN (=) * +--EXPR * | * +--LITERAL_NEW (new) * | * +--IDENT (Foo) * +--LPAREN (() * +--ELIST * +--RPAREN ()) * +--SEMI (;) * +--RESOURCE * | * +--MODIFIERS * +--TYPE * | * +--IDENT (Bar) * +--IDENT (bar) * +--ASSIGN (=) * +--EXPR * | * +--LITERAL_NEW (new) * | * +--IDENT (Bar) * +--LPAREN (() * +--ELIST * +--RPAREN ()) * +--RPAREN ()) * +--SLIST ({) * +--RCURLY (}) * </pre> * * @see #LPAREN * @see #RESOURCES * @see #RESOURCE * @see #SEMI * @see #RPAREN * @see #LITERAL_TRY **/ public static final int RESOURCE_SPECIFICATION = GeneratedJavaTokenTypes.RESOURCE_SPECIFICATION; /** * Java 7 try-with-resources construct. * * @see #RESOURCE_SPECIFICATION **/ public static final int RESOURCES = GeneratedJavaTokenTypes.RESOURCES; /** * Java 7 try-with-resources construct. * * @see #RESOURCE_SPECIFICATION **/ public static final int RESOURCE = GeneratedJavaTokenTypes.RESOURCE; /** * The <code>catch</code> keyword. * * @see #LPAREN * @see #PARAMETER_DEF * @see #RPAREN * @see #SLIST * @see #LITERAL_TRY **/ public static final int LITERAL_CATCH = GeneratedJavaTokenTypes.LITERAL_catch; /** * The <code>finally</code> keyword. * * @see #SLIST * @see #LITERAL_TRY **/ public static final int LITERAL_FINALLY = GeneratedJavaTokenTypes.LITERAL_finally; /** * The <code>+=</code> (addition assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int PLUS_ASSIGN = GeneratedJavaTokenTypes.PLUS_ASSIGN; /** * The <code>-=</code> (subtraction assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int MINUS_ASSIGN = GeneratedJavaTokenTypes.MINUS_ASSIGN; /** * The <code>*=</code> (multiplication assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int STAR_ASSIGN = GeneratedJavaTokenTypes.STAR_ASSIGN; /** * The <code>/=</code> (division assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int DIV_ASSIGN = GeneratedJavaTokenTypes.DIV_ASSIGN; /** * The <code>%=</code> (remainder assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int MOD_ASSIGN = GeneratedJavaTokenTypes.MOD_ASSIGN; /** * The <code>&gt;&gt;=</code> (signed right shift assignment) * operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int SR_ASSIGN = GeneratedJavaTokenTypes.SR_ASSIGN; /** * The <code>&gt;&gt;&gt;=</code> (unsigned right shift assignment) * operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int BSR_ASSIGN = GeneratedJavaTokenTypes.BSR_ASSIGN; /** * The <code>&lt;&lt;=</code> (left shift assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int SL_ASSIGN = GeneratedJavaTokenTypes.SL_ASSIGN; /** * The <code>&amp;=</code> (bitwise AND assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int BAND_ASSIGN = GeneratedJavaTokenTypes.BAND_ASSIGN; /** * The <code>^=</code> (bitwise exclusive OR assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int BXOR_ASSIGN = GeneratedJavaTokenTypes.BXOR_ASSIGN; /** * The <code>|=</code> (bitwise OR assignment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2">Java * Language Specification, &sect;15.26.2</a> * @see #EXPR **/ public static final int BOR_ASSIGN = GeneratedJavaTokenTypes.BOR_ASSIGN; /** * The <code>&#63;</code> (conditional) operator. Technically, * the colon is also part of this operator, but it appears as a * separate token. * * <p>For example:</p> * <pre> * (quantity == 1) ? "": "s" * </pre> * <p> * parses as: * </p> * <pre> * +--QUESTION (?) * | * +--LPAREN (() * +--EQUAL (==) * | * +--IDENT (quantity) * +--NUM_INT (1) * +--RPAREN ()) * +--STRING_LITERAL ("") * +--COLON (:) * +--STRING_LITERAL ("s") * </pre> * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25">Java * Language Specification, &sect;15.25</a> * @see #EXPR * @see #COLON **/ public static final int QUESTION = GeneratedJavaTokenTypes.QUESTION; /** * The <code>||</code> (conditional OR) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.24">Java * Language Specification, &sect;15.24</a> * @see #EXPR **/ public static final int LOR = GeneratedJavaTokenTypes.LOR; /** * The <code>&amp;&amp;</code> (conditional AND) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.23">Java * Language Specification, &sect;15.23</a> * @see #EXPR **/ public static final int LAND = GeneratedJavaTokenTypes.LAND; /** * The <code>|</code> (bitwise OR) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.22.1">Java * Language Specification, &sect;15.22.1</a> * @see #EXPR **/ public static final int BOR = GeneratedJavaTokenTypes.BOR; /** * The <code>^</code> (bitwise exclusive OR) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.22.1">Java * Language Specification, &sect;15.22.1</a> * @see #EXPR **/ public static final int BXOR = GeneratedJavaTokenTypes.BXOR; /** * The <code>&amp;</code> (bitwise AND) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.22.1">Java * Language Specification, &sect;15.22.1</a> * @see #EXPR **/ public static final int BAND = GeneratedJavaTokenTypes.BAND; /** * The <code>&#33;=</code> (not equal) operator. * * @see #EXPR **/ public static final int NOT_EQUAL = GeneratedJavaTokenTypes.NOT_EQUAL; /** * The <code>==</code> (equal) operator. * * @see #EXPR **/ public static final int EQUAL = GeneratedJavaTokenTypes.EQUAL; /** * The <code>&lt;</code> (less than) operator. * * @see #EXPR **/ public static final int LT = GeneratedJavaTokenTypes.LT; /** * The <code>&gt;</code> (greater than) operator. * * @see #EXPR **/ public static final int GT = GeneratedJavaTokenTypes.GT; /** * The <code>&lt;=</code> (less than or equal) operator. * * @see #EXPR **/ public static final int LE = GeneratedJavaTokenTypes.LE; /** * The <code>&gt;=</code> (greater than or equal) operator. * * @see #EXPR **/ public static final int GE = GeneratedJavaTokenTypes.GE; /** * The <code>instanceof</code> operator. The first child is an * object reference or something that evaluates to an object * reference. The second child is a reference type. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.20.2">Java * Language Specification, &sect;15.20.2</a> * @see #EXPR * @see #METHOD_CALL * @see #IDENT * @see #DOT * @see #TYPE * @see FullIdent **/ public static final int LITERAL_INSTANCEOF = GeneratedJavaTokenTypes.LITERAL_instanceof; /** * The <code>&lt;&lt;</code> (shift left) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19">Java * Language Specification, &sect;15.19</a> * @see #EXPR **/ public static final int SL = GeneratedJavaTokenTypes.SL; /** * The <code>&gt;&gt;</code> (signed shift right) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19">Java * Language Specification, &sect;15.19</a> * @see #EXPR **/ public static final int SR = GeneratedJavaTokenTypes.SR; /** * The <code>&gt;&gt;&gt;</code> (unsigned shift right) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19">Java * Language Specification, &sect;15.19</a> * @see #EXPR **/ public static final int BSR = GeneratedJavaTokenTypes.BSR; /** * The <code>+</code> (addition) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18">Java * Language Specification, &sect;15.18</a> * @see #EXPR **/ public static final int PLUS = GeneratedJavaTokenTypes.PLUS; /** * The <code>-</code> (subtraction) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18">Java * Language Specification, &sect;15.18</a> * @see #EXPR **/ public static final int MINUS = GeneratedJavaTokenTypes.MINUS; /** * The <code>/</code> (division) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.2">Java * Language Specification, &sect;15.17.2</a> * @see #EXPR **/ public static final int DIV = GeneratedJavaTokenTypes.DIV; /** * The <code>%</code> (remainder) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.3">Java * Language Specification, &sect;15.17.3</a> * @see #EXPR **/ public static final int MOD = GeneratedJavaTokenTypes.MOD; /** * The <code>++</code> (prefix increment) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.1">Java * Language Specification, &sect;15.15.1</a> * @see #EXPR * @see #POST_INC **/ public static final int INC = GeneratedJavaTokenTypes.INC; /** * The <code>--</code> (prefix decrement) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.2">Java * Language Specification, &sect;15.15.2</a> * @see #EXPR * @see #POST_DEC **/ public static final int DEC = GeneratedJavaTokenTypes.DEC; /** * The <code>~</code> (bitwise complement) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.5">Java * Language Specification, &sect;15.15.5</a> * @see #EXPR **/ public static final int BNOT = GeneratedJavaTokenTypes.BNOT; /** * The <code>&#33;</code> (logical complement) operator. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.6">Java * Language Specification, &sect;15.15.6</a> * @see #EXPR **/ public static final int LNOT = GeneratedJavaTokenTypes.LNOT; /** * The <code>true</code> keyword. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.3">Java * Language Specification, &sect;3.10.3</a> * @see #EXPR * @see #LITERAL_FALSE **/ public static final int LITERAL_TRUE = GeneratedJavaTokenTypes.LITERAL_true; /** * The <code>false</code> keyword. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.3">Java * Language Specification, &sect;3.10.3</a> * @see #EXPR * @see #LITERAL_TRUE **/ public static final int LITERAL_FALSE = GeneratedJavaTokenTypes.LITERAL_false; /** * The <code>null</code> keyword. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.7">Java * Language Specification, &sect;3.10.7</a> * @see #EXPR **/ public static final int LITERAL_NULL = GeneratedJavaTokenTypes.LITERAL_null; /** * The <code>new</code> keyword. This element is used to define * new instances of objects, new arrays, and new anonymous inner * classes. * * <p>For example:</p> * * <pre> * new ArrayList(50) * </pre> * * <p>parses as:</p> * <pre> * +--LITERAL_NEW (new) * | * +--IDENT (ArrayList) * +--LPAREN (() * +--ELIST * | * +--EXPR * | * +--NUM_INT (50) * +--RPAREN ()) * </pre> * * <p>For example:</p> * <pre> * new float[] * { * 3.0f, * 4.0f * }; * </pre> * * <p>parses as:</p> * <pre> * +--LITERAL_NEW (new) * | * +--LITERAL_FLOAT (float) * +--ARRAY_DECLARATOR ([) * +--ARRAY_INIT ({) * | * +--EXPR * | * +--NUM_FLOAT (3.0f) * +--COMMA (,) * +--EXPR * | * +--NUM_FLOAT (4.0f) * +--RCURLY (}) * </pre> * * <p>For example:</p> * <pre> * new FilenameFilter() * { * public boolean accept(File dir, String name) * { * return name.endsWith(".java"); * } * } * </pre> * * <p>parses as:</p> * <pre> * +--LITERAL_NEW (new) * | * +--IDENT (FilenameFilter) * +--LPAREN (() * +--ELIST * +--RPAREN ()) * +--OBJBLOCK * | * +--LCURLY ({) * +--METHOD_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--TYPE * | * +--LITERAL_BOOLEAN (boolean) * +--IDENT (accept) * +--PARAMETERS * | * +--PARAMETER_DEF * | * +--MODIFIERS * +--TYPE * | * +--IDENT (File) * +--IDENT (dir) * +--COMMA (,) * +--PARAMETER_DEF * | * +--MODIFIERS * +--TYPE * | * +--IDENT (String) * +--IDENT (name) * +--SLIST ({) * | * +--LITERAL_RETURN (return) * | * +--EXPR * | * +--METHOD_CALL (() * | * +--DOT (.) * | * +--IDENT (name) * +--IDENT (endsWith) * +--ELIST * | * +--EXPR * | * +--STRING_LITERAL (".java") * +--RPAREN ()) * +--SEMI (;) * +--RCURLY (}) * +--RCURLY (}) * </pre> * * @see #IDENT * @see #DOT * @see #LPAREN * @see #ELIST * @see #RPAREN * @see #OBJBLOCK * @see #ARRAY_INIT * @see FullIdent **/ public static final int LITERAL_NEW = GeneratedJavaTokenTypes.LITERAL_new; /** * An integer literal. These may be specified in decimal, * hexadecimal, or octal form. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.1">Java * Language Specification, &sect;3.10.1</a> * @see #EXPR * @see #NUM_LONG **/ public static final int NUM_INT = GeneratedJavaTokenTypes.NUM_INT; /** * A character literal. This is a (possibly escaped) character * enclosed in single quotes. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.4">Java * Language Specification, &sect;3.10.4</a> * @see #EXPR **/ public static final int CHAR_LITERAL = GeneratedJavaTokenTypes.CHAR_LITERAL; /** * A string literal. This is a sequence of (possibly escaped) * characters enclosed in double quotes. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.5">Java * Language Specification, &sect;3.10.5</a> * @see #EXPR **/ public static final int STRING_LITERAL = GeneratedJavaTokenTypes.STRING_LITERAL; /** * A single precision floating point literal. This is a floating * point number with an <code>F</code> or <code>f</code> suffix. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.2">Java * Language Specification, &sect;3.10.2</a> * @see #EXPR * @see #NUM_DOUBLE **/ public static final int NUM_FLOAT = GeneratedJavaTokenTypes.NUM_FLOAT; /** * A long integer literal. These are almost the same as integer * literals, but they have an <code>L</code> or <code>l</code> * (ell) suffix. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.1">Java * Language Specification, &sect;3.10.1</a> * @see #EXPR * @see #NUM_INT **/ public static final int NUM_LONG = GeneratedJavaTokenTypes.NUM_LONG; /** * A double precision floating point literal. This is a floating * point number with an optional <code>D</code> or <code>d</code> * suffix. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.2">Java * Language Specification, &sect;3.10.2</a> * @see #EXPR * @see #NUM_FLOAT **/ public static final int NUM_DOUBLE = GeneratedJavaTokenTypes.NUM_DOUBLE; /* * * This token does not appear in the tree. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.6">Java * Language Specification, &sect;3.6</a> * @see FileContents **/ //public static final int WS = GeneratedJavaTokenTypes.WS; /* * * This token does not appear in the tree. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.7">Java * Language Specification, &sect;3.7</a> * @see FileContents **/ //public static final int SL_COMMENT = GeneratedJavaTokenTypes.SL_COMMENT; /* * * This token does not appear in the tree. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.7">Java * Language Specification, &sect;3.7</a> * @see FileContents **/ //public static final int ML_COMMENT = GeneratedJavaTokenTypes.ML_COMMENT; /* * * This token does not appear in the tree. * * @see <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.6">Java * Language Specification, &sect;3.10.6</a> * @see #CHAR_LITERAL * @see #STRING_LITERAL **/ //public static final int ESC = GeneratedJavaTokenTypes.ESC; /* * * This token does not appear in the tree. * * @see #NUM_INT * @see #NUM_LONG **/ //public static final int HEX_DIGIT = GeneratedJavaTokenTypes.HEX_DIGIT; /* * * This token does not appear in the tree. * * @see #NUM_FLOAT * @see #NUM_DOUBLE **/ //public static final int EXPONENT = GeneratedJavaTokenTypes.EXPONENT; /* * * This token does not appear in the tree. * * @see #NUM_FLOAT * @see #NUM_DOUBLE **/ // public static final int FLOAT_SUFFIX = // GeneratedJavaTokenTypes.FLOAT_SUFFIX; /** * The <code>assert</code> keyword. This is only for Java 1.4 and * later. * * <p>For example:</p> * <pre> * assert(x==4); * </pre> * <p>parses as:</p> * <pre> * +--LITERAL_ASSERT (assert) * | * +--EXPR * | * +--LPAREN (() * +--EQUAL (==) * | * +--IDENT (x) * +--NUM_INT (4) * +--RPAREN ()) * +--SEMI (;) * </pre> **/ public static final int LITERAL_ASSERT = GeneratedJavaTokenTypes.ASSERT; /** * A static import declaration. Static import declarations are optional, * but must appear after the package declaration and before the type * declaration. * * <p>For example:</p> * * <pre> * import static java.io.IOException; * </pre> * * <p>parses as:</p> * * <pre> * +--STATIC_IMPORT (import) * | * +--LITERAL_STATIC * +--DOT (.) * | * +--DOT (.) * | * +--IDENT (java) * +--IDENT (io) * +--IDENT (IOException) * +--SEMI (;) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #LITERAL_STATIC * @see #DOT * @see #IDENT * @see #STAR * @see #SEMI * @see FullIdent **/ public static final int STATIC_IMPORT = GeneratedJavaTokenTypes.STATIC_IMPORT; /** * An enum declaration. Its notable children are * enum constant declarations followed by * any construct that may be expected in a class body. * * <p>For example:</p> * <pre> * public enum MyEnum * implements Serializable * { * FIRST_CONSTANT, * SECOND_CONSTANT; * * public void someMethod() * { * } * } * </pre> * <p>parses as:</p> * <pre> * +--ENUM_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--ENUM (enum) * +--IDENT (MyEnum) * +--EXTENDS_CLAUSE * +--IMPLEMENTS_CLAUSE * | * +--IDENT (Serializable) * +--OBJBLOCK * | * +--LCURLY ({) * +--ENUM_CONSTANT_DEF * | * +--IDENT (FIRST_CONSTANT) * +--COMMA (,) * +--ENUM_CONSTANT_DEF * | * +--IDENT (SECOND_CONSTANT) * +--SEMI (;) * +--METHOD_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--TYPE * | * +--LITERAL_void (void) * +--IDENT (someMethod) * +--LPAREN (() * +--PARAMETERS * +--RPAREN ()) * +--SLIST ({) * | * +--RCURLY (}) * +--RCURLY (}) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #MODIFIERS * @see #ENUM * @see #IDENT * @see #EXTENDS_CLAUSE * @see #IMPLEMENTS_CLAUSE * @see #OBJBLOCK * @see #LITERAL_NEW * @see #ENUM_CONSTANT_DEF **/ public static final int ENUM_DEF = GeneratedJavaTokenTypes.ENUM_DEF; /** * The <code>enum</code> keyword. This element appears * as part of an enum declaration. **/ public static final int ENUM = GeneratedJavaTokenTypes.ENUM; /** * An enum constant declaration. Its notable children are annotations, * arguments and object block akin to an anonymous * inner class' body. * * <p>For example:</p> * <pre> * SOME_CONSTANT(1) * { * public void someMethodOverridenFromMainBody() * { * } * } * </pre> * <p>parses as:</p> * <pre> * +--ENUM_CONSTANT_DEF * | * +--ANNOTATIONS * +--IDENT (SOME_CONSTANT) * +--LPAREN (() * +--ELIST * | * +--EXPR * | * +--NUM_INT (1) * +--RPAREN ()) * +--OBJBLOCK * | * +--LCURLY ({) * | * +--METHOD_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--TYPE * | * +--LITERAL_void (void) * +--IDENT (someMethodOverridenFromMainBody) * +--LPAREN (() * +--PARAMETERS * +--RPAREN ()) * +--SLIST ({) * | * +--RCURLY (}) * +--RCURLY (}) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #ANNOTATIONS * @see #MODIFIERS * @see #IDENT * @see #ELIST * @see #OBJBLOCK **/ public static final int ENUM_CONSTANT_DEF = GeneratedJavaTokenTypes.ENUM_CONSTANT_DEF; /** * A for-each clause. This is a child of * <code>LITERAL_FOR</code>. The children of this element may be * a parameter definition, the colon literal and an expression. * * @see #VARIABLE_DEF * @see #ELIST * @see #LITERAL_FOR **/ public static final int FOR_EACH_CLAUSE = GeneratedJavaTokenTypes.FOR_EACH_CLAUSE; /** * An annotation declaration. The notable children are the name of the * annotation type, annotation field declarations and (constant) fields. * * <p>For example:</p> * <pre> * public @interface MyAnnotation * { * int someValue(); * } * </pre> * <p>parses as:</p> * <pre> * +--ANNOTATION_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--AT (@) * +--LITERAL_INTERFACE (interface) * +--IDENT (MyAnnotation) * +--OBJBLOCK * | * +--LCURLY ({) * +--ANNOTATION_FIELD_DEF * | * +--MODIFIERS * +--TYPE * | * +--LITERAL_INT (int) * +--IDENT (someValue) * +--LPAREN (() * +--RPAREN ()) * +--SEMI (;) * +--RCURLY (}) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #MODIFIERS * @see #LITERAL_INTERFACE * @see #IDENT * @see #OBJBLOCK * @see #ANNOTATION_FIELD_DEF **/ public static final int ANNOTATION_DEF = GeneratedJavaTokenTypes.ANNOTATION_DEF; /** * An annotation field declaration. The notable children are modifiers, * field type, field name and an optional default value (a conditional * compile-time constant expression). Default values may also by * annotations. * * <p>For example:</p> * * <pre> * String someField() default "Hello world"; * </pre> * * <p>parses as:</p> * * <pre> * +--ANNOTATION_FIELD_DEF * | * +--MODIFIERS * +--TYPE * | * +--IDENT (String) * +--IDENT (someField) * +--LPAREN (() * +--RPAREN ()) * +--LITERAL_DEFAULT (default) * +--STRING_LITERAL ("Hello world") * +--SEMI (;) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #MODIFIERS * @see #TYPE * @see #LITERAL_DEFAULT */ public static final int ANNOTATION_FIELD_DEF = GeneratedJavaTokenTypes.ANNOTATION_FIELD_DEF; // note: &#064; is the html escape for '@', // used here to avoid confusing the javadoc tool /** * A collection of annotations on a package or enum constant. * A collections of annotations will only occur on these nodes * as all other nodes that may be qualified with an annotation can * be qualified with any other modifier and hence these annotations * would be contained in a {@link #MODIFIERS} node. * * <p>For example:</p> * * <pre> * &#064;MyAnnotation package blah; * </pre> * * <p>parses as:</p> * * <pre> * +--PACKAGE_DEF (package) * | * +--ANNOTATIONS * | * +--ANNOTATION * | * +--AT (&#064;) * +--IDENT (MyAnnotation) * +--IDENT (blah) * +--SEMI (;) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #ANNOTATION * @see #AT * @see #IDENT */ public static final int ANNOTATIONS = GeneratedJavaTokenTypes.ANNOTATIONS; // note: &#064; is the html escape for '@', // used here to avoid confusing the javadoc tool /** * An annotation of a package, type, field, parameter or variable. * An annotation may occur anywhere modifiers occur (it is a * type of modifier) and may also occur prior to a package definition. * The notable children are: The annotation name and either a single * default annotation value or a sequence of name value pairs. * Annotation values may also be annotations themselves. * * <p>For example:</p> * * <pre> * &#064;MyAnnotation(someField1 = "Hello", * someField2 = &#064;SomeOtherAnnotation) * </pre> * * <p>parses as:</p> * * <pre> * +--ANNOTATION * | * +--AT (&#064;) * +--IDENT (MyAnnotation) * +--LPAREN (() * +--ANNOTATION_MEMBER_VALUE_PAIR * | * +--IDENT (someField1) * +--ASSIGN (=) * +--ANNOTATION * | * +--AT (&#064;) * +--IDENT (SomeOtherAnnotation) * +--ANNOTATION_MEMBER_VALUE_PAIR * | * +--IDENT (someField2) * +--ASSIGN (=) * +--STRING_LITERAL ("Hello") * +--RPAREN ()) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #MODIFIERS * @see #IDENT * @see #ANNOTATION_MEMBER_VALUE_PAIR */ public static final int ANNOTATION = GeneratedJavaTokenTypes.ANNOTATION; /** * An initialisation of an annotation member with a value. * Its children are the name of the member, the assignment literal * and the (compile-time constant conditional expression) value. * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #ANNOTATION * @see #IDENT */ public static final int ANNOTATION_MEMBER_VALUE_PAIR = GeneratedJavaTokenTypes.ANNOTATION_MEMBER_VALUE_PAIR; /** * An annotation array member initialisation. * Initializers can not be nested. * Am initializer may be present as a default to a annotation * member, as the single default value to an annotation * (e.g. @Annotation({1,2})) or as the value of an annotation * member value pair. * * <p>For example:</p> * * <pre> * { 1, 2 } * </pre> * * <p>parses as:</p> * * <pre> * +--ANNOTATION_ARRAY_INIT ({) * | * +--NUM_INT (1) * +--COMMA (,) * +--NUM_INT (2) * +--RCURLY (}) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> * @see #ANNOTATION * @see #IDENT * @see #ANNOTATION_MEMBER_VALUE_PAIR */ public static final int ANNOTATION_ARRAY_INIT = GeneratedJavaTokenTypes.ANNOTATION_ARRAY_INIT; /** * A list of type parameters to a class, interface or * method definition. Children are LT, at least one * TYPE_PARAMETER, zero or more of: a COMMAs followed by a single * TYPE_PARAMETER and a final GT. * * <p>For example:</p> * * <pre> * public class Blah&lt;A, B&gt; * { * } * </pre> * * <p>parses as:</p> * * <pre> * +--CLASS_DEF ({) * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--LITERAL_CLASS (class) * +--IDENT (Blah) * +--TYPE_PARAMETERS * | * +--GENERIC_START (&lt;) * +--TYPE_PARAMETER * | * +--IDENT (A) * +--COMMA (,) * +--TYPE_PARAMETER * | * +--IDENT (B) * +--GENERIC_END (&gt;) * +--OBJBLOCK * | * +--LCURLY ({) * +--NUM_INT (1) * +--COMMA (,) * +--NUM_INT (2) * +--RCURLY (}) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=14"> * JSR14</a> * @see #GENERIC_START * @see #GENERIC_END * @see #TYPE_PARAMETER * @see #COMMA */ public static final int TYPE_PARAMETERS = GeneratedJavaTokenTypes.TYPE_PARAMETERS; /** * A type parameter to a class, interface or method definition. * Children are the type name and an optional TYPE_UPPER_BOUNDS. * * <p>For example:</p> * * <pre> * A extends Collection * </pre> * * <p>parses as:</p> * * <pre> * +--TYPE_PARAMETER * | * +--IDENT (A) * +--TYPE_UPPER_BOUNDS * | * +--IDENT (Collection) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=14"> * JSR14</a> * @see #IDENT * @see #WILDCARD_TYPE * @see #TYPE_UPPER_BOUNDS */ public static final int TYPE_PARAMETER = GeneratedJavaTokenTypes.TYPE_PARAMETER; /** * A list of type arguments to a type reference or * a method/ctor invocation. Children are GENERIC_START, at least one * TYPE_ARGUMENT, zero or more of a COMMAs followed by a single * TYPE_ARGUMENT, and a final GENERIC_END. * * <p>For example:</p> * * <pre> * public Collection&lt;?&gt; a; * </pre> * * <p>parses as:</p> * * <pre> * +--VARIABLE_DEF * | * +--MODIFIERS * | * +--LITERAL_PUBLIC (public) * +--TYPE * | * +--IDENT (Collection) * | * +--TYPE_ARGUMENTS * | * +--GENERIC_START (&lt;) * +--TYPE_ARGUMENT * | * +--WILDCARD_TYPE (?) * +--GENERIC_END (&gt;) * +--IDENT (a) * +--SEMI (;) * </pre> * * @see #GENERIC_START * @see #GENERIC_END * @see #TYPE_ARGUMENT * @see #COMMA */ public static final int TYPE_ARGUMENTS = GeneratedJavaTokenTypes.TYPE_ARGUMENTS; /** * A type arguments to a type reference or a method/ctor invocation. * Children are either: type name or wildcard type with possible type * upper or lower bounds. * * <p>For example:</p> * * <pre> * ? super List * </pre> * * <p>parses as:</p> * * <pre> * +--TYPE_ARGUMENT * | * +--WILDCARD_TYPE (?) * +--TYPE_LOWER_BOUNDS * | * +--IDENT (List) * </pre> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=14"> * JSR14</a> * @see #WILDCARD_TYPE * @see #TYPE_UPPER_BOUNDS * @see #TYPE_LOWER_BOUNDS */ public static final int TYPE_ARGUMENT = GeneratedJavaTokenTypes.TYPE_ARGUMENT; /** * The type that refers to all types. This node has no children. * * @see <a href="http://www.jcp.org/en/jsr/detail?id=14"> * JSR14</a> * @see #TYPE_ARGUMENT * @see #TYPE_UPPER_BOUNDS * @see #TYPE_LOWER_BOUNDS */ public static final int WILDCARD_TYPE = GeneratedJavaTokenTypes.WILDCARD_TYPE; /** * An upper bounds on a wildcard type argument or type parameter. * This node has one child - the type that is being used for * the bounding. * * @see <a href="http://www.jcp.org/en/jsr/detail?id=14"> * JSR14</a> * @see #TYPE_PARAMETER * @see #TYPE_ARGUMENT * @see #WILDCARD_TYPE */ public static final int TYPE_UPPER_BOUNDS = GeneratedJavaTokenTypes.TYPE_UPPER_BOUNDS; /** * A lower bounds on a wildcard type argument. This node has one child * - the type that is being used for the bounding. * * @see <a href="http://www.jcp.org/en/jsr/detail?id=14"> * JSR14</a> * @see #TYPE_ARGUMENT * @see #WILDCARD_TYPE */ public static final int TYPE_LOWER_BOUNDS = GeneratedJavaTokenTypes.TYPE_LOWER_BOUNDS; /** * An 'at' symbol - signifying an annotation instance or the prefix * to the interface literal signifying the definition of an annotation * declaration. * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> */ public static final int AT = GeneratedJavaTokenTypes.AT; /** * A triple dot for variable-length parameters. This token only ever occurs * in a parameter declaration immediately after the type of the parameter. * * @see <a href="http://www.jcp.org/en/jsr/detail?id=201"> * JSR201</a> */ public static final int ELLIPSIS = GeneratedJavaTokenTypes.ELLIPSIS; /** * '&amp;' symbol when used in a generic upper or lower bounds constrain * e.g. {@code Comparable&lt;<? extends Serializable, CharSequence>}. */ public static final int TYPE_EXTENSION_AND = GeneratedJavaTokenTypes.TYPE_EXTENSION_AND; /** * '&lt;' symbol signifying the start of type arguments or type * parameters. */ public static final int GENERIC_START = GeneratedJavaTokenTypes.GENERIC_START; /** * '&gt;' symbol signifying the end of type arguments or type parameters. */ public static final int GENERIC_END = GeneratedJavaTokenTypes.GENERIC_END; /** * Special lambda symbol '-&gt;'. */ public static final int LAMBDA = GeneratedJavaTokenTypes.LAMBDA; /** * Begining of single line comment: '//'. * * <pre> * +--SINLE_LINE_COMMENT * | * +--COMMENT_CONTENT * </pre> */ public static final int SINGLE_LINE_COMMENT = GeneratedJavaTokenTypes.SINGLE_LINE_COMMENT; /** * Begining of block comment: '/*'. * * <pre> * +--BLOCK_COMMENT_BEGIN * | * +--COMMENT_CONTENT * +--BLOCK_COMMENT_END * </pre> */ public static final int BLOCK_COMMENT_BEGIN = GeneratedJavaTokenTypes.BLOCK_COMMENT_BEGIN; /** * End of block comment: '* /'. * * <pre> * +--BLOCK_COMMENT_BEGIN * | * +--COMMENT_CONTENT * +--BLOCK_COMMENT_END * </pre> */ public static final int BLOCK_COMMENT_END = GeneratedJavaTokenTypes.BLOCK_COMMENT_END; /** * Text of single-line or block comment. * *<pre> * +--SINLE_LINE_COMMENT * | * +--COMMENT_CONTENT * </pre> * * <pre> * +--BLOCK_COMMENT_BEGIN * | * +--COMMENT_CONTENT * +--BLOCK_COMMENT_END * </pre> */ public static final int COMMENT_CONTENT = GeneratedJavaTokenTypes.COMMENT_CONTENT; //////////////////////////////////////////////////////////////////////// // The interesting code goes here //////////////////////////////////////////////////////////////////////// /** maps from a token name to value */ private static final ImmutableMap<String, Integer> TOKEN_NAME_TO_VALUE; /** maps from a token value to name */ private static final String[] TOKEN_VALUE_TO_NAME; // initialise the constants static { final ImmutableMap.Builder<String, Integer> builder = ImmutableMap.builder(); final Field[] fields = TokenTypes.class.getDeclaredFields(); String[] tempTokenValueToName = new String[0]; for (final Field f : fields) { // Only process the int declarations. if (f.getType() != Integer.TYPE) { continue; } final String name = f.getName(); try { final int tokenValue = f.getInt(name); builder.put(name, tokenValue); if (tokenValue > tempTokenValueToName.length - 1) { final String[] temp = new String[tokenValue + 1]; System.arraycopy(tempTokenValueToName, 0, temp, 0, tempTokenValueToName.length); tempTokenValueToName = temp; } tempTokenValueToName[tokenValue] = name; } catch (final IllegalArgumentException e) { System.exit(1); } catch (final IllegalAccessException e) { System.exit(1); } } TOKEN_NAME_TO_VALUE = builder.build(); TOKEN_VALUE_TO_NAME = tempTokenValueToName; } /** * Returns the name of a token for a given ID. * @param iD the ID of the token name to get * @return a token name */ public static String getTokenName(int iD) { if (iD > TOKEN_VALUE_TO_NAME.length - 1) { throw new IllegalArgumentException("given id " + iD); } final String name = TOKEN_VALUE_TO_NAME[iD]; if (name == null) { throw new IllegalArgumentException("given id " + iD); } return name; } /** * Returns the ID of a token for a given name. * @param name the name of the token ID to get * @return a token ID */ public static int getTokenId(String name) { final Integer id = TOKEN_NAME_TO_VALUE.get(name); if (id == null) { throw new IllegalArgumentException("given name " + name); } return id.intValue(); } /** * Returns the short description of a token for a given name. * @param name the name of the token ID to get * @return a short description */ public static String getShortDescription(String name) { if (!TOKEN_NAME_TO_VALUE.containsKey(name)) { throw new IllegalArgumentException("given name " + name); } final String tokentypes = "com.puppycrawl.tools.checkstyle.api.tokentypes"; final ResourceBundle bundle = ResourceBundle.getBundle(tokentypes); return bundle.getString(name); } /** * Is argument comment-related type (SINGLE_LINE_COMMENT, * BLOCK_COMMENT_BEGIN, BLOCK_COMMENT_END, COMMENT_CONTENT). * @param type * token type. * @return true if type is comment-related type. */ public static boolean isCommentType(int type) { return type == TokenTypes.SINGLE_LINE_COMMENT || type == TokenTypes.BLOCK_COMMENT_BEGIN || type == TokenTypes.BLOCK_COMMENT_END || type == TokenTypes.COMMENT_CONTENT; } /** * Is argument comment-related type name (SINGLE_LINE_COMMENT, * BLOCK_COMMENT_BEGIN, BLOCK_COMMENT_END, COMMENT_CONTENT). * @param type * token type name. * @return true if type is comment-related type name. */ public static boolean isCommentType(String type) { return isCommentType(getTokenId(type)); } }
additional fix for #823
src/main/java/com/puppycrawl/tools/checkstyle/api/TokenTypes.java
additional fix for #823
Java
apache-2.0
5a6289fafc1bd6fbc4f4eace6be67e425804051a
0
allotria/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,samthor/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,kdwink/intellij-community,fnouama/intellij-community,vladmm/intellij-community,joewalnes/idea-community,michaelgallacher/intellij-community,consulo/consulo,jagguli/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,fnouama/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,signed/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,fitermay/intellij-community,caot/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,slisson/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,semonte/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,apixandru/intellij-community,FHannes/intellij-community,holmes/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,allotria/intellij-community,suncycheng/intellij-community,joewalnes/idea-community,fitermay/intellij-community,nicolargo/intellij-community,slisson/intellij-community,caot/intellij-community,da1z/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,allotria/intellij-community,blademainer/intellij-community,hurricup/intellij-community,hurricup/intellij-community,petteyg/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,holmes/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,semonte/intellij-community,ibinti/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,fitermay/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,vladmm/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,signed/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,signed/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,jagguli/intellij-community,fitermay/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,consulo/consulo,da1z/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,izonder/intellij-community,FHannes/intellij-community,FHannes/intellij-community,da1z/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,signed/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,caot/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,nicolargo/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,vladmm/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,xfournet/intellij-community,consulo/consulo,muntasirsyed/intellij-community,adedayo/intellij-community,apixandru/intellij-community,supersven/intellij-community,petteyg/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,supersven/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,ibinti/intellij-community,retomerz/intellij-community,adedayo/intellij-community,allotria/intellij-community,kool79/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,dslomov/intellij-community,ryano144/intellij-community,blademainer/intellij-community,retomerz/intellij-community,petteyg/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,gnuhub/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,consulo/consulo,Lekanich/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,supersven/intellij-community,kdwink/intellij-community,ernestp/consulo,retomerz/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,ibinti/intellij-community,vladmm/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,slisson/intellij-community,ahb0327/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,caot/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,da1z/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,consulo/consulo,vladmm/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,signed/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,clumsy/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,supersven/intellij-community,adedayo/intellij-community,caot/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,allotria/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,adedayo/intellij-community,ernestp/consulo,retomerz/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,ryano144/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,hurricup/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,slisson/intellij-community,nicolargo/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,fnouama/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,supersven/intellij-community,xfournet/intellij-community,asedunov/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,clumsy/intellij-community,samthor/intellij-community,consulo/consulo,joewalnes/idea-community,ol-loginov/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,semonte/intellij-community,supersven/intellij-community,da1z/intellij-community,dslomov/intellij-community,jagguli/intellij-community,asedunov/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,petteyg/intellij-community,izonder/intellij-community,hurricup/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,apixandru/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,retomerz/intellij-community,signed/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,fnouama/intellij-community,asedunov/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,diorcety/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,amith01994/intellij-community,semonte/intellij-community,kool79/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,kool79/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,semonte/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,da1z/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,ernestp/consulo,ibinti/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,kool79/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,apixandru/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,suncycheng/intellij-community,caot/intellij-community,da1z/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,semonte/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,fitermay/intellij-community,kdwink/intellij-community,hurricup/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,holmes/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,izonder/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,ernestp/consulo,gnuhub/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,FHannes/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,slisson/intellij-community,supersven/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,kool79/intellij-community,joewalnes/idea-community,pwoodworth/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,ernestp/consulo,supersven/intellij-community,signed/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,holmes/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,slisson/intellij-community,izonder/intellij-community,caot/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,fnouama/intellij-community,robovm/robovm-studio,asedunov/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,fnouama/intellij-community,asedunov/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,da1z/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,ryano144/intellij-community,samthor/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,ernestp/consulo,kdwink/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,blademainer/intellij-community,allotria/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,caot/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,signed/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,fnouama/intellij-community,allotria/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,signed/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,joewalnes/idea-community,vladmm/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,izonder/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,xfournet/intellij-community,samthor/intellij-community,ryano144/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,fitermay/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,amith01994/intellij-community,samthor/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,hurricup/intellij-community,semonte/intellij-community,blademainer/intellij-community,holmes/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.ui; import com.intellij.codeStyle.CodeStyleFacade; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.*; import com.intellij.util.containers.HashMap; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import git4idea.GitUtil; import git4idea.config.GitVcsSettings; import git4idea.config.GitVersion; import git4idea.i18n.GitBundle; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.io.IOException; import java.util.*; import java.util.List; /** * This dialog allows converting the specified files before committing them. */ public class GitConvertFilesDialog extends DialogWrapper { /** * The version when option --stdin was added */ private static final GitVersion CHECK_ATTR_STDIN_SUPPORTED = new GitVersion(1, 6, 1, 0); /** * Do not convert exit code */ public static final int DO_NOT_CONVERT = NEXT_USER_EXIT_CODE; /** * The checkbox used to indicate that dialog should not be shown */ private JCheckBox myDoNotShowCheckBox; /** * The root panel of the dialog */ private JPanel myRootPanel; /** * The tree of files to convert */ private CheckboxTreeBase myFilesToConvert; /** * The root node in the tree */ private CheckedTreeNode myRootNode; /** * The constructor * * @param project the project to which this dialog is related * @param filesToShow the files to show sorted by vcs root */ GitConvertFilesDialog(Project project, Map<VirtualFile, Set<VirtualFile>> filesToShow) { super(project, true); ArrayList<VirtualFile> roots = new ArrayList<VirtualFile>(filesToShow.keySet()); Collections.sort(roots, GitUtil.VIRTUAL_FILE_COMPARATOR); for (VirtualFile root : roots) { CheckedTreeNode vcsRoot = new CheckedTreeNode(root); myRootNode.add(vcsRoot); ArrayList<VirtualFile> files = new ArrayList<VirtualFile>(filesToShow.get(root)); Collections.sort(files, GitUtil.VIRTUAL_FILE_COMPARATOR); for (VirtualFile file : files) { vcsRoot.add(new CheckedTreeNode(file)); } } TreeUtil.expandAll(myFilesToConvert); setTitle(GitBundle.getString("crlf.convert.title")); setOKButtonText(GitBundle.getString("crlf.convert.convert")); init(); } /** * {@inheritDoc} */ @Override protected Action[] createActions() { return new Action[]{getOKAction(), new DoNotConvertAction(), getCancelAction()}; } /** * Create custom UI components */ private void createUIComponents() { myRootNode = new CheckedTreeNode("ROOT"); myFilesToConvert = new CheckboxTree(new FileTreeCellRenderer(), myRootNode) { protected void onNodeStateChanged(CheckedTreeNode node) { VirtualFile[] files = myFilesToConvert.getCheckedNodes(VirtualFile.class, null); setOKActionEnabled(files != null && files.length > 0); super.onNodeStateChanged(node); } }; } /** * {@inheritDoc} */ @Override protected JComponent createCenterPanel() { return myRootPanel; } /** * {@inheritDoc} */ @Override protected String getDimensionServiceKey() { return getClass().getName(); } /** * Check if files need to be converted to other line separator. The method could be invoked from non-UI thread. * * @param project the project to use * @param settings the vcs settings * @param sortedChanges sorted changes * @param exceptions the collection with exceptions * @return true if conversion completed successfully, false if process was cancelled or there were errors */ public static boolean showDialogIfNeeded(final Project project, final GitVcsSettings settings, Map<VirtualFile, List<Change>> sortedChanges, final List<VcsException> exceptions) { final GitVcsSettings.ConversionPolicy conversionPolicy = settings.getLineSeparatorsConversion(); if (conversionPolicy != GitVcsSettings.ConversionPolicy.NONE) { LocalFileSystem lfs = LocalFileSystem.getInstance(); final String nl = CodeStyleFacade.getInstance(project).getLineSeparator(); final Map<VirtualFile, Set<VirtualFile>> files = new HashMap<VirtualFile, Set<VirtualFile>>(); // preliminary screening of files for (Map.Entry<VirtualFile, List<Change>> entry : sortedChanges.entrySet()) { final VirtualFile root = entry.getKey(); final Set<VirtualFile> added = new HashSet<VirtualFile>(); for (Change change : entry.getValue()) { switch (change.getType()) { case NEW: case MODIFICATION: case MOVED: VirtualFile f = lfs.findFileByPath(change.getAfterRevision().getFile().getPath()); if (f != null && !f.getFileType().isBinary() && !nl.equals(LoadTextUtil.detectLineSeparator(f, false))) { added.add(f); } break; case DELETED: } } if (!added.isEmpty()) { files.put(root, added); } } // check crlf for real for (Iterator<Map.Entry<VirtualFile, Set<VirtualFile>>> i = files.entrySet().iterator(); i.hasNext();) { Map.Entry<VirtualFile, Set<VirtualFile>> e = i.next(); Set<VirtualFile> fs = e.getValue(); for (Iterator<VirtualFile> j = fs.iterator(); j.hasNext();) { VirtualFile f = j.next(); String detectedLineSeparator = LoadTextUtil.detectLineSeparator(f, true); if (detectedLineSeparator == null || nl.equals(detectedLineSeparator)) { j.remove(); } } if (fs.isEmpty()) { i.remove(); } } if (files.isEmpty()) { return true; } UIUtil.invokeAndWaitIfNeeded(new Runnable() { public void run() { VirtualFile[] selectedFiles = null; if (settings.getLineSeparatorsConversion() == GitVcsSettings.ConversionPolicy.ASK) { GitConvertFilesDialog d = new GitConvertFilesDialog(project, files); d.show(); if (d.isOK()) { if (d.myDoNotShowCheckBox.isSelected()) { settings.setLineSeparatorsConversion(GitVcsSettings.ConversionPolicy.CONVERT); } selectedFiles = d.myFilesToConvert.getCheckedNodes(VirtualFile.class, null); } else if (d.getExitCode() == DO_NOT_CONVERT) { if (d.myDoNotShowCheckBox.isSelected()) { settings.setLineSeparatorsConversion(GitVcsSettings.ConversionPolicy.NONE); } } else { //noinspection ThrowableInstanceNeverThrown exceptions.add(new VcsException("Commit was cancelled in file conversion dialog")); } } else { ArrayList<VirtualFile> fileList = new ArrayList<VirtualFile>(); for (Set<VirtualFile> fileSet : files.values()) { fileList.addAll(fileSet); } selectedFiles = VfsUtil.toVirtualFileArray(fileList); } if (selectedFiles != null) { for (VirtualFile f : selectedFiles) { if (f == null) { continue; } try { LoadTextUtil.changeLineSeparator(project, GitConvertFilesDialog.class.getName(), f, nl); } catch (IOException e) { //noinspection ThrowableInstanceNeverThrown exceptions.add(new VcsException("Failed to change line separators for the file: " + f.getPresentableUrl(), e)); } } } } }); } return exceptions.isEmpty(); } /** * Action used to indicate that no conversion should be performed */ class DoNotConvertAction extends AbstractAction { private static final long serialVersionUID = 1931383640152023206L; /** * The constructor */ DoNotConvertAction() { putValue(NAME, GitBundle.getString("crlf.convert.leave")); putValue(DEFAULT_ACTION, Boolean.FALSE); } /** * {@inheritDoc} */ public void actionPerformed(ActionEvent e) { if (myPerformAction) return; try { myPerformAction = true; close(DO_NOT_CONVERT); } finally { myPerformAction = false; } } } /** * The cell renderer for the tree */ static class FileTreeCellRenderer extends CheckboxTree.CheckboxTreeCellRenderer { /** * {@inheritDoc} */ @Override public void customizeRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { // Fix GTK background if (UIUtil.isUnderGTKLookAndFeel()){ final Color background = selected ? UIUtil.getTreeSelectionBackground() : UIUtil.getTreeTextBackground(); UIUtil.changeBackGround(this, background); } ColoredTreeCellRenderer r = getTextRenderer(); if (!(value instanceof CheckedTreeNode)) { // unknown node type renderUnknown(r, value); return; } CheckedTreeNode node = (CheckedTreeNode)value; if (!(node.getUserObject() instanceof VirtualFile)) { // unknown node type renderUnknown(r, node.getUserObject()); return; } VirtualFile file = (VirtualFile)node.getUserObject(); if (leaf) { VirtualFile parent = (VirtualFile)((CheckedTreeNode)node.getParent()).getUserObject(); // the real file Icon i = file.getIcon(); if (i != null) { r.setIcon(i); } r.append(GitUtil.getRelativeFilePath(file, parent), SimpleTextAttributes.REGULAR_ATTRIBUTES, true); } else { // the vcs root node r.append(file.getPresentableUrl(), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES, true); } } /** * Render unknown node * * @param r a renderer to use * @param value the unknown value */ private static void renderUnknown(ColoredTreeCellRenderer r, Object value) { r.append("UNSUPPORTED NODE TYPE: " + (value == null ? "null" : value.getClass().getName()), SimpleTextAttributes.ERROR_ATTRIBUTES); } } }
plugins/git4idea/src/git4idea/ui/GitConvertFilesDialog.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.ui; import com.intellij.codeStyle.CodeStyleFacade; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.*; import com.intellij.util.containers.HashMap; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import git4idea.GitUtil; import git4idea.commands.GitCommand; import git4idea.commands.GitFileUtils; import git4idea.commands.GitSimpleHandler; import git4idea.commands.StringScanner; import git4idea.config.GitVcsSettings; import git4idea.config.GitVersion; import git4idea.i18n.GitBundle; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.io.IOException; import java.util.*; import java.util.List; /** * This dialog allows converting the specified files before committing them. */ public class GitConvertFilesDialog extends DialogWrapper { /** * The version when option --stdin was added */ private static final GitVersion CHECK_ATTR_STDIN_SUPPORTED = new GitVersion(1, 6, 1, 0); /** * Do not convert exit code */ public static final int DO_NOT_CONVERT = NEXT_USER_EXIT_CODE; /** * The checkbox used to indicate that dialog should not be shown */ private JCheckBox myDoNotShowCheckBox; /** * The root panel of the dialog */ private JPanel myRootPanel; /** * The tree of files to convert */ private CheckboxTreeBase myFilesToConvert; /** * The root node in the tree */ private CheckedTreeNode myRootNode; /** * The constructor * * @param project the project to which this dialog is related * @param filesToShow the files to show sorted by vcs root */ GitConvertFilesDialog(Project project, Map<VirtualFile, Set<VirtualFile>> filesToShow) { super(project, true); ArrayList<VirtualFile> roots = new ArrayList<VirtualFile>(filesToShow.keySet()); Collections.sort(roots, GitUtil.VIRTUAL_FILE_COMPARATOR); for (VirtualFile root : roots) { CheckedTreeNode vcsRoot = new CheckedTreeNode(root); myRootNode.add(vcsRoot); ArrayList<VirtualFile> files = new ArrayList<VirtualFile>(filesToShow.get(root)); Collections.sort(files, GitUtil.VIRTUAL_FILE_COMPARATOR); for (VirtualFile file : files) { vcsRoot.add(new CheckedTreeNode(file)); } } TreeUtil.expandAll(myFilesToConvert); setTitle(GitBundle.getString("crlf.convert.title")); setOKButtonText(GitBundle.getString("crlf.convert.convert")); init(); } /** * {@inheritDoc} */ @Override protected Action[] createActions() { return new Action[]{getOKAction(), new DoNotConvertAction(), getCancelAction()}; } /** * Create custom UI components */ private void createUIComponents() { myRootNode = new CheckedTreeNode("ROOT"); myFilesToConvert = new CheckboxTree(new FileTreeCellRenderer(), myRootNode) { protected void onNodeStateChanged(CheckedTreeNode node) { VirtualFile[] files = myFilesToConvert.getCheckedNodes(VirtualFile.class, null); setOKActionEnabled(files != null && files.length > 0); super.onNodeStateChanged(node); } }; } /** * {@inheritDoc} */ @Override protected JComponent createCenterPanel() { return myRootPanel; } /** * {@inheritDoc} */ @Override protected String getDimensionServiceKey() { return getClass().getName(); } /** * Check if files need to be converted to other line separator. The method could be invoked from non-UI thread. * * @param project the project to use * @param settings the vcs settings * @param sortedChanges sorted changes * @param exceptions the collection with exceptions * @return true if conversion completed successfully, false if process was cancelled or there were errors */ public static boolean showDialogIfNeeded(final Project project, final GitVcsSettings settings, Map<VirtualFile, List<Change>> sortedChanges, final List<VcsException> exceptions) { try { final GitVcsSettings.ConversionPolicy conversionPolicy = settings.getLineSeparatorsConversion(); if (conversionPolicy != GitVcsSettings.ConversionPolicy.NONE) { LocalFileSystem lfs = LocalFileSystem.getInstance(); final String nl = CodeStyleFacade.getInstance(project).getLineSeparator(); final Map<VirtualFile, Set<VirtualFile>> files = new HashMap<VirtualFile, Set<VirtualFile>>(); // preliminary screening of files for (Map.Entry<VirtualFile, List<Change>> entry : sortedChanges.entrySet()) { final VirtualFile root = entry.getKey(); final Set<VirtualFile> added = new HashSet<VirtualFile>(); for (Change change : entry.getValue()) { switch (change.getType()) { case NEW: case MODIFICATION: case MOVED: VirtualFile f = lfs.findFileByPath(change.getAfterRevision().getFile().getPath()); if (f != null && !f.getFileType().isBinary() && !nl.equals(LoadTextUtil.detectLineSeparator(f, false))) { added.add(f); } break; case DELETED: } } if (!added.isEmpty()) { files.put(root, added); } } // ignore files with CRLF unset ignoreFilesWithCrlfUnset(project, files); // check crlf for real for (Iterator<Map.Entry<VirtualFile, Set<VirtualFile>>> i = files.entrySet().iterator(); i.hasNext();) { Map.Entry<VirtualFile, Set<VirtualFile>> e = i.next(); Set<VirtualFile> fs = e.getValue(); for (Iterator<VirtualFile> j = fs.iterator(); j.hasNext();) { VirtualFile f = j.next(); String detectedLineSeparator = LoadTextUtil.detectLineSeparator(f, true); if (detectedLineSeparator == null || nl.equals(detectedLineSeparator)) { j.remove(); } } if (fs.isEmpty()) { i.remove(); } } if (files.isEmpty()) { return true; } UIUtil.invokeAndWaitIfNeeded(new Runnable() { public void run() { VirtualFile[] selectedFiles = null; if (settings.getLineSeparatorsConversion() == GitVcsSettings.ConversionPolicy.ASK) { GitConvertFilesDialog d = new GitConvertFilesDialog(project, files); d.show(); if (d.isOK()) { if (d.myDoNotShowCheckBox.isSelected()) { settings.setLineSeparatorsConversion(GitVcsSettings.ConversionPolicy.CONVERT); } selectedFiles = d.myFilesToConvert.getCheckedNodes(VirtualFile.class, null); } else if (d.getExitCode() == DO_NOT_CONVERT) { if (d.myDoNotShowCheckBox.isSelected()) { settings.setLineSeparatorsConversion(GitVcsSettings.ConversionPolicy.NONE); } } else { //noinspection ThrowableInstanceNeverThrown exceptions.add(new VcsException("Commit was cancelled in file conversion dialog")); } } else { ArrayList<VirtualFile> fileList = new ArrayList<VirtualFile>(); for (Set<VirtualFile> fileSet : files.values()) { fileList.addAll(fileSet); } selectedFiles = VfsUtil.toVirtualFileArray(fileList); } if (selectedFiles != null) { for (VirtualFile f : selectedFiles) { if (f == null) { continue; } try { LoadTextUtil.changeLineSeparator(project, GitConvertFilesDialog.class.getName(), f, nl); } catch (IOException e) { //noinspection ThrowableInstanceNeverThrown exceptions.add(new VcsException("Failed to change line separators for the file: " + f.getPresentableUrl(), e)); } } } } }); } } catch (VcsException e) { exceptions.add(e); } return exceptions.isEmpty(); } /** * Remove files that have -crlf attribute specified * * @param project the context project * @param files the files to check (map from vcs roots to the set of files under root) * @throws VcsException if there is problem with running git */ private static void ignoreFilesWithCrlfUnset(Project project, Map<VirtualFile, Set<VirtualFile>> files) throws VcsException { for (final Map.Entry<VirtualFile, Set<VirtualFile>> e : files.entrySet()) { final VirtualFile r = e.getKey(); final HashMap<String, VirtualFile> filesToCheck = new HashMap<String, VirtualFile>(); Set<VirtualFile> fileSet = e.getValue(); for (VirtualFile file : fileSet) { filesToCheck.put(GitUtil.relativePath(r, file), file); } final List<List<String>> chunkedFiles = GitFileUtils.chunkFiles(r, filesToCheck.values()); for (List<String> list : chunkedFiles) { GitSimpleHandler h = new GitSimpleHandler(project, r, GitCommand.CHECK_ATTR); h.addParameters("crlf"); h.setSilent(true); h.setNoSSH(true); h.endOptions(); h.addParameters(list); StringScanner output = new StringScanner(h.run()); String unsetIndicator = ": crlf: unset"; while (output.hasMoreData()) { String l = output.line(); if (l.endsWith(unsetIndicator)) { fileSet.remove(filesToCheck.get(GitUtil.unescapePath(l.substring(0, l.length() - unsetIndicator.length())))); } } } } } /** * Action used to indicate that no conversion should be performed */ class DoNotConvertAction extends AbstractAction { private static final long serialVersionUID = 1931383640152023206L; /** * The constructor */ DoNotConvertAction() { putValue(NAME, GitBundle.getString("crlf.convert.leave")); putValue(DEFAULT_ACTION, Boolean.FALSE); } /** * {@inheritDoc} */ public void actionPerformed(ActionEvent e) { if (myPerformAction) return; try { myPerformAction = true; close(DO_NOT_CONVERT); } finally { myPerformAction = false; } } } /** * The cell renderer for the tree */ static class FileTreeCellRenderer extends CheckboxTree.CheckboxTreeCellRenderer { /** * {@inheritDoc} */ @Override public void customizeRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { // Fix GTK background if (UIUtil.isUnderGTKLookAndFeel()){ final Color background = selected ? UIUtil.getTreeSelectionBackground() : UIUtil.getTreeTextBackground(); UIUtil.changeBackGround(this, background); } ColoredTreeCellRenderer r = getTextRenderer(); if (!(value instanceof CheckedTreeNode)) { // unknown node type renderUnknown(r, value); return; } CheckedTreeNode node = (CheckedTreeNode)value; if (!(node.getUserObject() instanceof VirtualFile)) { // unknown node type renderUnknown(r, node.getUserObject()); return; } VirtualFile file = (VirtualFile)node.getUserObject(); if (leaf) { VirtualFile parent = (VirtualFile)((CheckedTreeNode)node.getParent()).getUserObject(); // the real file Icon i = file.getIcon(); if (i != null) { r.setIcon(i); } r.append(GitUtil.getRelativeFilePath(file, parent), SimpleTextAttributes.REGULAR_ATTRIBUTES, true); } else { // the vcs root node r.append(file.getPresentableUrl(), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES, true); } } /** * Render unknown node * * @param r a renderer to use * @param value the unknown value */ private static void renderUnknown(ColoredTreeCellRenderer r, Object value) { r.append("UNSUPPORTED NODE TYPE: " + (value == null ? "null" : value.getClass().getName()), SimpleTextAttributes.ERROR_ATTRIBUTES); } } }
Git: the policy of converting files before commit shouldn't be affected by gitattributes crlf settings.
plugins/git4idea/src/git4idea/ui/GitConvertFilesDialog.java
Git: the policy of converting files before commit shouldn't be affected by gitattributes crlf settings.
Java
bsd-2-clause
8e84ffba045e56740a9f25ab13f9c02f9731d89c
0
markphip/testing,edgehosting/jira-dvcs-connector,markphip/testing,edgehosting/jira-dvcs-connector,edgehosting/jira-dvcs-connector,markphip/testing
package com.atlassian.jira.plugins.dvcs.ondemand; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.atlassian.jira.plugins.dvcs.model.Credential; import com.atlassian.jira.plugins.dvcs.model.Organization; import com.atlassian.jira.plugins.dvcs.ondemand.AccountsConfig.BitbucketAccountInfo; import com.atlassian.jira.plugins.dvcs.ondemand.AccountsConfig.Links; import com.atlassian.jira.plugins.dvcs.service.OrganizationService; import com.atlassian.plugin.PluginAccessor; import com.atlassian.plugin.PluginController; import com.atlassian.plugin.web.descriptors.WebFragmentModuleDescriptor; import com.atlassian.sal.api.scheduling.PluginScheduler; public class BitbucketAccountsConfigServiceTest { @Mock private OrganizationService organizationService; @Mock private AccountsConfigProvider configProvider; @Mock private PluginScheduler pluginScheduler; @Mock private PluginController pluginController; @Mock private PluginAccessor pluginAccessor; @Mock private WebFragmentModuleDescriptor webFragmentModuleDescriptor; @Captor ArgumentCaptor<Organization> organizationCaptor; private BitbucketAccountsConfigService testedService; public BitbucketAccountsConfigServiceTest() { super(); } @BeforeMethod public void setUp() { MockitoAnnotations.initMocks(this); testedService = new BitbucketAccountsConfigService(configProvider, organizationService, pluginScheduler, pluginController, pluginAccessor); when(configProvider.supportsIntegratedAccounts()).thenReturn(true); when(pluginAccessor.getEnabledPluginModule(anyString())).thenReturn(webFragmentModuleDescriptor); } @Test public void testAddNewAccountWithSuccess() { AccountsConfig correctConfig = createCorrectConfig(); when(configProvider.provideConfiguration()).thenReturn(correctConfig); when(organizationService.findIntegratedAccount()).thenReturn(null); when(organizationService.getByHostAndName(eq("https://bitbucket.org"), eq("A"))).thenReturn(null); testedService.reload(false); verify(organizationService).save(organizationCaptor.capture()); Organization savedOrg = organizationCaptor.getValue(); assertThat(savedOrg.getName()).isEqualTo("A"); assertThat(savedOrg.getCredential().getOauthKey()).isEqualTo("K"); assertThat(savedOrg.getCredential().getOauthSecret()).isEqualTo("S"); } @Test public void testAddNewAccountEmptyConfig() { when(configProvider.provideConfiguration()).thenReturn(null); when(organizationService.findIntegratedAccount()).thenReturn(null); testedService.reload(false); verify(organizationService, times(0)).save(organizationCaptor.capture()); } @Test public void testUpdateAccountEmptyConfig() { when(configProvider.provideConfiguration()).thenReturn(null); Organization existingAccount = createSampleAccount("A", "B", "S", "token"); when(organizationService.findIntegratedAccount()).thenReturn(existingAccount); testedService.reload(false); verify(organizationService, times(0)).save(organizationCaptor.capture()); verify(organizationService).remove(eq(5)); } @Test public void testUpdateAccountCredentialsWithSuccess() { AccountsConfig correctConfig = createCorrectConfig(); when(configProvider.provideConfiguration()).thenReturn(correctConfig); Organization existingAccount = createSampleAccount("A", "B", "S", "token"); when(organizationService.findIntegratedAccount()).thenReturn(existingAccount); when(organizationService.getByHostAndName(eq("https://bitbucket.org"), eq("A"))).thenReturn(null); testedService.reload(false); verify(organizationService).updateCredentials(eq(5), eq(new Credential("K", "S",null))); } @Test public void testUpdateAccountCredentialsEmptyConfig_ShouldRemoveIntegratedAccount() { when(configProvider.provideConfiguration()).thenReturn(null); Organization existingAccount = createSampleAccount("A", "B", "S", "token"); when(organizationService.findIntegratedAccount()).thenReturn(existingAccount); when(organizationService.getByHostAndName(eq("https://bitbucket.org"), eq("A"))).thenReturn(null); testedService.reload(false); verify(organizationService).remove(eq(5)); } //-- @Test public void testAddNewAccountWithSuccess_UserAddedAccountExists() { AccountsConfig config = createCorrectConfig(); when(configProvider.provideConfiguration()).thenReturn(config); when(organizationService.findIntegratedAccount()).thenReturn(null); Organization userAddedAccount = createSampleAccount("A", "key", "secret", "token"); when(organizationService.getByHostAndName(eq("https://bitbucket.org"), eq("A"))).thenReturn(userAddedAccount); testedService.reload(false); verify(organizationService).updateCredentials(userAddedAccount.getId(), new Credential("K", "S", null)); } //-- private Organization createSampleAccount(String name, String key, String secret, String token) { Organization org = new Organization(); org.setId(5); org.setName(name); org.setCredential(new Credential(key, secret, token)); return org; } private AccountsConfig createCorrectConfig() { return createConfig("A", "K", "S"); } private AccountsConfig createConfig(String account, String key, String secret) { AccountsConfig accountsConfig = new AccountsConfig(); List<Links> sysadminApplicationLinks = new ArrayList<AccountsConfig.Links>(); Links links = new Links(); List<BitbucketAccountInfo> bbLinks = new ArrayList<AccountsConfig.BitbucketAccountInfo>(); BitbucketAccountInfo bbAccount = new BitbucketAccountInfo(); bbAccount.setAccount(account); bbAccount.setKey(key); bbAccount.setSecret(secret); bbLinks.add(bbAccount); links.setBitbucket(bbLinks); sysadminApplicationLinks.add(links); accountsConfig.setSysadminApplicationLinks(sysadminApplicationLinks); return accountsConfig; } }
jira-dvcs-connector-plugin/src/test/java/com/atlassian/jira/plugins/dvcs/ondemand/BitbucketAccountsConfigServiceTest.java
package com.atlassian.jira.plugins.dvcs.ondemand; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.atlassian.jira.plugins.dvcs.model.Credential; import com.atlassian.jira.plugins.dvcs.model.Organization; import com.atlassian.jira.plugins.dvcs.ondemand.AccountsConfig.BitbucketAccountInfo; import com.atlassian.jira.plugins.dvcs.ondemand.AccountsConfig.Links; import com.atlassian.jira.plugins.dvcs.service.OrganizationService; import com.atlassian.plugin.PluginAccessor; import com.atlassian.plugin.PluginController; import com.atlassian.plugin.web.descriptors.WebFragmentModuleDescriptor; import com.atlassian.sal.api.scheduling.PluginScheduler; public class BitbucketAccountsConfigServiceTest { @Mock private OrganizationService organizationService; @Mock private AccountsConfigProvider configProvider; @Mock private PluginScheduler pluginScheduler; @Mock private PluginController pluginController; @Mock private PluginAccessor pluginAccessor; @Mock private WebFragmentModuleDescriptor webFragmentModuleDescriptor; @Captor ArgumentCaptor<Organization> organizationCaptor; private BitbucketAccountsConfigService testedService; public BitbucketAccountsConfigServiceTest() { super(); } @BeforeMethod public void setUp() { MockitoAnnotations.initMocks(this); testedService = new BitbucketAccountsConfigService(configProvider, organizationService, pluginScheduler, pluginController, pluginAccessor); when(configProvider.supportsIntegratedAccounts()).thenReturn(true); when(pluginAccessor.getEnabledPluginModule(anyString())).thenReturn(webFragmentModuleDescriptor); } @Test public void testAddNewAccountWithSuccess() { AccountsConfig correctConfig = createCorrectConfig(); when(configProvider.provideConfiguration()).thenReturn(correctConfig); when(organizationService.findIntegratedAccount()).thenReturn(null); when(organizationService.getByHostAndName(eq("https://bitbucket.org"), eq("A"))).thenReturn(null); testedService.reload(false); verify(organizationService).save(organizationCaptor.capture()); Organization savedOrg = organizationCaptor.getValue(); assertThat(savedOrg.getName()).isEqualTo("A"); assertThat(savedOrg.getCredential().getOauthKey()).isEqualTo("K"); assertThat(savedOrg.getCredential().getOauthSecret()).isEqualTo("S"); } @Test public void testAddNewAccountEmptyConfig() { when(configProvider.provideConfiguration()).thenReturn(null); when(organizationService.findIntegratedAccount()).thenReturn(null); testedService.reload(false); verify(organizationService, times(0)).save(organizationCaptor.capture()); } @Test public void testUpdateAccountEmptyConfig() { when(configProvider.provideConfiguration()).thenReturn(null); Organization existingAccount = createSampleAccount("A", "B", "S"); when(organizationService.findIntegratedAccount()).thenReturn(existingAccount); testedService.reload(false); verify(organizationService, times(0)).save(organizationCaptor.capture()); verify(organizationService).remove(eq(5)); } @Test public void testUpdateAccountCredentialsWithSuccess() { AccountsConfig correctConfig = createCorrectConfig(); when(configProvider.provideConfiguration()).thenReturn(correctConfig); Organization existingAccount = createSampleAccount("A", "B", "S"); when(organizationService.findIntegratedAccount()).thenReturn(existingAccount); when(organizationService.getByHostAndName(eq("https://bitbucket.org"), eq("A"))).thenReturn(null); testedService.reload(false); verify(organizationService).updateCredentials(eq(5), eq(new Credential("K", "S",null))); } @Test public void testUpdateAccountCredentialsEmptyConfig_ShouldRemoveIntegratedAccount() { when(configProvider.provideConfiguration()).thenReturn(null); Organization existingAccount = createSampleAccount("A", "B", "S"); when(organizationService.findIntegratedAccount()).thenReturn(existingAccount); when(organizationService.getByHostAndName(eq("https://bitbucket.org"), eq("A"))).thenReturn(null); testedService.reload(false); verify(organizationService).remove(eq(5)); } //-- @Test public void testAddNewAccountWithSuccess_UserAddedAccountExists() { AccountsConfig correctConfig = createCorrectConfig(); when(configProvider.provideConfiguration()).thenReturn(correctConfig); when(organizationService.findIntegratedAccount()).thenReturn(null); Organization userAddedAccount = createSampleAccount("A", null, null); when(organizationService.getByHostAndName(eq("https://bitbucket.org"), eq("A"))).thenReturn(userAddedAccount); testedService.reload(false); verify(organizationService).updateCredentials(userAddedAccount.getId(), new Credential("K", "S", null)); } //-- private Organization createSampleAccount(String name, String key, String secret) { Organization org = new Organization(); org.setId(5); org.setName(name); org.setCredential(new Credential(key, secret, null)); return org; } private AccountsConfig createCorrectConfig() { return createConfig("A", "K", "S"); } private AccountsConfig createConfig(String account, String key, String secret) { AccountsConfig accountsConfig = new AccountsConfig(); List<Links> sysadminApplicationLinks = new ArrayList<AccountsConfig.Links>(); Links links = new Links(); List<BitbucketAccountInfo> bbLinks = new ArrayList<AccountsConfig.BitbucketAccountInfo>(); BitbucketAccountInfo bbAccount = new BitbucketAccountInfo(); bbAccount.setAccount(account); bbAccount.setKey(key); bbAccount.setSecret(secret); bbLinks.add(bbAccount); links.setBitbucket(bbLinks); sysadminApplicationLinks.add(links); accountsConfig.setSysadminApplicationLinks(sysadminApplicationLinks); return accountsConfig; } }
BBC-496 Fixing test
jira-dvcs-connector-plugin/src/test/java/com/atlassian/jira/plugins/dvcs/ondemand/BitbucketAccountsConfigServiceTest.java
BBC-496 Fixing test
Java
bsd-2-clause
509331ab153ca5151dac1aadcffe4479c54fbd44
0
OpenAS2/OpenAs2App,igwtech/OpenAs2App,igwtech/OpenAs2App,igwtech/OpenAs2App,igwtech/OpenAs2App,OpenAS2/OpenAs2App,OpenAS2/OpenAs2App,OpenAS2/OpenAs2App
package org.openas2.util; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.PasswordAuthentication; import java.net.Proxy; import java.net.SocketException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.security.KeyStore; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import javax.mail.Header; import javax.mail.MessagingException; import javax.mail.internet.InternetHeaders; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpHost; import org.apache.http.NameValuePair; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.BufferedHttpEntity; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.InputStreamEntity; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.ssl.SSLContexts; import org.openas2.OpenAS2Exception; import org.openas2.WrappedException; import org.openas2.message.Message; /** * @author Christopher */ public class HTTPUtil { public static final String MA_HTTP_REQ_TYPE = "HTTP_REQUEST_TYPE"; public static final String MA_HTTP_REQ_URL = "HTTP_REQUEST_URL"; public static final String HTTP_PROP_REMOVE_HEADER_FOLDING = "remove_http_header_folding"; public static final String HTTP_PROP_SSL_PROTOCOLS = "http_ssl_protocols"; public static final String HTTP_PROP_OVERRIDE_SSL_CHECKS = "http_override_ssl_checks"; public static final String PARAM_READ_TIMEOUT = "readtimeout"; public static final String PARAM_CONNECT_TIMEOUT = "connecttimeout"; public static final String PARAM_SOCKET_TIMEOUT = "sockettimeout"; public static final String PARAM_HTTP_USER = "http_user"; public static final String PARAM_HTTP_PWD = "http_password"; public static final String HEADER_CONTENT_TYPE = "Content-Type"; public static final String HEADER_USER_AGENT = "User-Agent"; public static final String HEADER_CONNECTION = "Connection"; public abstract static class Method { public static final String GET = "GET"; public static final String HEAD = "HEAD"; public static final String POST = "POST"; public static final String PUT = "PUT"; public static final String DELETE = "DELETE"; public static final String TRACE = "TRACE"; public static final String CONNECT = "CONNECT"; } private static final Map<Integer, String> httpResponseCodeToPhrase = new HashMap<Integer, String>() { private static final long serialVersionUID = 1L; { put(100, "Continue"); put(101, "Switching Protocols"); put(200, "OK"); put(201, "Created"); put(202, "Accepted"); put(203, "Non-Authoritative Information"); put(204, "No Content"); put(205, "Reset Content"); put(206, "Partial Content"); put(300, "Multiple Choices"); put(301, "Moved Permanently"); put(302, "Found"); put(303, "See Other"); put(304, "Not Modified"); put(305, "Use Proxy"); put(307, "Temporary Redirect"); put(400, "Bad Request"); put(401, "Unauthorized"); put(402, "Payment Required"); put(403, "Forbidden"); put(404, "Not Found"); put(405, "Method Not Allowed"); put(406, "Not Acceptable"); put(407, "Proxy Authentication Required"); put(408, "Request Time-out"); put(409, "Conflict"); put(410, "Gone"); put(411, "Length Required"); put(412, "Precondition Failed"); put(413, "Request Entity Too Large"); put(414, "Request-URI Too Large"); put(415, "Unsupported Media Type"); put(416, "Requested range not satisfiable"); put(417, "Expectation Failed"); put(500, "Internal Server Error"); put(501, "Not Implemented"); put(502, "Bad Gateway"); put(503, "Service Unavailable"); put(504, "Gateway Time-out"); put(505, "HTTP Version not supported"); } }; public static String getHTTPResponseMessage(int responseCode) { String code = httpResponseCodeToPhrase.get(responseCode); return (code == null) ? "Unknown" : code; } public static byte[] readHTTP(InputStream inStream, OutputStream outStream, InternetHeaders headerCache, List<String> httpRequest) throws IOException, MessagingException { byte[] data = null; Log logger = LogFactory.getLog(HTTPUtil.class.getSimpleName()); // Get the stream and read in the HTTP request and headers BufferedInputStream in = new BufferedInputStream(inStream); String[] request = HTTPUtil.readRequest(in); for (int i = 0; i < request.length; i++) { httpRequest.add(request[i]); } headerCache.load(in); if (logger.isTraceEnabled()) { logger.trace("HTTP received request: " + request[0] + " " + request[1] + "\n\tHeaders: " + printHeaders(headerCache.getAllHeaders(), "==", ";;")); } DataInputStream dataIn = new DataInputStream(in); // Retrieve the message content if (headerCache.getHeader("Content-Length") == null) { String transfer_encoding = headerCache.getHeader("Transfer-Encoding", ","); if (transfer_encoding != null) { if (transfer_encoding.replaceAll("\\s+", "").equalsIgnoreCase("chunked")) { int length = 0; data = null; for (; ; ) { // First get hex chunk length; followed by CRLF int blocklen = 0; for (; ; ) { int ch = dataIn.readByte(); if (ch == '\n') { break; } if (ch >= 'a' && ch <= 'f') { ch -= ('a' - 10); } else if (ch >= 'A' && ch <= 'F') { ch -= ('A' - 10); } else if (ch >= '0' && ch <= '9') { ch -= '0'; } else { continue; } blocklen = (blocklen * 16) + ch; } // Zero length is end of chunks if (blocklen == 0) { break; } // Ok, now read new chunk int newlen = length + blocklen; byte[] newdata = new byte[newlen]; if (length > 0) { System.arraycopy(data, 0, newdata, 0, length); } dataIn.readFully(newdata, length, blocklen); data = newdata; length = newlen; // And now the CRLF after the chunk; while (dataIn.readByte() != '\n') { ; } } headerCache.setHeader("Content-Length", Integer.toString(length)); } else { if (outStream != null) { HTTPUtil.sendHTTPResponse(outStream, HttpURLConnection.HTTP_LENGTH_REQUIRED, null); } throw new IOException("Transfer-Encoding unimplemented: " + transfer_encoding); } } else { return null; } } else { // Receive the transmission's data int contentSize = Integer.parseInt(headerCache.getHeader("Content-Length", ",")); data = new byte[contentSize]; dataIn.readFully(data); } return data; } /* * TODO: Move this out of HTTPUtil class so that class does not depend on AS2 * specific stuff */ public static byte[] readData(InputStream inStream, OutputStream outStream, Message msg) throws IOException, MessagingException { List<String> request = new ArrayList<String>(2); byte[] data = readHTTP(inStream, outStream, msg.getHeaders(), request); msg.setAttribute(MA_HTTP_REQ_TYPE, request.get(0)); msg.setAttribute(MA_HTTP_REQ_URL, request.get(1)); if (data == null) { String healthCheckUri = Properties.getProperty("health_check_uri", "healthcheck"); if ("GET".equalsIgnoreCase(request.get(0)) && request.get(1).matches("^[/]{0,1}" + healthCheckUri + "*")) { if (outStream != null) { HTTPUtil.sendHTTPResponse(outStream, HttpURLConnection.HTTP_OK, null); msg.setAttribute("isHealthCheck", "true"); // provide means for caller to know what happened } return null; } else { HTTPUtil.sendHTTPResponse(outStream, HttpURLConnection.HTTP_LENGTH_REQUIRED, null); if ("true".equals(Properties.getProperty(Properties.LOG_INVALID_HTTP_REQUEST, "true"))) { Log logger = LogFactory.getLog(HTTPUtil.class.getSimpleName()); logger.warn("The request either contained no data or has issues with the Transfer-Encoding or Content-Length: : " + request.get(0) + " " + request.get(1) + "\n\tHeaders: " + printHeaders(msg.getHeaders().getAllHeaders(), "==", ";;")); } return null; } } cleanIdHeaders(msg.getHeaders()); return data; } /** * Cleans specific headers to ensure AS2 compatibility * * @param hdrs Headers to be cleaned */ public static void cleanIdHeaders(InternetHeaders hdrs) { // Handle the case where the AS2 ID could be encapsulated in double quotes per RFC4130 // some AS2 applications will send the quoted AND the unquoted ID so need String[] idHeaders = {"AS2-From", "AS2-To"}; for (int i = 0; i < idHeaders.length; i++) { // Target only the first entry if there is more than one to get a single value String value = StringUtil.removeDoubleQuotes(hdrs.getHeader(idHeaders[i], null)); // Delete all headers with the same key hdrs.removeHeader(idHeaders[i]); // Add back as a single value without quotes hdrs.setHeader(idHeaders[i], value); } } public static String[] readRequest(InputStream in) throws IOException { int byteBuf = in.read(); StringBuffer strBuf = new StringBuffer(); while ((byteBuf != -1) && (byteBuf != '\r')) { strBuf.append((char) byteBuf); byteBuf = in.read(); } if (byteBuf != -1) { in.read(); // read in the \n } StringTokenizer tokens = new StringTokenizer(strBuf.toString(), " "); int tokenCount = tokens.countTokens(); if (tokenCount >= 3) { String[] requestParts = new String[tokenCount]; for (int i = 0; i < tokenCount; i++) { requestParts[i] = tokens.nextToken(); } return requestParts; } else if (tokenCount == 2) { String[] requestParts = new String[3]; requestParts[0] = tokens.nextToken(); requestParts[1] = "/"; requestParts[2] = tokens.nextToken(); return requestParts; } else { throw new IOException("Invalid HTTP Request: Token Count - " + tokenCount + "::: String length - " + strBuf.length() + " ::: String - " + strBuf.toString()); } } /** * Execute a request via HTTP * * @param method GET, PUT, POST, DELETE, etc * @param url The remote connection string * @param headers HTTP headers to be sent * @param params Parameters for the get. Can be null. * @param inputStream Source stream for retrieving request data * @param options Any additional options for affecting request behaviour. Can NOT be null. * @param noChunkMaxSize The maximum size before chunking would need to be utilised. 0 disables check for chunking * @return ResponseWrapper * @throws Exception */ public static ResponseWrapper execRequest(String method, String url, Enumeration<Header> headers, NameValuePair[] params, InputStream inputStream, Map<String, String> options, long noChunkMaxSize) throws Exception { HttpClientBuilder httpBuilder = HttpClientBuilder.create(); URL urlObj = new URL(url); /* * httpClient is used for this request only, * set a connection manager that manages just one connection. */ if (urlObj.getProtocol().equalsIgnoreCase("https")) { /* * Note: registration of a custom SSLSocketFactory via httpBuilder.setSSLSocketFactory is ignored when a connection manager is set. * The custom SSLSocketFactory needs to be registered together with the connection manager. */ SSLConnectionSocketFactory sslCsf = buildSslFactory(urlObj, options); httpBuilder.setConnectionManager(new BasicHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslCsf).build())); } else { httpBuilder.setConnectionManager(new BasicHttpClientConnectionManager()); } RequestBuilder rb = getRequestBuilder(method, urlObj, params, headers); RequestConfig.Builder rcBuilder = buildRequestConfig(options); setProxyConfig(httpBuilder, rcBuilder, urlObj.getProtocol()); rb.setConfig(rcBuilder.build()); String httpUser = options.get(HTTPUtil.PARAM_HTTP_USER); String httpPwd = options.get(HTTPUtil.PARAM_HTTP_PWD); if (httpUser != null) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(httpUser, httpPwd)); httpBuilder.setDefaultCredentialsProvider(credentialsProvider); } if (inputStream != null) { if (noChunkMaxSize > 0L) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); long copied = IOUtils.copyLarge(inputStream, bout, 0L, noChunkMaxSize + 1, new byte[8192]); if (copied > noChunkMaxSize) { throw new IOException("Mime inputstream too big to put in memory (more than " + noChunkMaxSize + " bytes)."); } ByteArrayEntity bae = new ByteArrayEntity(bout.toByteArray(), null); rb.setEntity(bae); } else { InputStreamEntity ise = new InputStreamEntity(inputStream); // Use a BufferedEntity for BasicAuth connections to avoid the NonRepeatableRequestExceotion if (httpUser != null) { rb.setEntity(new BufferedHttpEntity(ise)); } else { rb.setEntity(ise); } } } final HttpUriRequest request = rb.build(); BasicHttpContext localcontext = new BasicHttpContext(); BasicScheme basicAuth = new BasicScheme(); localcontext.setAttribute("preemptive-auth", basicAuth); try (CloseableHttpClient httpClient = httpBuilder.build()) { ProfilerStub transferStub = Profiler.startProfile(); try (CloseableHttpResponse response = httpClient.execute(request, localcontext)) { ResponseWrapper resp = new ResponseWrapper(response); Profiler.endProfile(transferStub); resp.setTransferTimeMs(transferStub.getMilliseconds()); for (org.apache.http.Header header : response.getAllHeaders()) { resp.addHeaderLine(header.toString()); } return resp; } } } private static SSLConnectionSocketFactory buildSslFactory(URL urlObj, Map<String, String> options) throws Exception { boolean overrideSslChecks = "true".equalsIgnoreCase(options.get(HTTPUtil.HTTP_PROP_OVERRIDE_SSL_CHECKS)); SSLContext sslcontext; String selfSignedCN = System.getProperty("org.openas2.cert.TrustSelfSignedCN"); if ((selfSignedCN != null && selfSignedCN.contains(urlObj.getHost())) || overrideSslChecks) { File file = getTrustedCertsKeystore(); KeyStore ks = null; try (InputStream in = new FileInputStream(file)) { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, "changeit".toCharArray()); } try { // Trust own CA and all self-signed certs sslcontext = SSLContexts.custom().loadTrustMaterial(ks, new TrustSelfSignedStrategy()).build(); // Allow TLSv1 protocol only by default } catch (Exception e) { throw new OpenAS2Exception("Self-signed certificate URL connection failed connecting to : " + urlObj.toString(), e); } } else { sslcontext = SSLContexts.createSystemDefault(); } // String [] protocols = Properties.getProperty(HTTP_PROP_SSL_PROTOCOLS, // "TLSv1").split("\\s*,\\s*"); HostnameVerifier hnv = SSLConnectionSocketFactory.getDefaultHostnameVerifier(); if (overrideSslChecks) { hnv = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; } SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, null, null, hnv); return sslsf; } private static RequestBuilder getRequestBuilder(String method, URL urlObj, NameValuePair[] params, Enumeration<Header> headers) throws URISyntaxException { RequestBuilder req = null; if (method == null || method.equalsIgnoreCase(Method.GET)) { //default get req = RequestBuilder.get(); } else if (method.equalsIgnoreCase(Method.POST)) { req = RequestBuilder.post(); } else if (method.equalsIgnoreCase(Method.HEAD)) { req = RequestBuilder.head(); } else if (method.equalsIgnoreCase(Method.PUT)) { req = RequestBuilder.put(); } else if (method.equalsIgnoreCase(Method.DELETE)) { req = RequestBuilder.delete(); } else if (method.equalsIgnoreCase(Method.TRACE)) { req = RequestBuilder.trace(); } else { throw new IllegalArgumentException("Illegal HTTP Method: " + method); } req.setUri(urlObj.toURI()); if (params != null && params.length > 0) { req.addParameters(params); } if (headers != null) { boolean removeHeaderFolding = "true".equals(Properties.getProperty(HTTP_PROP_REMOVE_HEADER_FOLDING, "true")); while (headers.hasMoreElements()) { Header header = headers.nextElement(); String headerValue = header.getValue(); if (removeHeaderFolding) { headerValue = headerValue.replaceAll("\r\n[ \t]*", " "); } req.setHeader(header.getName(), headerValue); } } return req; } private static RequestConfig.Builder buildRequestConfig(Map<String, String> options) { String connectTimeOutStr = options.get(PARAM_CONNECT_TIMEOUT); String socketTimeOutStr = options.get(PARAM_SOCKET_TIMEOUT); RequestConfig.Builder rcBuilder = RequestConfig.custom(); if (connectTimeOutStr != null) { rcBuilder.setConnectTimeout(Integer.parseInt(connectTimeOutStr)); } if (socketTimeOutStr != null) { rcBuilder.setSocketTimeout(Integer.parseInt(socketTimeOutStr)); } return rcBuilder; } /* * Sends an HTTP response on the connection passed as a parameter with the * specified response code. If there are headers in the enumeration then it will * send the headers * * @param out The HTTP output stream * * @param responsCode The HTTP response code to be sent * * @param data Data if any. Can be null * * @param headers Headers if any to be sent */ public static void sendHTTPResponse(OutputStream out, int responseCode, ByteArrayOutputStream data, Enumeration<String> headers) throws IOException { StringBuffer httpResponse = new StringBuffer(); httpResponse.append(responseCode).append(" "); httpResponse.append(HTTPUtil.getHTTPResponseMessage(responseCode)); httpResponse.append("\r\n"); StringBuffer response = new StringBuffer("HTTP/1.1 "); response.append(httpResponse); out.write(response.toString().getBytes()); String header; if (headers != null) { boolean removeHeaderFolding = "true".equals(Properties.getProperty("remove_http_header_folding", "true")); while (headers.hasMoreElements()) { header = headers.nextElement(); // Support // https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-13#section-3.2 if (removeHeaderFolding) { header = header.replaceAll("\r\n[ \t]*", " "); } out.write((header + "\r\n").getBytes()); } } if (data == null || data.size() < 1) { // if no data will be sent, write the HTTP code or zero Content-Length boolean sendHttpCodeAsString = "true".equals(Properties.getProperty("send_http_code_as_string_when_no_data", "true")); if (sendHttpCodeAsString) { byte[] responseCodeBytes = httpResponse.toString().getBytes(); out.write(("Content-Length: " + responseCodeBytes.length + "\r\n\r\n").getBytes()); out.write(responseCodeBytes); } else { out.write("Content-Length: 0\r\n\r\n".getBytes()); } } else { out.write(("\r\n").getBytes()); //Add null line before body per RFC822 data.writeTo(out); } out.flush(); } /* * Sends an HTTP response on the connection passed as a parameter with the * specified response code. * * @param out The HTTP output stream * * @param responsCode The HTTP response code to be sent * * @param data Data if any. Can be null */ public static void sendHTTPResponse(OutputStream out, int responseCode, String data) throws IOException { ByteArrayOutputStream dataOS = null; if (data != null) { dataOS = new ByteArrayOutputStream(); dataOS.write(data.getBytes()); } sendHTTPResponse(out, responseCode, dataOS, null); } public static String printHeaders(Enumeration<Header> hdrs, String nameValueSeparator, String valuePairSeparator) { String headers = ""; while (hdrs.hasMoreElements()) { Header h = hdrs.nextElement(); headers = headers + valuePairSeparator + h.getName() + nameValueSeparator + h.getValue(); } return (headers); } public static File getTrustedCertsKeystore() throws OpenAS2Exception { File file = new File("jssecacerts"); if (!file.isFile()) { char SEP = File.separatorChar; File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); /* Check if this is a JDK home */ if (!dir.isDirectory()) { dir = new File(System.getProperty("java.home") + SEP + "jre" + SEP + "lib" + SEP + "security"); } if (!dir.isDirectory()) { throw new OpenAS2Exception("The JSSE folder could not be identified. Please check that JSSE is installed."); } file = new File(dir, "jssecacerts"); if (file.isFile() == false) { file = new File(dir, "cacerts"); } } return file; } public static String getParamsString(Map<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); result.append("&"); } String resultString = result.toString(); return resultString.length() > 0 ? resultString.substring(0, resultString.length() - 1) : resultString; } public static boolean isLocalhostBound(InetAddress addr) { // Check if the address is a valid special local or loop back if (addr.isAnyLocalAddress() || addr.isLoopbackAddress()) { return true; } // Check if the address is defined on any interface try { return NetworkInterface.getByInetAddress(addr) != null; } catch (SocketException e) { return false; } } /** * @param url * @param output * @param input * @param useCaches * @param requestMethod * @return * @throws OpenAS2Exception * @deprecated Use post method to send messages */ public static HttpURLConnection getConnection(String url, boolean output, boolean input, boolean useCaches, String requestMethod) throws OpenAS2Exception { if (url == null) { throw new OpenAS2Exception("HTTP getConnection method received empty URL string."); } try { initializeProxyAuthenticator(); HttpURLConnection conn; URL urlObj = new URL(url); if (urlObj.getProtocol().equalsIgnoreCase("https")) { HttpsURLConnection connS = (HttpsURLConnection) urlObj.openConnection(getProxy("https")); String selfSignedCN = System.getProperty("org.openas2.cert.TrustSelfSignedCN"); if (selfSignedCN != null) { File file = new File("jssecacerts"); if (file.isFile() == false) { char SEP = File.separatorChar; File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); /* Check if this is a JDK home */ if (!dir.isDirectory()) { dir = new File(System.getProperty("java.home") + SEP + "jre" + SEP + "lib" + SEP + "security"); } if (!dir.isDirectory()) { throw new OpenAS2Exception("The JSSE folder could not be identified. Please check that JSSE is installed."); } file = new File(dir, "jssecacerts"); if (file.isFile() == false) { file = new File(dir, "cacerts"); } } InputStream in = new FileInputStream(file); try { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, "changeit".toCharArray()); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SelfSignedTrustManager tm = new SelfSignedTrustManager(defaultTrustManager); tm.setTrustCN(selfSignedCN); context.init(null, new TrustManager[]{tm}, null); connS.setSSLSocketFactory(context.getSocketFactory()); } catch (Exception e) { throw new OpenAS2Exception("Self-signed certificate URL connection failed connecting to : " + url, e); } } conn = connS; } else { conn = (HttpURLConnection) urlObj.openConnection(getProxy("http")); } conn.setDoOutput(output); conn.setDoInput(input); conn.setUseCaches(useCaches); conn.setRequestMethod(requestMethod); return conn; } catch (IOException ioe) { throw new WrappedException("URL connection failed connecting to: " + url, ioe); } } private static void setProxyConfig(HttpClientBuilder builder, RequestConfig.Builder rcBuilder, String protocol) throws OpenAS2Exception { String proxyHost = Properties.getProperty(protocol + ".proxyHost", null); if (proxyHost == null) { proxyHost = System.getProperty(protocol + ".proxyHost"); } if (proxyHost == null) { return; } String proxyPort = Properties.getProperty(protocol + ".proxyPort", null); if (proxyPort == null) { proxyPort = System.getProperty(protocol + ".proxyPort"); } if (proxyPort == null) { throw new OpenAS2Exception("Missing PROXY port since Proxy host is set"); } int port = Integer.parseInt(proxyPort); HttpHost proxy = new HttpHost(proxyHost, port); rcBuilder.setProxy(proxy); String proxyUser1 = Properties.getProperty("http.proxyUser", null); final String proxyUser = proxyUser1 == null ? System.getProperty("http.proxyUser") : proxyUser1; if (proxyUser == null) { return; } String proxyPwd1 = Properties.getProperty("http.proxyPassword", null); final String proxyPassword = proxyPwd1 == null ? System.getProperty("http.proxyPassword") : proxyPwd1; CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyHost, port), new UsernamePasswordCredentials(proxyUser, proxyPassword)); builder.setDefaultCredentialsProvider(credsProvider); } /** * @param protocol * @return * @throws OpenAS2Exception * @deprecated - use post method to send messages */ private static Proxy getProxy(String protocol) throws OpenAS2Exception { String proxyHost = Properties.getProperty(protocol + ".proxyHost", null); if (proxyHost == null) { proxyHost = System.getProperty(protocol + ".proxyHost"); } if (proxyHost == null) { return Proxy.NO_PROXY; } String proxyPort = Properties.getProperty(protocol + ".proxyPort", null); if (proxyPort == null) { proxyPort = System.getProperty(protocol + ".proxyPort"); } if (proxyPort == null) { throw new OpenAS2Exception("Missing PROXY port since Proxy host is set"); } int port = Integer.parseInt(proxyPort); return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, port)); } /** * @deprecated - use post method to send messages */ private static void initializeProxyAuthenticator() { String proxyUser1 = Properties.getProperty("http.proxyUser", null); final String proxyUser = proxyUser1 == null ? System.getProperty("http.proxyUser") : proxyUser1; String proxyPwd1 = Properties.getProperty("http.proxyPassword", null); final String proxyPassword = proxyPwd1 == null ? System.getProperty("http.proxyPassword") : proxyPwd1; if (proxyUser != null && proxyPassword != null) { Authenticator.setDefault(new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()); } }); } } // Copy headers from an Http connection to an InternetHeaders object public static void copyHttpHeaders(HttpURLConnection conn, InternetHeaders headers) { Iterator<Map.Entry<String, List<String>>> connHeadersIt = conn.getHeaderFields().entrySet().iterator(); Iterator<String> connValuesIt; Map.Entry<String, List<String>> connHeader; String headerName; while (connHeadersIt.hasNext()) { connHeader = connHeadersIt.next(); headerName = connHeader.getKey(); if (headerName != null) { connValuesIt = connHeader.getValue().iterator(); while (connValuesIt.hasNext()) { String value = connValuesIt.next(); String[] existingVals = headers.getHeader(headerName); if (existingVals == null) { headers.setHeader(headerName, value); } else { // Avoid duplicates of the same value since headers that exist in the HTTP // headers // may already have been inserted in the Message object boolean exists = false; for (int i = 0; i < existingVals.length; i++) { if (value.equals(existingVals[i])) { exists = true; } } if (!exists) { headers.addHeader(headerName, value); } } } } } } private static class SelfSignedTrustManager implements X509TrustManager { private final X509TrustManager tm; private String[] trustCN = null; SelfSignedTrustManager(X509TrustManager tm) { this.tm = tm; } public X509Certificate[] getAcceptedIssuers() { return tm.getAcceptedIssuers(); } public void checkClientTrusted(X509Certificate[] chain, String authType) { throw new UnsupportedOperationException(); } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (chain.length == 1) { // Only ignore the check for self signed certs where CN (Canonical Name) matches String dn = chain[0].getIssuerX500Principal().getName(); for (int i = 0; i < trustCN.length; i++) { if (dn.contains("CN=" + trustCN[i])) { return; } } } tm.checkServerTrusted(chain, authType); } public void setTrustCN(String trustCN) { this.trustCN = trustCN.split(","); } } }
Server/src/main/java/org/openas2/util/HTTPUtil.java
package org.openas2.util; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.PasswordAuthentication; import java.net.Proxy; import java.net.SocketException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.security.KeyStore; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import javax.mail.Header; import javax.mail.MessagingException; import javax.mail.internet.InternetHeaders; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpHost; import org.apache.http.NameValuePair; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.BufferedHttpEntity; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.InputStreamEntity; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.ssl.SSLContexts; import org.openas2.OpenAS2Exception; import org.openas2.WrappedException; import org.openas2.message.Message; /** * @author Christopher */ public class HTTPUtil { public static final String MA_HTTP_REQ_TYPE = "HTTP_REQUEST_TYPE"; public static final String MA_HTTP_REQ_URL = "HTTP_REQUEST_URL"; public static final String HTTP_PROP_REMOVE_HEADER_FOLDING = "remove_http_header_folding"; public static final String HTTP_PROP_SSL_PROTOCOLS = "http_ssl_protocols"; public static final String HTTP_PROP_OVERRIDE_SSL_CHECKS = "http_override_ssl_checks"; public static final String PARAM_READ_TIMEOUT = "readtimeout"; public static final String PARAM_CONNECT_TIMEOUT = "connecttimeout"; public static final String PARAM_SOCKET_TIMEOUT = "sockettimeout"; public static final String PARAM_HTTP_USER = "http_user"; public static final String PARAM_HTTP_PWD = "http_password"; public static final String HEADER_CONTENT_TYPE = "Content-Type"; public static final String HEADER_USER_AGENT = "User-Agent"; public static final String HEADER_CONNECTION = "Connection"; public abstract static class Method { public static final String GET = "GET"; public static final String HEAD = "HEAD"; public static final String POST = "POST"; public static final String PUT = "PUT"; public static final String DELETE = "DELETE"; public static final String TRACE = "TRACE"; public static final String CONNECT = "CONNECT"; } private static final Map<Integer, String> httpResponseCodeToPhrase = new HashMap<Integer, String>() { private static final long serialVersionUID = 1L; { put(100, "Continue"); put(101, "Switching Protocols"); put(200, "OK"); put(201, "Created"); put(202, "Accepted"); put(203, "Non-Authoritative Information"); put(204, "No Content"); put(205, "Reset Content"); put(206, "Partial Content"); put(300, "Multiple Choices"); put(301, "Moved Permanently"); put(302, "Found"); put(303, "See Other"); put(304, "Not Modified"); put(305, "Use Proxy"); put(307, "Temporary Redirect"); put(400, "Bad Request"); put(401, "Unauthorized"); put(402, "Payment Required"); put(403, "Forbidden"); put(404, "Not Found"); put(405, "Method Not Allowed"); put(406, "Not Acceptable"); put(407, "Proxy Authentication Required"); put(408, "Request Time-out"); put(409, "Conflict"); put(410, "Gone"); put(411, "Length Required"); put(412, "Precondition Failed"); put(413, "Request Entity Too Large"); put(414, "Request-URI Too Large"); put(415, "Unsupported Media Type"); put(416, "Requested range not satisfiable"); put(417, "Expectation Failed"); put(500, "Internal Server Error"); put(501, "Not Implemented"); put(502, "Bad Gateway"); put(503, "Service Unavailable"); put(504, "Gateway Time-out"); put(505, "HTTP Version not supported"); } }; public static String getHTTPResponseMessage(int responseCode) { String code = httpResponseCodeToPhrase.get(responseCode); return (code == null) ? "Unknown" : code; } public static byte[] readHTTP(InputStream inStream, OutputStream outStream, InternetHeaders headerCache, List<String> httpRequest) throws IOException, MessagingException { byte[] data = null; Log logger = LogFactory.getLog(HTTPUtil.class.getSimpleName()); // Get the stream and read in the HTTP request and headers BufferedInputStream in = new BufferedInputStream(inStream); String[] request = HTTPUtil.readRequest(in); for (int i = 0; i < request.length; i++) { httpRequest.add(request[i]); } headerCache.load(in); if (logger.isTraceEnabled()) { logger.trace("HTTP received request: " + request[0] + " " + request[1] + "\n\tHeaders: " + printHeaders(headerCache.getAllHeaders(), "==", ";;")); } DataInputStream dataIn = new DataInputStream(in); // Retrieve the message content if (headerCache.getHeader("Content-Length") == null) { String transfer_encoding = headerCache.getHeader("Transfer-Encoding", ","); if (transfer_encoding != null) { if (transfer_encoding.replaceAll("\\s+", "").equalsIgnoreCase("chunked")) { int length = 0; data = null; for (; ; ) { // First get hex chunk length; followed by CRLF int blocklen = 0; for (; ; ) { int ch = dataIn.readByte(); if (ch == '\n') { break; } if (ch >= 'a' && ch <= 'f') { ch -= ('a' - 10); } else if (ch >= 'A' && ch <= 'F') { ch -= ('A' - 10); } else if (ch >= '0' && ch <= '9') { ch -= '0'; } else { continue; } blocklen = (blocklen * 16) + ch; } // Zero length is end of chunks if (blocklen == 0) { break; } // Ok, now read new chunk int newlen = length + blocklen; byte[] newdata = new byte[newlen]; if (length > 0) { System.arraycopy(data, 0, newdata, 0, length); } dataIn.readFully(newdata, length, blocklen); data = newdata; length = newlen; // And now the CRLF after the chunk; while (dataIn.readByte() != '\n') { ; } } headerCache.setHeader("Content-Length", Integer.toString(length)); } else { if (outStream != null) { HTTPUtil.sendHTTPResponse(outStream, HttpURLConnection.HTTP_LENGTH_REQUIRED, null); } throw new IOException("Transfer-Encoding unimplemented: " + transfer_encoding); } } else { return null; } } else { // Receive the transmission's data int contentSize = Integer.parseInt(headerCache.getHeader("Content-Length", ",")); data = new byte[contentSize]; dataIn.readFully(data); } return data; } /* * TODO: Move this out of HTTPUtil class so that class does not depend on AS2 * specific stuff */ public static byte[] readData(InputStream inStream, OutputStream outStream, Message msg) throws IOException, MessagingException { List<String> request = new ArrayList<String>(2); byte[] data = readHTTP(inStream, outStream, msg.getHeaders(), request); msg.setAttribute(MA_HTTP_REQ_TYPE, request.get(0)); msg.setAttribute(MA_HTTP_REQ_URL, request.get(1)); if (data == null) { String healthCheckUri = Properties.getProperty("health_check_uri", "healthcheck"); if ("GET".equalsIgnoreCase(request.get(0)) && request.get(1).matches("^[/]{0,1}" + healthCheckUri + "*")) { if (outStream != null) { HTTPUtil.sendHTTPResponse(outStream, HttpURLConnection.HTTP_OK, null); msg.setAttribute("isHealthCheck", "true"); // provide means for caller to know what happened } return null; } else { HTTPUtil.sendHTTPResponse(outStream, HttpURLConnection.HTTP_LENGTH_REQUIRED, null); Log logger = LogFactory.getLog(HTTPUtil.class.getSimpleName()); logger.error("Inbound HTTP request does not provide means to determine data length: " + request.get(0) + " " + request.get(1) + "\n\tHeaders: " + printHeaders(msg.getHeaders().getAllHeaders(), "==", ";;")); throw new IOException("Content-Length missing and no \"Transfer-Encoding\" header found to determine how to read message body."); } } cleanIdHeaders(msg.getHeaders()); return data; } /** * Cleans specific headers to ensure AS2 compatibility * * @param hdrs Headers to be cleaned */ public static void cleanIdHeaders(InternetHeaders hdrs) { // Handle the case where the AS2 ID could be encapsulated in double quotes per RFC4130 // some AS2 applications will send the quoted AND the unquoted ID so need String[] idHeaders = {"AS2-From", "AS2-To"}; for (int i = 0; i < idHeaders.length; i++) { // Target only the first entry if there is more than one to get a single value String value = StringUtil.removeDoubleQuotes(hdrs.getHeader(idHeaders[i], null)); // Delete all headers with the same key hdrs.removeHeader(idHeaders[i]); // Add back as a single value without quotes hdrs.setHeader(idHeaders[i], value); } } public static String[] readRequest(InputStream in) throws IOException { int byteBuf = in.read(); StringBuffer strBuf = new StringBuffer(); while ((byteBuf != -1) && (byteBuf != '\r')) { strBuf.append((char) byteBuf); byteBuf = in.read(); } if (byteBuf != -1) { in.read(); // read in the \n } StringTokenizer tokens = new StringTokenizer(strBuf.toString(), " "); int tokenCount = tokens.countTokens(); if (tokenCount >= 3) { String[] requestParts = new String[tokenCount]; for (int i = 0; i < tokenCount; i++) { requestParts[i] = tokens.nextToken(); } return requestParts; } else if (tokenCount == 2) { String[] requestParts = new String[3]; requestParts[0] = tokens.nextToken(); requestParts[1] = "/"; requestParts[2] = tokens.nextToken(); return requestParts; } else { throw new IOException("Invalid HTTP Request: Token Count - " + tokenCount + "::: String length - " + strBuf.length() + " ::: String - " + strBuf.toString()); } } /** * Execute a request via HTTP * * @param method GET, PUT, POST, DELETE, etc * @param url The remote connection string * @param headers HTTP headers to be sent * @param params Parameters for the get. Can be null. * @param inputStream Source stream for retrieving request data * @param options Any additional options for affecting request behaviour. Can NOT be null. * @param noChunkMaxSize The maximum size before chunking would need to be utilised. 0 disables check for chunking * @return ResponseWrapper * @throws Exception */ public static ResponseWrapper execRequest(String method, String url, Enumeration<Header> headers, NameValuePair[] params, InputStream inputStream, Map<String, String> options, long noChunkMaxSize) throws Exception { HttpClientBuilder httpBuilder = HttpClientBuilder.create(); URL urlObj = new URL(url); /* * httpClient is used for this request only, * set a connection manager that manages just one connection. */ if (urlObj.getProtocol().equalsIgnoreCase("https")) { /* * Note: registration of a custom SSLSocketFactory via httpBuilder.setSSLSocketFactory is ignored when a connection manager is set. * The custom SSLSocketFactory needs to be registered together with the connection manager. */ SSLConnectionSocketFactory sslCsf = buildSslFactory(urlObj, options); httpBuilder.setConnectionManager(new BasicHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslCsf).build())); } else { httpBuilder.setConnectionManager(new BasicHttpClientConnectionManager()); } RequestBuilder rb = getRequestBuilder(method, urlObj, params, headers); RequestConfig.Builder rcBuilder = buildRequestConfig(options); setProxyConfig(httpBuilder, rcBuilder, urlObj.getProtocol()); rb.setConfig(rcBuilder.build()); String httpUser = options.get(HTTPUtil.PARAM_HTTP_USER); String httpPwd = options.get(HTTPUtil.PARAM_HTTP_PWD); if (httpUser != null) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(httpUser, httpPwd)); httpBuilder.setDefaultCredentialsProvider(credentialsProvider); } if (inputStream != null) { if (noChunkMaxSize > 0L) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); long copied = IOUtils.copyLarge(inputStream, bout, 0L, noChunkMaxSize + 1, new byte[8192]); if (copied > noChunkMaxSize) { throw new IOException("Mime inputstream too big to put in memory (more than " + noChunkMaxSize + " bytes)."); } ByteArrayEntity bae = new ByteArrayEntity(bout.toByteArray(), null); rb.setEntity(bae); } else { InputStreamEntity ise = new InputStreamEntity(inputStream); // Use a BufferedEntity for BasicAuth connections to avoid the NonRepeatableRequestExceotion if (httpUser != null) { rb.setEntity(new BufferedHttpEntity(ise)); } else { rb.setEntity(ise); } } } final HttpUriRequest request = rb.build(); BasicHttpContext localcontext = new BasicHttpContext(); BasicScheme basicAuth = new BasicScheme(); localcontext.setAttribute("preemptive-auth", basicAuth); try (CloseableHttpClient httpClient = httpBuilder.build()) { ProfilerStub transferStub = Profiler.startProfile(); try (CloseableHttpResponse response = httpClient.execute(request, localcontext)) { ResponseWrapper resp = new ResponseWrapper(response); Profiler.endProfile(transferStub); resp.setTransferTimeMs(transferStub.getMilliseconds()); for (org.apache.http.Header header : response.getAllHeaders()) { resp.addHeaderLine(header.toString()); } return resp; } } } private static SSLConnectionSocketFactory buildSslFactory(URL urlObj, Map<String, String> options) throws Exception { boolean overrideSslChecks = "true".equalsIgnoreCase(options.get(HTTPUtil.HTTP_PROP_OVERRIDE_SSL_CHECKS)); SSLContext sslcontext; String selfSignedCN = System.getProperty("org.openas2.cert.TrustSelfSignedCN"); if ((selfSignedCN != null && selfSignedCN.contains(urlObj.getHost())) || overrideSslChecks) { File file = getTrustedCertsKeystore(); KeyStore ks = null; try (InputStream in = new FileInputStream(file)) { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, "changeit".toCharArray()); } try { // Trust own CA and all self-signed certs sslcontext = SSLContexts.custom().loadTrustMaterial(ks, new TrustSelfSignedStrategy()).build(); // Allow TLSv1 protocol only by default } catch (Exception e) { throw new OpenAS2Exception("Self-signed certificate URL connection failed connecting to : " + urlObj.toString(), e); } } else { sslcontext = SSLContexts.createSystemDefault(); } // String [] protocols = Properties.getProperty(HTTP_PROP_SSL_PROTOCOLS, // "TLSv1").split("\\s*,\\s*"); HostnameVerifier hnv = SSLConnectionSocketFactory.getDefaultHostnameVerifier(); if (overrideSslChecks) { hnv = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; } SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, null, null, hnv); return sslsf; } private static RequestBuilder getRequestBuilder(String method, URL urlObj, NameValuePair[] params, Enumeration<Header> headers) throws URISyntaxException { RequestBuilder req = null; if (method == null || method.equalsIgnoreCase(Method.GET)) { //default get req = RequestBuilder.get(); } else if (method.equalsIgnoreCase(Method.POST)) { req = RequestBuilder.post(); } else if (method.equalsIgnoreCase(Method.HEAD)) { req = RequestBuilder.head(); } else if (method.equalsIgnoreCase(Method.PUT)) { req = RequestBuilder.put(); } else if (method.equalsIgnoreCase(Method.DELETE)) { req = RequestBuilder.delete(); } else if (method.equalsIgnoreCase(Method.TRACE)) { req = RequestBuilder.trace(); } else { throw new IllegalArgumentException("Illegal HTTP Method: " + method); } req.setUri(urlObj.toURI()); if (params != null && params.length > 0) { req.addParameters(params); } if (headers != null) { boolean removeHeaderFolding = "true".equals(Properties.getProperty(HTTP_PROP_REMOVE_HEADER_FOLDING, "true")); while (headers.hasMoreElements()) { Header header = headers.nextElement(); String headerValue = header.getValue(); if (removeHeaderFolding) { headerValue = headerValue.replaceAll("\r\n[ \t]*", " "); } req.setHeader(header.getName(), headerValue); } } return req; } private static RequestConfig.Builder buildRequestConfig(Map<String, String> options) { String connectTimeOutStr = options.get(PARAM_CONNECT_TIMEOUT); String socketTimeOutStr = options.get(PARAM_SOCKET_TIMEOUT); RequestConfig.Builder rcBuilder = RequestConfig.custom(); if (connectTimeOutStr != null) { rcBuilder.setConnectTimeout(Integer.parseInt(connectTimeOutStr)); } if (socketTimeOutStr != null) { rcBuilder.setSocketTimeout(Integer.parseInt(socketTimeOutStr)); } return rcBuilder; } /* * Sends an HTTP response on the connection passed as a parameter with the * specified response code. If there are headers in the enumeration then it will * send the headers * * @param out The HTTP output stream * * @param responsCode The HTTP response code to be sent * * @param data Data if any. Can be null * * @param headers Headers if any to be sent */ public static void sendHTTPResponse(OutputStream out, int responseCode, ByteArrayOutputStream data, Enumeration<String> headers) throws IOException { StringBuffer httpResponse = new StringBuffer(); httpResponse.append(responseCode).append(" "); httpResponse.append(HTTPUtil.getHTTPResponseMessage(responseCode)); httpResponse.append("\r\n"); StringBuffer response = new StringBuffer("HTTP/1.1 "); response.append(httpResponse); out.write(response.toString().getBytes()); String header; if (headers != null) { boolean removeHeaderFolding = "true".equals(Properties.getProperty("remove_http_header_folding", "true")); while (headers.hasMoreElements()) { header = headers.nextElement(); // Support // https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-13#section-3.2 if (removeHeaderFolding) { header = header.replaceAll("\r\n[ \t]*", " "); } out.write((header + "\r\n").getBytes()); } } if (data == null || data.size() < 1) { // if no data will be sent, write the HTTP code or zero Content-Length boolean sendHttpCodeAsString = "true".equals(Properties.getProperty("send_http_code_as_string_when_no_data", "true")); if (sendHttpCodeAsString) { byte[] responseCodeBytes = httpResponse.toString().getBytes(); out.write(("Content-Length: " + responseCodeBytes.length + "\r\n\r\n").getBytes()); out.write(responseCodeBytes); } else { out.write("Content-Length: 0\r\n\r\n".getBytes()); } } else { out.write(("\r\n").getBytes()); //Add null line before body per RFC822 data.writeTo(out); } out.flush(); } /* * Sends an HTTP response on the connection passed as a parameter with the * specified response code. * * @param out The HTTP output stream * * @param responsCode The HTTP response code to be sent * * @param data Data if any. Can be null */ public static void sendHTTPResponse(OutputStream out, int responseCode, String data) throws IOException { ByteArrayOutputStream dataOS = null; if (data != null) { dataOS = new ByteArrayOutputStream(); dataOS.write(data.getBytes()); } sendHTTPResponse(out, responseCode, dataOS, null); } public static String printHeaders(Enumeration<Header> hdrs, String nameValueSeparator, String valuePairSeparator) { String headers = ""; while (hdrs.hasMoreElements()) { Header h = hdrs.nextElement(); headers = headers + valuePairSeparator + h.getName() + nameValueSeparator + h.getValue(); } return (headers); } public static File getTrustedCertsKeystore() throws OpenAS2Exception { File file = new File("jssecacerts"); if (!file.isFile()) { char SEP = File.separatorChar; File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); /* Check if this is a JDK home */ if (!dir.isDirectory()) { dir = new File(System.getProperty("java.home") + SEP + "jre" + SEP + "lib" + SEP + "security"); } if (!dir.isDirectory()) { throw new OpenAS2Exception("The JSSE folder could not be identified. Please check that JSSE is installed."); } file = new File(dir, "jssecacerts"); if (file.isFile() == false) { file = new File(dir, "cacerts"); } } return file; } public static String getParamsString(Map<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); result.append("&"); } String resultString = result.toString(); return resultString.length() > 0 ? resultString.substring(0, resultString.length() - 1) : resultString; } public static boolean isLocalhostBound(InetAddress addr) { // Check if the address is a valid special local or loop back if (addr.isAnyLocalAddress() || addr.isLoopbackAddress()) { return true; } // Check if the address is defined on any interface try { return NetworkInterface.getByInetAddress(addr) != null; } catch (SocketException e) { return false; } } /** * @param url * @param output * @param input * @param useCaches * @param requestMethod * @return * @throws OpenAS2Exception * @deprecated Use post method to send messages */ public static HttpURLConnection getConnection(String url, boolean output, boolean input, boolean useCaches, String requestMethod) throws OpenAS2Exception { if (url == null) { throw new OpenAS2Exception("HTTP getConnection method received empty URL string."); } try { initializeProxyAuthenticator(); HttpURLConnection conn; URL urlObj = new URL(url); if (urlObj.getProtocol().equalsIgnoreCase("https")) { HttpsURLConnection connS = (HttpsURLConnection) urlObj.openConnection(getProxy("https")); String selfSignedCN = System.getProperty("org.openas2.cert.TrustSelfSignedCN"); if (selfSignedCN != null) { File file = new File("jssecacerts"); if (file.isFile() == false) { char SEP = File.separatorChar; File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); /* Check if this is a JDK home */ if (!dir.isDirectory()) { dir = new File(System.getProperty("java.home") + SEP + "jre" + SEP + "lib" + SEP + "security"); } if (!dir.isDirectory()) { throw new OpenAS2Exception("The JSSE folder could not be identified. Please check that JSSE is installed."); } file = new File(dir, "jssecacerts"); if (file.isFile() == false) { file = new File(dir, "cacerts"); } } InputStream in = new FileInputStream(file); try { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, "changeit".toCharArray()); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SelfSignedTrustManager tm = new SelfSignedTrustManager(defaultTrustManager); tm.setTrustCN(selfSignedCN); context.init(null, new TrustManager[]{tm}, null); connS.setSSLSocketFactory(context.getSocketFactory()); } catch (Exception e) { throw new OpenAS2Exception("Self-signed certificate URL connection failed connecting to : " + url, e); } } conn = connS; } else { conn = (HttpURLConnection) urlObj.openConnection(getProxy("http")); } conn.setDoOutput(output); conn.setDoInput(input); conn.setUseCaches(useCaches); conn.setRequestMethod(requestMethod); return conn; } catch (IOException ioe) { throw new WrappedException("URL connection failed connecting to: " + url, ioe); } } private static void setProxyConfig(HttpClientBuilder builder, RequestConfig.Builder rcBuilder, String protocol) throws OpenAS2Exception { String proxyHost = Properties.getProperty(protocol + ".proxyHost", null); if (proxyHost == null) { proxyHost = System.getProperty(protocol + ".proxyHost"); } if (proxyHost == null) { return; } String proxyPort = Properties.getProperty(protocol + ".proxyPort", null); if (proxyPort == null) { proxyPort = System.getProperty(protocol + ".proxyPort"); } if (proxyPort == null) { throw new OpenAS2Exception("Missing PROXY port since Proxy host is set"); } int port = Integer.parseInt(proxyPort); HttpHost proxy = new HttpHost(proxyHost, port); rcBuilder.setProxy(proxy); String proxyUser1 = Properties.getProperty("http.proxyUser", null); final String proxyUser = proxyUser1 == null ? System.getProperty("http.proxyUser") : proxyUser1; if (proxyUser == null) { return; } String proxyPwd1 = Properties.getProperty("http.proxyPassword", null); final String proxyPassword = proxyPwd1 == null ? System.getProperty("http.proxyPassword") : proxyPwd1; CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyHost, port), new UsernamePasswordCredentials(proxyUser, proxyPassword)); builder.setDefaultCredentialsProvider(credsProvider); } /** * @param protocol * @return * @throws OpenAS2Exception * @deprecated - use post method to send messages */ private static Proxy getProxy(String protocol) throws OpenAS2Exception { String proxyHost = Properties.getProperty(protocol + ".proxyHost", null); if (proxyHost == null) { proxyHost = System.getProperty(protocol + ".proxyHost"); } if (proxyHost == null) { return Proxy.NO_PROXY; } String proxyPort = Properties.getProperty(protocol + ".proxyPort", null); if (proxyPort == null) { proxyPort = System.getProperty(protocol + ".proxyPort"); } if (proxyPort == null) { throw new OpenAS2Exception("Missing PROXY port since Proxy host is set"); } int port = Integer.parseInt(proxyPort); return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, port)); } /** * @deprecated - use post method to send messages */ private static void initializeProxyAuthenticator() { String proxyUser1 = Properties.getProperty("http.proxyUser", null); final String proxyUser = proxyUser1 == null ? System.getProperty("http.proxyUser") : proxyUser1; String proxyPwd1 = Properties.getProperty("http.proxyPassword", null); final String proxyPassword = proxyPwd1 == null ? System.getProperty("http.proxyPassword") : proxyPwd1; if (proxyUser != null && proxyPassword != null) { Authenticator.setDefault(new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()); } }); } } // Copy headers from an Http connection to an InternetHeaders object public static void copyHttpHeaders(HttpURLConnection conn, InternetHeaders headers) { Iterator<Map.Entry<String, List<String>>> connHeadersIt = conn.getHeaderFields().entrySet().iterator(); Iterator<String> connValuesIt; Map.Entry<String, List<String>> connHeader; String headerName; while (connHeadersIt.hasNext()) { connHeader = connHeadersIt.next(); headerName = connHeader.getKey(); if (headerName != null) { connValuesIt = connHeader.getValue().iterator(); while (connValuesIt.hasNext()) { String value = connValuesIt.next(); String[] existingVals = headers.getHeader(headerName); if (existingVals == null) { headers.setHeader(headerName, value); } else { // Avoid duplicates of the same value since headers that exist in the HTTP // headers // may already have been inserted in the Message object boolean exists = false; for (int i = 0; i < existingVals.length; i++) { if (value.equals(existingVals[i])) { exists = true; } } if (!exists) { headers.addHeader(headerName, value); } } } } } } private static class SelfSignedTrustManager implements X509TrustManager { private final X509TrustManager tm; private String[] trustCN = null; SelfSignedTrustManager(X509TrustManager tm) { this.tm = tm; } public X509Certificate[] getAcceptedIssuers() { return tm.getAcceptedIssuers(); } public void checkClientTrusted(X509Certificate[] chain, String authType) { throw new UnsupportedOperationException(); } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (chain.length == 1) { // Only ignore the check for self signed certs where CN (Canonical Name) matches String dn = chain[0].getIssuerX500Principal().getName(); for (int i = 0; i < trustCN.length; i++) { if (dn.contains("CN=" + trustCN[i])) { return; } } } tm.checkServerTrusted(chain, authType); } public void setTrustCN(String trustCN) { this.trustCN = trustCN.split(","); } } }
Avoid IOException when missing Content-Length (#266) This happens when someone just opens the as2 url in a browser. The exception causes more noise than needed since the information is already being logged as well.
Server/src/main/java/org/openas2/util/HTTPUtil.java
Avoid IOException when missing Content-Length (#266)
Java
bsd-3-clause
8e8ea289b39d58b9ec86355585acfc185d5f7d60
0
mdeanda/ajaxproxy,mdeanda/ajaxproxy,mdeanda/ajaxproxy
package com.thedeanda.ajaxproxy.ui; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JEditorPane; import javax.swing.JFileChooser; import javax.swing.JList; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.plaf.basic.BasicSplitPaneDivider; import javax.swing.plaf.basic.BasicSplitPaneUI; import javax.swing.text.Document; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import net.miginfocom.swing.MigLayout; import net.sourceforge.javajson.JsonArray; import net.sourceforge.javajson.JsonException; import net.sourceforge.javajson.JsonObject; import net.sourceforge.javajson.JsonValue; import org.apache.commons.lang.StringUtils; import com.thedeanda.ajaxproxy.AccessTracker; import com.thedeanda.ajaxproxy.AjaxProxy; import com.thedeanda.ajaxproxy.LoadedResource; /** tracks files that get loaded */ public class ResourceViewerPanel extends JPanel implements AccessTracker, ActionListener { private static final long serialVersionUID = 1L; private static final int INPUT_TAB = 1; private static final int INPUT_FORMATTED_TAB = 2; private static final int INPUT_TREE_TAB = 3; private static final int OUTPUT_TAB = 4; private static final int OUTPUT_FORMATTED_TAB = 5; private static final int OUTPUT_TREE_TAB = 6; private JButton clearBtn; private JButton exportBtn; private JCheckBox toggleBtn; private DefaultListModel model; private JList list; private JTabbedPane tabs; private JTextArea outputContent; private JScrollPane outputScroll; private JTextArea inputContent; private JScrollPane inputScroll; private JEditorPane headersContent; private JScrollPane headersScroll; private JTextArea inputFormattedContent; private JScrollPane inputFormattedScroll; private JTextArea outputFormattedContent; private JScrollPane outputFormattedScroll; private JTextField filter; private Color okColor; private Color badColor; private Pattern filterRegEx; private JMenuItem removeRequestMenuItem; private JTree outputInteractive; private JScrollPane outputInteractiveScroll; private DefaultTreeModel outputTreeModel; private DefaultMutableTreeNode rootOutputNode; private DefaultMutableTreeNode rootInputNode; private DefaultTreeModel inputTreeModel; private JTree inputInteractive; private JScrollPane inputInteractiveScroll; public ResourceViewerPanel() { setLayout(new MigLayout("fill", "[][][grow]", "[][fill]")); model = new DefaultListModel(); clearBtn = new JButton("Clear"); exportBtn = new JButton("Export"); toggleBtn = new JCheckBox("Monitor Resources"); clearBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { model.clear(); showResource(null); } }); exportBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { export(); } }); add(clearBtn); add(exportBtn); add(toggleBtn, "align right, wrap"); JPanel leftPanel = new JPanel(new MigLayout("insets 0, fill", "[fill]", "")); leftPanel.setBorder(BorderFactory.createEmptyBorder()); filter = new JTextField(); leftPanel.add(filter, "growx, wrap"); // Listen for changes in the text okColor = filter.getBackground(); badColor = new Color(240, 220, 200); filter.getDocument().addDocumentListener(new DocumentListener() { public void changedUpdate(DocumentEvent e) { resetFilter(); } public void removeUpdate(DocumentEvent e) { resetFilter(); } public void insertUpdate(DocumentEvent e) { resetFilter(); } }); final JPopupMenu popup = new JPopupMenu(); removeRequestMenuItem = new JMenuItem("Remove Request"); removeRequestMenuItem.addActionListener(this); popup.add(removeRequestMenuItem); list = new JList(model); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent evt) { listItemSelected(evt); } }); list.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { maybeShowPopup(e); } @Override public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { list.setSelectedIndex(list.locationToIndex(e.getPoint())); if (e.isPopupTrigger() && list.getSelectedIndex() >= 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } }); list.setBorder(BorderFactory.createEmptyBorder()); leftPanel.add(new JScrollPane(list), "grow"); HTMLEditorKit kit = new HTMLEditorKit(); StyleSheet styleSheet = kit.getStyleSheet(); styleSheet .addRule("body {color:#000000; margin: 4px; font-size: 10px; font-family: sans-serif; }"); styleSheet.addRule("h1 { margin: 4px 0; font-size: 12px; }"); styleSheet.addRule("div.items { margin-left: 10px;}"); styleSheet.addRule("p { margin: 0; font-family: monospace;}"); styleSheet.addRule("b { font-family: sans-serif; color: #444444;}"); headersContent = new JEditorPane(); headersContent.setEditable(false); headersScroll = new JScrollPane(headersContent); headersContent.setEditorKit(kit); Document doc = kit.createDefaultDocument(); headersContent.setDocument(doc); inputContent = new JTextArea(); inputContent.setEditable(false); inputScroll = new JScrollPane(inputContent); inputFormattedContent = new JTextArea(); inputFormattedContent.setEditable(false); inputFormattedScroll = new JScrollPane(inputFormattedContent); rootInputNode = new DefaultMutableTreeNode(""); inputTreeModel = new DefaultTreeModel(rootInputNode); initTree(rootInputNode, new JsonObject()); inputInteractive = new JTree(inputTreeModel); inputInteractiveScroll = new JScrollPane(inputInteractive); inputInteractive.setShowsRootHandles(true); outputContent = new JTextArea(); outputContent.setEditable(false); outputScroll = new JScrollPane(outputContent); outputFormattedContent = new JTextArea(); outputFormattedContent.setEditable(false); outputFormattedScroll = new JScrollPane(outputFormattedContent); rootOutputNode = new DefaultMutableTreeNode(""); outputTreeModel = new DefaultTreeModel(rootOutputNode); initTree(rootOutputNode, new JsonObject()); outputInteractive = new JTree(outputTreeModel); outputInteractiveScroll = new JScrollPane(outputInteractive); outputInteractive.setShowsRootHandles(true); tabs = new JTabbedPane(); tabs.add("Headers", headersScroll); tabs.add("Input", inputScroll); tabs.add("Input (tabbed)", inputFormattedScroll); tabs.add("Input (tree)", inputInteractiveScroll); tabs.add("Output", outputScroll); tabs.add("Output (tabbed)", outputFormattedScroll); tabs.add("Output (tree)", outputInteractiveScroll); tabs.setBorder(BorderFactory.createEmptyBorder()); JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); split.setLeftComponent(leftPanel); split.setRightComponent(tabs); split.setDividerLocation(200); split.setBorder(BorderFactory.createEmptyBorder()); flattenSplitPane(split); add(split, "span 3, growx, growy"); } private void initTree(DefaultMutableTreeNode top, JsonObject obj) { for (String key : obj) { JsonValue val = obj.get(key); if (val.isJsonObject()) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(key); top.add(node); initTree(node, val.getJsonObject()); } else if (val.isJsonArray()) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(key); top.add(node); initTree(node, val.getJsonArray()); } else { DefaultMutableTreeNode node = new DefaultMutableTreeNode(key + "=" + val.toString()); top.add(node); } } } private void initTree(DefaultMutableTreeNode top, JsonArray arr) { int i = 0; for (JsonValue val : arr) { if (val.isJsonObject()) { DefaultMutableTreeNode node = new DefaultMutableTreeNode("[" + i + "]"); top.add(node); initTree(node, val.getJsonObject()); } else if (val.isJsonArray()) { DefaultMutableTreeNode node = new DefaultMutableTreeNode("[" + i + "]"); top.add(node); initTree(node, val.getJsonArray()); } else { DefaultMutableTreeNode node = new DefaultMutableTreeNode( val.toString()); top.add(node); } i++; } } public static void flattenSplitPane(JSplitPane jSplitPane) { jSplitPane.setUI(new BasicSplitPaneUI() { public BasicSplitPaneDivider createDefaultDivider() { return new BasicSplitPaneDivider(this) { private static final long serialVersionUID = 1L; public void setBorder(Border b) { } }; } }); jSplitPane.setBorder(null); } private void listItemSelected(ListSelectionEvent evt) { if (!evt.getValueIsAdjusting()) { LoadedResource lr = (LoadedResource) list.getSelectedValue(); if (lr != null) { showResource(lr); } } } private void showResource(final LoadedResource lr) { outputContent.setText(""); inputContent.setText(""); headersContent.setText(""); inputFormattedContent.setText(""); outputFormattedContent.setText(""); rootOutputNode.removeAllChildren(); outputTreeModel.reload(); rootInputNode.removeAllChildren(); inputTreeModel.reload(); if (lr != null) { final DataHolder holder = new DataHolder(); final Runnable uiupdate = new Runnable() { @Override public void run() { headersContent.setText(holder.headers); headersContent.setCaretPosition(0); inputContent.setText(holder.input); inputContent.setCaretPosition(0); if (holder.input == null) tabs.setEnabledAt(INPUT_TAB, false); else tabs.setEnabledAt(INPUT_TAB, true); if (holder.inputFormatted != null) { inputFormattedContent.setText(holder.inputFormatted); inputFormattedContent.setCaretPosition(0); tabs.setEnabledAt(INPUT_FORMATTED_TAB, true); } else { tabs.setEnabledAt(INPUT_FORMATTED_TAB, false); } try { JsonObject obj = JsonObject.parse(holder.input); initTree(rootInputNode, obj); inputTreeModel.reload(); tabs.setEnabledAt(INPUT_TREE_TAB, true); } catch (Exception e) { tabs.setEnabledAt(INPUT_TREE_TAB, false); } try { JsonObject obj = JsonObject.parse(holder.output); initTree(rootOutputNode, obj); outputTreeModel.reload(); tabs.setEnabledAt(OUTPUT_TREE_TAB, true); } catch (Exception e) { tabs.setEnabledAt(OUTPUT_TREE_TAB, false); } outputContent.setText(holder.output); outputContent.setCaretPosition(0); if (holder.output == null) tabs.setEnabledAt(OUTPUT_TAB, false); else tabs.setEnabledAt(OUTPUT_TAB, true); if (holder.outputFormatted != null) { outputFormattedContent.setText(holder.outputFormatted); outputFormattedContent.setCaretPosition(0); tabs.setEnabledAt(OUTPUT_FORMATTED_TAB, true); } else { tabs.setEnabledAt(OUTPUT_FORMATTED_TAB, false); } } }; new Thread(new Runnable() { @Override public void run() { holder.input = lr.getInputAsText(); if (holder.input != null && holder.input.trim().equals("")) holder.input = null; holder.inputFormatted = tryFormatting(holder.input); holder.output = lr.getOutputAsText(); if (holder.output != null && holder.output.trim().equals("")) holder.output = null; holder.outputFormatted = tryFormatting(holder.output); StringBuffer headers = new StringBuffer(); Map<String, String> map = lr.getHeaders(); headers.append("<html><body>"); headers.append("<p><b>URL:</b> "); headers.append(lr.getUrl()); headers.append("</p>"); headers.append("<p><b>Method:</b> "); headers.append(lr.getMethod()); headers.append("</p>"); headers.append("<p><b>Duration:</b> "); headers.append(lr.getDuration()); headers.append("</p>"); writeField(headers, "Status", String.valueOf(lr.getStatusCode())); headers.append("<h1>Headers</h1><div class=\"items\">"); for (String name : map.keySet()) { headers.append("<p><b>"); headers.append(name); headers.append(":</b> "); headers.append(map.get(name)); headers.append("</p>"); } headers.append("</div></body></html>"); holder.headers = headers.toString(); SwingUtilities.invokeLater(uiupdate); } }).start(); } } private void writeField(StringBuffer headers, String name, String value) { headers.append("<p><b>"); headers.append(name); headers.append(":</b> "); headers.append(value); headers.append("</p>"); } private String tryFormatting(String str) { String ret = null; if (str == null) return null; str = str.trim(); if (str.startsWith("{") || str.startsWith("[")) { // try json parsing try { ret = JsonObject.parse(str).toString(4); } catch (JsonException je) { ret = null; } } else if (str.startsWith("<")) { // try xml parsing ret = null; } return ret; } public void setProxy(AjaxProxy proxy) { if (proxy != null) proxy.addTracker(this); } @Override public void trackFile(LoadedResource res) { boolean show = toggleBtn.isSelected(); if (show && filterRegEx != null) { Matcher matcher = filterRegEx.matcher(res.getUrl()); if (matcher.matches()) show = true; else show = false; } if (show) { model.addElement(res); } } private void resetFilter() { try { filterRegEx = Pattern.compile(filter.getText()); filter.setBackground(okColor); } catch (PatternSyntaxException ex) { filterRegEx = null; filter.setBackground(badColor); } } private void export() { String urlPrefix = JOptionPane.showInputDialog("URL Prefix", "http://localhost"); final JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File folder = fc.getSelectedFile(); String path = folder.getAbsolutePath(); for (int i = 0; i < model.getSize(); i++) { LoadedResource obj = (LoadedResource) model.get(i); String fn = StringUtils.leftPad(String.valueOf(i), 8, "0"); JsonObject json = new JsonObject(); json.put("url", urlPrefix + obj.getUrl()); try { json.put("input", JsonObject.parse(obj.getInputAsText())); } catch (JsonException e1) { json.put("input", obj.getInputAsText()); e1.printStackTrace(); } try { json.put("output", JsonObject.parse(obj.getOutputAsText())); } catch (JsonException e1) { json.put("output", obj.getOutputAsText()); e1.printStackTrace(); } json.put("status", obj.getStatusCode()); json.put("duration", obj.getDuration()); json.put("method", obj.getMethod()); JsonObject headers = new JsonObject(); json.put("headers", headers); Map<String, String> hdrs = obj.getHeaders(); for (String key : hdrs.keySet()) { headers.put(key, hdrs.get(key)); } Writer writer = null; try { writer = new OutputStreamWriter(new FileOutputStream( new File(path + File.separator + fn + ".txt")), "UTF-8"); writer.write(json.toString(4)); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } } } class DataHolder { public String input; public String inputFormatted; public String output; public String outputFormatted; public String headers; } @Override public void actionPerformed(ActionEvent evt) { if (evt.getSource() == removeRequestMenuItem) { int index = list.getSelectedIndex(); if (index >= 0) { model.remove(index); if (model.getSize() > index) list.setSelectedIndex(index); else if (!model.isEmpty()) { list.setSelectedIndex(index - 1); } } } } }
src/com/thedeanda/ajaxproxy/ui/ResourceViewerPanel.java
package com.thedeanda.ajaxproxy.ui; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JEditorPane; import javax.swing.JFileChooser; import javax.swing.JList; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.plaf.basic.BasicSplitPaneDivider; import javax.swing.plaf.basic.BasicSplitPaneUI; import javax.swing.text.Document; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import net.miginfocom.swing.MigLayout; import net.sourceforge.javajson.JsonArray; import net.sourceforge.javajson.JsonException; import net.sourceforge.javajson.JsonObject; import net.sourceforge.javajson.JsonValue; import org.apache.commons.lang.StringUtils; import com.thedeanda.ajaxproxy.AccessTracker; import com.thedeanda.ajaxproxy.AjaxProxy; import com.thedeanda.ajaxproxy.LoadedResource; /** tracks files that get loaded */ public class ResourceViewerPanel extends JPanel implements AccessTracker, ActionListener { private static final long serialVersionUID = 1L; private static final int INPUT_TAB = 1; private static final int INPUT_FORMATTED_TAB = 2; private static final int OUTPUT_TAB = 3; private static final int OUTPUT_FORMATTED_TAB = 4; private JButton clearBtn; private JButton exportBtn; private JCheckBox toggleBtn; private DefaultListModel model; private JList list; private JTabbedPane tabs; private JTextArea outputContent; private JScrollPane outputScroll; private JTextArea inputContent; private JScrollPane inputScroll; private JEditorPane headersContent; private JScrollPane headersScroll; private JTextArea inputFormattedContent; private JScrollPane inputFormattedScroll; private JTextArea outputFormattedContent; private JScrollPane outputFormattedScroll; private JTextField filter; private Color okColor; private Color badColor; private Pattern filterRegEx; private JMenuItem removeRequestMenuItem; private JTree outputInteractive; private JScrollPane outputInteractiveScroll; private DefaultTreeModel outputTreeModel; private DefaultMutableTreeNode rootOutputNode; public ResourceViewerPanel() { setLayout(new MigLayout("fill", "[][][grow]", "[][fill]")); model = new DefaultListModel(); clearBtn = new JButton("Clear"); exportBtn = new JButton("Export"); toggleBtn = new JCheckBox("Monitor Resources"); clearBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { model.clear(); showResource(null); } }); exportBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { export(); } }); add(clearBtn); add(exportBtn); add(toggleBtn, "align right, wrap"); JPanel leftPanel = new JPanel(new MigLayout("insets 0, fill", "[fill]", "")); leftPanel.setBorder(BorderFactory.createEmptyBorder()); filter = new JTextField(); leftPanel.add(filter, "growx, wrap"); // Listen for changes in the text okColor = filter.getBackground(); badColor = new Color(240, 220, 200); filter.getDocument().addDocumentListener(new DocumentListener() { public void changedUpdate(DocumentEvent e) { resetFilter(); } public void removeUpdate(DocumentEvent e) { resetFilter(); } public void insertUpdate(DocumentEvent e) { resetFilter(); } }); final JPopupMenu popup = new JPopupMenu(); removeRequestMenuItem = new JMenuItem("Remove Request"); removeRequestMenuItem.addActionListener(this); popup.add(removeRequestMenuItem); list = new JList(model); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent evt) { listItemSelected(evt); } }); list.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { maybeShowPopup(e); } @Override public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { list.setSelectedIndex(list.locationToIndex(e.getPoint())); if (e.isPopupTrigger() && list.getSelectedIndex() >= 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } }); list.setBorder(BorderFactory.createEmptyBorder()); leftPanel.add(new JScrollPane(list), "grow"); HTMLEditorKit kit = new HTMLEditorKit(); StyleSheet styleSheet = kit.getStyleSheet(); styleSheet .addRule("body {color:#000000; margin: 4px; font-size: 10px; font-family: sans-serif; }"); styleSheet.addRule("h1 { margin: 4px 0; font-size: 12px; }"); styleSheet.addRule("div.items { margin-left: 10px;}"); styleSheet.addRule("p { margin: 0; font-family: monospace;}"); styleSheet.addRule("b { font-family: sans-serif; color: #444444;}"); headersContent = new JEditorPane(); headersContent.setEditable(false); headersScroll = new JScrollPane(headersContent); headersContent.setEditorKit(kit); Document doc = kit.createDefaultDocument(); headersContent.setDocument(doc); inputContent = new JTextArea(); inputContent.setEditable(false); inputScroll = new JScrollPane(inputContent); inputFormattedContent = new JTextArea(); inputFormattedContent.setEditable(false); inputFormattedScroll = new JScrollPane(inputFormattedContent); rootOutputNode = new DefaultMutableTreeNode(""); outputTreeModel = new DefaultTreeModel(rootOutputNode); initTree(rootOutputNode, new JsonObject()); outputInteractive = new JTree(outputTreeModel); outputInteractiveScroll = new JScrollPane(outputInteractive); outputInteractive.setShowsRootHandles(true); outputContent = new JTextArea(); outputContent.setEditable(false); outputScroll = new JScrollPane(outputContent); outputFormattedContent = new JTextArea(); outputFormattedContent.setEditable(false); outputFormattedScroll = new JScrollPane(outputFormattedContent); tabs = new JTabbedPane(); tabs.add("Headers", headersScroll); tabs.add("Input", inputScroll); tabs.add("Input (formatted)", inputFormattedScroll); tabs.add("Output", outputScroll); tabs.add("Output (formatted)", outputFormattedScroll); tabs.add("Output (interactive)", outputInteractiveScroll); tabs.setBorder(BorderFactory.createEmptyBorder()); JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); split.setLeftComponent(leftPanel); split.setRightComponent(tabs); split.setDividerLocation(200); split.setBorder(BorderFactory.createEmptyBorder()); flattenSplitPane(split); add(split, "span 3, growx, growy"); } private void initTree(DefaultMutableTreeNode top, JsonObject obj) { for (String key : obj) { JsonValue val = obj.get(key); if (val.isJsonObject()) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(key); top.add(node); initTree(node, val.getJsonObject()); } else if (val.isJsonArray()) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(key); top.add(node); initTree(node, val.getJsonArray()); } else { DefaultMutableTreeNode node = new DefaultMutableTreeNode(key + "=" + val.toString()); top.add(node); } } } private void initTree(DefaultMutableTreeNode top, JsonArray arr) { int i = 0; for (JsonValue val : arr) { if (val.isJsonObject()) { DefaultMutableTreeNode node = new DefaultMutableTreeNode("[" + i + "]"); top.add(node); initTree(node, val.getJsonObject()); } else if (val.isJsonArray()) { DefaultMutableTreeNode node = new DefaultMutableTreeNode("[" + i + "]"); top.add(node); initTree(node, val.getJsonArray()); } else { DefaultMutableTreeNode node = new DefaultMutableTreeNode( val.toString()); top.add(node); } i++; } } public static void flattenSplitPane(JSplitPane jSplitPane) { jSplitPane.setUI(new BasicSplitPaneUI() { public BasicSplitPaneDivider createDefaultDivider() { return new BasicSplitPaneDivider(this) { private static final long serialVersionUID = 1L; public void setBorder(Border b) { } }; } }); jSplitPane.setBorder(null); } private void listItemSelected(ListSelectionEvent evt) { if (!evt.getValueIsAdjusting()) { LoadedResource lr = (LoadedResource) list.getSelectedValue(); if (lr != null) { showResource(lr); } } } private void showResource(final LoadedResource lr) { outputContent.setText(""); inputContent.setText(""); headersContent.setText(""); inputFormattedContent.setText(""); outputFormattedContent.setText(""); rootOutputNode.removeAllChildren(); outputTreeModel.reload(); if (lr != null) { final DataHolder holder = new DataHolder(); final Runnable uiupdate = new Runnable() { @Override public void run() { headersContent.setText(holder.headers); headersContent.setCaretPosition(0); inputContent.setText(holder.input); inputContent.setCaretPosition(0); if (holder.input == null) tabs.setEnabledAt(INPUT_TAB, false); else tabs.setEnabledAt(INPUT_TAB, true); if (holder.inputFormatted != null) { inputFormattedContent.setText(holder.inputFormatted); inputFormattedContent.setCaretPosition(0); tabs.setEnabledAt(INPUT_FORMATTED_TAB, true); } else { tabs.setEnabledAt(INPUT_FORMATTED_TAB, false); } try { JsonObject obj = JsonObject.parse(holder.output); initTree(rootOutputNode, obj); outputTreeModel.reload(); } catch (JsonException e) { } outputContent.setText(holder.output); outputContent.setCaretPosition(0); if (holder.output == null) tabs.setEnabledAt(OUTPUT_TAB, false); else tabs.setEnabledAt(OUTPUT_TAB, true); if (holder.outputFormatted != null) { outputFormattedContent.setText(holder.outputFormatted); outputFormattedContent.setCaretPosition(0); tabs.setEnabledAt(OUTPUT_FORMATTED_TAB, true); } else { tabs.setEnabledAt(OUTPUT_FORMATTED_TAB, false); } } }; new Thread(new Runnable() { @Override public void run() { holder.input = lr.getInputAsText(); if (holder.input != null && holder.input.trim().equals("")) holder.input = null; holder.inputFormatted = tryFormatting(holder.input); holder.output = lr.getOutputAsText(); if (holder.output != null && holder.output.trim().equals("")) holder.output = null; holder.outputFormatted = tryFormatting(holder.output); StringBuffer headers = new StringBuffer(); Map<String, String> map = lr.getHeaders(); headers.append("<html><body>"); headers.append("<p><b>URL:</b> "); headers.append(lr.getUrl()); headers.append("</p>"); headers.append("<p><b>Method:</b> "); headers.append(lr.getMethod()); headers.append("</p>"); headers.append("<p><b>Duration:</b> "); headers.append(lr.getDuration()); headers.append("</p>"); writeField(headers, "Status", String.valueOf(lr.getStatusCode())); headers.append("<h1>Headers</h1><div class=\"items\">"); for (String name : map.keySet()) { headers.append("<p><b>"); headers.append(name); headers.append(":</b> "); headers.append(map.get(name)); headers.append("</p>"); } headers.append("</div></body></html>"); holder.headers = headers.toString(); SwingUtilities.invokeLater(uiupdate); } }).start(); } } private void writeField(StringBuffer headers, String name, String value) { headers.append("<p><b>"); headers.append(name); headers.append(":</b> "); headers.append(value); headers.append("</p>"); } private String tryFormatting(String str) { String ret = null; if (str == null) return null; str = str.trim(); if (str.startsWith("{") || str.startsWith("[")) { // try json parsing try { ret = JsonObject.parse(str).toString(4); } catch (JsonException je) { ret = null; } } else if (str.startsWith("<")) { // try xml parsing ret = null; } return ret; } public void setProxy(AjaxProxy proxy) { if (proxy != null) proxy.addTracker(this); } @Override public void trackFile(LoadedResource res) { boolean show = toggleBtn.isSelected(); if (show && filterRegEx != null) { Matcher matcher = filterRegEx.matcher(res.getUrl()); if (matcher.matches()) show = true; else show = false; } if (show) { model.addElement(res); } } private void resetFilter() { try { filterRegEx = Pattern.compile(filter.getText()); filter.setBackground(okColor); } catch (PatternSyntaxException ex) { filterRegEx = null; filter.setBackground(badColor); } } private void export() { String urlPrefix = JOptionPane.showInputDialog("URL Prefix", "http://localhost"); final JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File folder = fc.getSelectedFile(); String path = folder.getAbsolutePath(); for (int i = 0; i < model.getSize(); i++) { LoadedResource obj = (LoadedResource) model.get(i); String fn = StringUtils.leftPad(String.valueOf(i), 8, "0"); JsonObject json = new JsonObject(); json.put("url", urlPrefix + obj.getUrl()); try { json.put("input", JsonObject.parse(obj.getInputAsText())); } catch (JsonException e1) { json.put("input", obj.getInputAsText()); e1.printStackTrace(); } try { json.put("output", JsonObject.parse(obj.getOutputAsText())); } catch (JsonException e1) { json.put("output", obj.getOutputAsText()); e1.printStackTrace(); } json.put("status", obj.getStatusCode()); json.put("duration", obj.getDuration()); json.put("method", obj.getMethod()); JsonObject headers = new JsonObject(); json.put("headers", headers); Map<String, String> hdrs = obj.getHeaders(); for (String key : hdrs.keySet()) { headers.put(key, hdrs.get(key)); } Writer writer = null; try { writer = new OutputStreamWriter(new FileOutputStream( new File(path + File.separator + fn + ".txt")), "UTF-8"); writer.write(json.toString(4)); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } } } class DataHolder { public String input; public String inputFormatted; public String output; public String outputFormatted; public String headers; } @Override public void actionPerformed(ActionEvent evt) { if (evt.getSource() == removeRequestMenuItem) { int index = list.getSelectedIndex(); if (index >= 0) { model.remove(index); if (model.getSize() > index) list.setSelectedIndex(index); else if (!model.isEmpty()) { list.setSelectedIndex(index - 1); } } } } }
added jtree to input
src/com/thedeanda/ajaxproxy/ui/ResourceViewerPanel.java
added jtree to input
Java
bsd-3-clause
2777473ea3f0cbd028d018ba2131cedcb1a8e32a
0
vmluan/dhis2-core,troyel/dhis2-core,msf-oca-his/dhis-core,vmluan/dhis2-core,troyel/dhis2-core,hispindia/dhis2-Core,troyel/dhis2-core,jason-p-pickering/dhis2-core,jason-p-pickering/dhis2-core,vietnguyen/dhis2-core,troyel/dhis2-core,msf-oca-his/dhis-core,jason-p-pickering/dhis2-core,jason-p-pickering/dhis2-persian-calendar,troyel/dhis2-core,jason-p-pickering/dhis2-persian-calendar,msf-oca-his/dhis2-core,msf-oca-his/dhis2-core,vmluan/dhis2-core,dhis2/dhis2-core,hispindia/dhis2-Core,hispindia/dhis2-Core,msf-oca-his/dhis2-core,dhis2/dhis2-core,jason-p-pickering/dhis2-persian-calendar,dhis2/dhis2-core,vmluan/dhis2-core,jason-p-pickering/dhis2-persian-calendar,jason-p-pickering/dhis2-core,hispindia/dhis2-Core,msf-oca-his/dhis-core,dhis2/dhis2-core,msf-oca-his/dhis2-core,msf-oca-his/dhis-core,msf-oca-his/dhis2-core,vietnguyen/dhis2-core,vietnguyen/dhis2-core,vietnguyen/dhis2-core,msf-oca-his/dhis-core,jason-p-pickering/dhis2-core,dhis2/dhis2-core,jason-p-pickering/dhis2-persian-calendar,vmluan/dhis2-core,hispindia/dhis2-Core,vietnguyen/dhis2-core
package org.hisp.dhis.analytics.event.data; /* * Copyright (c) 2004-2016, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import static org.hisp.dhis.common.DimensionalObject.ORGUNIT_DIM_ID; import static org.hisp.dhis.common.DimensionalObject.PERIOD_DIM_ID; import static org.hisp.dhis.common.DimensionalObjectUtils.getDimensionalItemIds; import static org.hisp.dhis.common.DimensionalObjectUtils.asTypedList; import static org.hisp.dhis.organisationunit.OrganisationUnit.getParentGraphMap; import static org.hisp.dhis.organisationunit.OrganisationUnit.getParentNameGraphMap; import static org.hisp.dhis.analytics.DataQueryParams.NUMERATOR_ID; import static org.hisp.dhis.analytics.DataQueryParams.DENOMINATOR_ID; import static org.hisp.dhis.analytics.DataQueryParams.FACTOR_ID; import static org.hisp.dhis.analytics.DataQueryParams.VALUE_ID; import static org.hisp.dhis.analytics.DataQueryParams.NUMERATOR_HEADER_NAME; import static org.hisp.dhis.analytics.DataQueryParams.DENOMINATOR_HEADER_NAME; import static org.hisp.dhis.analytics.DataQueryParams.FACTOR_HEADER_NAME; import static org.hisp.dhis.analytics.DataQueryParams.VALUE_HEADER_NAME; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.hisp.dhis.analytics.AnalyticsMetaDataKey; import org.hisp.dhis.analytics.AnalyticsSecurityManager; import org.hisp.dhis.analytics.DataQueryParams; import org.hisp.dhis.analytics.Rectangle; import org.hisp.dhis.analytics.event.EventAnalyticsManager; import org.hisp.dhis.analytics.event.EventAnalyticsService; import org.hisp.dhis.analytics.event.EventDataQueryService; import org.hisp.dhis.analytics.event.EventQueryParams; import org.hisp.dhis.analytics.event.EventQueryPlanner; import org.hisp.dhis.common.AnalyticalObject; import org.hisp.dhis.common.DimensionType; import org.hisp.dhis.common.DimensionalItemObject; import org.hisp.dhis.common.DimensionalObject; import org.hisp.dhis.common.DisplayProperty; import org.hisp.dhis.common.EventAnalyticalObject; import org.hisp.dhis.common.Grid; import org.hisp.dhis.common.GridHeader; import org.hisp.dhis.common.IdentifiableObjectUtils; import org.hisp.dhis.common.IllegalQueryException; import org.hisp.dhis.common.NameableObjectUtils; import org.hisp.dhis.common.Pager; import org.hisp.dhis.common.QueryItem; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.program.Program; import org.hisp.dhis.program.ProgramStage; import org.hisp.dhis.system.database.DatabaseInfo; import org.hisp.dhis.system.grid.ListGrid; import org.hisp.dhis.user.User; import org.hisp.dhis.util.Timer; import org.springframework.beans.factory.annotation.Autowired; /** * @author Lars Helge Overland */ public class DefaultEventAnalyticsService implements EventAnalyticsService { @Autowired private EventAnalyticsManager analyticsManager; @Autowired private EventDataQueryService eventDataQueryService; @Autowired private AnalyticsSecurityManager securityManager; @Autowired private EventQueryPlanner queryPlanner; @Autowired private DatabaseInfo databaseInfo; // ------------------------------------------------------------------------- // EventAnalyticsService implementation // ------------------------------------------------------------------------- // TODO use ValueType for type in grid headers // TODO order event analytics tables on execution date to avoid default // TODO sorting in queries @Override public Grid getAggregatedEventData( EventQueryParams params ) { securityManager.decideAccess( params ); queryPlanner.validate( params ); params.removeProgramIndicatorItems(); // Not supported as items for aggregate Grid grid = new ListGrid(); int maxLimit = queryPlanner.getMaxLimit(); // --------------------------------------------------------------------- // Headers and data // --------------------------------------------------------------------- if ( !params.isSkipData() ) { // ----------------------------------------------------------------- // Headers // ----------------------------------------------------------------- if ( params.isCollapseDataDimensions() || params.isAggregateData() ) { grid.addHeader( new GridHeader( DimensionalObject.DATA_COLLAPSED_DIM_ID, DataQueryParams.DISPLAY_NAME_DATA_X, String.class.getName(), false, true ) ); } else { for ( QueryItem item : params.getItems() ) { String legendSet = item.hasLegendSet() ? item.getLegendSet().getUid() : null; grid.addHeader( new GridHeader( item.getItem().getUid(), item.getItem().getName(), item.getTypeAsString(), false, true, item.getOptionSetUid(), legendSet ) ); } } for ( DimensionalObject dimension : params.getDimensions() ) { grid.addHeader( new GridHeader( dimension.getDimension(), dimension.getDisplayName(), String.class.getName(), false, true ) ); } grid.addHeader( new GridHeader( VALUE_ID, VALUE_HEADER_NAME, Double.class.getName(), false, false ) ); if ( params.isIncludeNumDen() ) { grid.addHeader( new GridHeader( NUMERATOR_ID, NUMERATOR_HEADER_NAME, Double.class.getName(), false, false ) ) .addHeader( new GridHeader( DENOMINATOR_ID, DENOMINATOR_HEADER_NAME, Double.class.getName(), false, false ) ) .addHeader( new GridHeader( FACTOR_ID, FACTOR_HEADER_NAME, Double.class.getName(), false, false ) ); } // ----------------------------------------------------------------- // Data // ----------------------------------------------------------------- Timer timer = new Timer().start().disablePrint(); List<EventQueryParams> queries = queryPlanner.planAggregateQuery( params ); timer.getSplitTime( "Planned event query, got partitions: " + params.getPartitions() ); for ( EventQueryParams query : queries ) { analyticsManager.getAggregatedEventData( query, grid, maxLimit ); } timer.getTime( "Got aggregated events" ); if ( maxLimit > 0 && grid.getHeight() > maxLimit ) { throw new IllegalQueryException( "Number of rows produced by query is larger than the max limit: " + maxLimit ); } // ----------------------------------------------------------------- // Limit and sort, done again due to potential multiple partitions // ----------------------------------------------------------------- if ( params.hasSortOrder() ) { grid.sortGrid( 1, params.getSortOrderAsInt() ); } if ( params.hasLimit() && grid.getHeight() > params.getLimit() ) { grid.limitGrid( params.getLimit() ); } } // --------------------------------------------------------------------- // Meta-data // --------------------------------------------------------------------- if ( !params.isSkipMeta() ) { Map<String, Object> metaData = new HashMap<>(); metaData.put( AnalyticsMetaDataKey.NAMES.getKey(), getUidNameMap( params ) ); metaData.put( PERIOD_DIM_ID, getDimensionalItemIds( params.getDimensionOrFilterItems( PERIOD_DIM_ID ) ) ); metaData.put( ORGUNIT_DIM_ID, getDimensionalItemIds( params.getDimensionOrFilterItems( ORGUNIT_DIM_ID ) ) ); User user = securityManager.getCurrentUser( params ); List<OrganisationUnit> organisationUnits = asTypedList( params.getDimensionOrFilterItems( ORGUNIT_DIM_ID ) ); Collection<OrganisationUnit> roots = user != null ? user.getOrganisationUnits() : null; if ( params.isHierarchyMeta() ) { metaData.put( AnalyticsMetaDataKey.ORG_UNIT_HIERARCHY.getKey(), getParentGraphMap( organisationUnits, roots ) ); } if ( params.isShowHierarchy() ) { metaData.put( AnalyticsMetaDataKey.ORG_UNIT_NAME_HIERARCHY.getKey(), getParentNameGraphMap( organisationUnits, roots, true ) ); } grid.setMetaData( metaData ); } return grid; } @Override public Grid getAggregatedEventData( AnalyticalObject object ) { EventQueryParams params = eventDataQueryService.getFromAnalyticalObject( (EventAnalyticalObject) object ); return getAggregatedEventData( params ); } @Override public Grid getEvents( EventQueryParams params ) { securityManager.decideAccessEventQuery( params ); queryPlanner.validate( params ); params.replacePeriodsWithStartEndDates(); Grid grid = new ListGrid(); // --------------------------------------------------------------------- // Headers // --------------------------------------------------------------------- grid.addHeader( new GridHeader( ITEM_EVENT, "Event", String.class.getName(), false, true ) ) .addHeader( new GridHeader( ITEM_PROGRAM_STAGE, "Program stage", String.class.getName(), false, true ) ) .addHeader( new GridHeader( ITEM_EXECUTION_DATE, "Event date", String.class.getName(), false, true ) ) .addHeader( new GridHeader( ITEM_LONGITUDE, "Longitude", String.class.getName(), false, true ) ) .addHeader( new GridHeader( ITEM_LATITUDE, "Latitude", String.class.getName(), false, true ) ) .addHeader( new GridHeader( ITEM_ORG_UNIT_NAME, "Organisation unit name", String.class.getName(), false, true ) ) .addHeader( new GridHeader( ITEM_ORG_UNIT_CODE, "Organisation unit code", String.class.getName(), false, true ) ); for ( DimensionalObject dimension : params.getDimensions() ) { grid.addHeader( new GridHeader( dimension.getDimension(), dimension.getDisplayName(), String.class.getName(), false, true ) ); } for ( QueryItem item : params.getItems() ) { grid.addHeader( new GridHeader( item.getItem().getUid(), item.getItem().getName(), item.getTypeAsString(), false, true, item.getOptionSetUid(), item.getLegendSetUid() ) ); } // --------------------------------------------------------------------- // Data // --------------------------------------------------------------------- Timer timer = new Timer().start().disablePrint(); params = queryPlanner.planEventQuery( params ); timer.getSplitTime( "Planned event query, got partitions: " + params.getPartitions() ); long count = 0; if ( params.getPartitions().hasAny() ) { if ( params.isPaging() ) { count += analyticsManager.getEventCount( params ); } analyticsManager.getEvents( params, grid, queryPlanner.getMaxLimit() ); timer.getTime( "Got events " + grid.getHeight() ); } // --------------------------------------------------------------------- // Meta-data // --------------------------------------------------------------------- Map<String, Object> metaData = new HashMap<>(); metaData.put( AnalyticsMetaDataKey.NAMES.getKey(), getUidNameMap( params ) ); User user = securityManager.getCurrentUser( params ); Collection<OrganisationUnit> roots = user != null ? user.getOrganisationUnits() : null; if ( params.isHierarchyMeta() ) { Map<String, String> parentMap = getParentGraphMap( asTypedList( params.getDimensionOrFilterItems( ORGUNIT_DIM_ID ) ), roots ); metaData.put( AnalyticsMetaDataKey.ORG_UNIT_HIERARCHY.getKey(), parentMap ); } if ( params.isPaging() ) { Pager pager = new Pager( params.getPageWithDefault(), count, params.getPageSizeWithDefault() ); metaData.put( AnalyticsMetaDataKey.PAGER.getKey(), pager ); } return grid.setMetaData( metaData ); } @Override public Grid getEventClusters( EventQueryParams params ) { if ( !databaseInfo.isSpatialSupport() ) { throw new IllegalQueryException( "Spatial database support is not enabled" ); } params = new EventQueryParams.Builder( params ) .withGeometryOnly( true ) .build(); securityManager.decideAccess( params ); queryPlanner.validate( params ); params.replacePeriodsWithStartEndDates(); Grid grid = new ListGrid(); // --------------------------------------------------------------------- // Headers // --------------------------------------------------------------------- grid.addHeader( new GridHeader( ITEM_COUNT, "Count", Long.class.getName(), false, false ) ) .addHeader( new GridHeader( ITEM_CENTER, "Center", String.class.getName(), false, false ) ) .addHeader( new GridHeader( ITEM_EXTENT, "Extent", String.class.getName(), false, false ) ) .addHeader( new GridHeader( ITEM_POINTS, "Points", String.class.getName(), false, false ) ); // --------------------------------------------------------------------- // Data // --------------------------------------------------------------------- params = queryPlanner.planEventQuery( params ); analyticsManager.getEventClusters( params, grid, queryPlanner.getMaxLimit() ); return grid; } @Override public Rectangle getRectangle( EventQueryParams params ) { if ( !databaseInfo.isSpatialSupport() ) { throw new IllegalQueryException( "Spatial database support is not enabled" ); } params = new EventQueryParams.Builder( params ) .withGeometryOnly( true ) .build(); securityManager.decideAccess( params ); queryPlanner.validate( params ); params.replacePeriodsWithStartEndDates(); params = queryPlanner.planEventQuery( params ); return analyticsManager.getRectangle( params ); } // ------------------------------------------------------------------------- // Supportive methods // ------------------------------------------------------------------------- private Map<String, String> getUidNameMap( EventQueryParams params ) { Map<String, String> map = new HashMap<>(); Program program = params.getProgram(); ProgramStage stage = params.getProgramStage(); map.put( program.getUid(), program.getDisplayProperty( params.getDisplayProperty() ) ); if ( stage != null ) { map.put( stage.getUid(), stage.getName() ); } else { for ( ProgramStage st : program.getProgramStages() ) { map.put( st.getUid(), st.getName() ); } } if ( params.hasValueDimension() ) { map.put( params.getValue().getUid(), params.getValue().getDisplayProperty( params.getDisplayProperty() ) ); } map.putAll( getUidNameMap( params.getItems(), params.getDisplayProperty() ) ); map.putAll( getUidNameMap( params.getItemFilters(), params.getDisplayProperty() ) ); map.putAll( getUidNameMap( params.getDimensions(), params.isHierarchyMeta(), params.getDisplayProperty() ) ); map.putAll( getUidNameMap( params.getFilters(), params.isHierarchyMeta(), params.getDisplayProperty() ) ); map.putAll( IdentifiableObjectUtils.getUidNameMap( params.getLegends() ) ); return map; } private Map<String, String> getUidNameMap( List<QueryItem> queryItems, DisplayProperty displayProperty ) { Map<String, String> map = new HashMap<>(); for ( QueryItem item : queryItems ) { map.put( item.getItem().getUid(), item.getItem().getDisplayProperty( displayProperty ) ); } return map; } private Map<String, String> getUidNameMap( List<DimensionalObject> dimensions, boolean hierarchyMeta, DisplayProperty displayProperty ) { Map<String, String> map = new HashMap<>(); for ( DimensionalObject dimension : dimensions ) { boolean hierarchy = hierarchyMeta && DimensionType.ORGANISATION_UNIT.equals( dimension.getDimensionType() ); for ( DimensionalItemObject object : dimension.getItems() ) { Set<DimensionalItemObject> objects = new HashSet<>(); objects.add( object ); if ( hierarchy ) { OrganisationUnit unit = (OrganisationUnit) object; objects.addAll( unit.getAncestors() ); } map.putAll( NameableObjectUtils.getUidDisplayPropertyMap( objects, displayProperty ) ); } map.put( dimension.getDimension(), dimension.getDisplayProperty( displayProperty ) ); } return map; } }
dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/event/data/DefaultEventAnalyticsService.java
package org.hisp.dhis.analytics.event.data; /* * Copyright (c) 2004-2016, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import static org.hisp.dhis.common.DimensionalObject.ORGUNIT_DIM_ID; import static org.hisp.dhis.common.DimensionalObject.PERIOD_DIM_ID; import static org.hisp.dhis.common.DimensionalObjectUtils.getDimensionalItemIds; import static org.hisp.dhis.common.DimensionalObjectUtils.asTypedList; import static org.hisp.dhis.organisationunit.OrganisationUnit.getParentGraphMap; import static org.hisp.dhis.organisationunit.OrganisationUnit.getParentNameGraphMap; import static org.hisp.dhis.analytics.DataQueryParams.NUMERATOR_ID; import static org.hisp.dhis.analytics.DataQueryParams.DENOMINATOR_ID; import static org.hisp.dhis.analytics.DataQueryParams.FACTOR_ID; import static org.hisp.dhis.analytics.DataQueryParams.VALUE_ID; import static org.hisp.dhis.analytics.DataQueryParams.NUMERATOR_HEADER_NAME; import static org.hisp.dhis.analytics.DataQueryParams.DENOMINATOR_HEADER_NAME; import static org.hisp.dhis.analytics.DataQueryParams.FACTOR_HEADER_NAME; import static org.hisp.dhis.analytics.DataQueryParams.VALUE_HEADER_NAME; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.hisp.dhis.analytics.AnalyticsMetaDataKey; import org.hisp.dhis.analytics.AnalyticsSecurityManager; import org.hisp.dhis.analytics.DataQueryParams; import org.hisp.dhis.analytics.Rectangle; import org.hisp.dhis.analytics.event.EventAnalyticsManager; import org.hisp.dhis.analytics.event.EventAnalyticsService; import org.hisp.dhis.analytics.event.EventDataQueryService; import org.hisp.dhis.analytics.event.EventQueryParams; import org.hisp.dhis.analytics.event.EventQueryPlanner; import org.hisp.dhis.common.AnalyticalObject; import org.hisp.dhis.common.DimensionType; import org.hisp.dhis.common.DimensionalItemObject; import org.hisp.dhis.common.DimensionalObject; import org.hisp.dhis.common.DisplayProperty; import org.hisp.dhis.common.EventAnalyticalObject; import org.hisp.dhis.common.Grid; import org.hisp.dhis.common.GridHeader; import org.hisp.dhis.common.IdentifiableObjectUtils; import org.hisp.dhis.common.IllegalQueryException; import org.hisp.dhis.common.NameableObjectUtils; import org.hisp.dhis.common.Pager; import org.hisp.dhis.common.QueryItem; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.program.Program; import org.hisp.dhis.program.ProgramStage; import org.hisp.dhis.system.database.DatabaseInfo; import org.hisp.dhis.system.grid.ListGrid; import org.hisp.dhis.user.User; import org.hisp.dhis.util.Timer; import org.springframework.beans.factory.annotation.Autowired; /** * @author Lars Helge Overland */ public class DefaultEventAnalyticsService implements EventAnalyticsService { @Autowired private EventAnalyticsManager analyticsManager; @Autowired private EventDataQueryService eventDataQueryService; @Autowired private AnalyticsSecurityManager securityManager; @Autowired private EventQueryPlanner queryPlanner; @Autowired private DatabaseInfo databaseInfo; // ------------------------------------------------------------------------- // EventAnalyticsService implementation // ------------------------------------------------------------------------- // TODO use ValueType for type in grid headers // TODO order event analytics tables on execution date to avoid default // TODO sorting in queries @Override public Grid getAggregatedEventData( EventQueryParams params ) { securityManager.decideAccess( params ); queryPlanner.validate( params ); params.removeProgramIndicatorItems(); // Not supported as items for aggregate Grid grid = new ListGrid(); int maxLimit = queryPlanner.getMaxLimit(); // --------------------------------------------------------------------- // Headers and data // --------------------------------------------------------------------- if ( !params.isSkipData() ) { // ----------------------------------------------------------------- // Headers // ----------------------------------------------------------------- if ( params.isCollapseDataDimensions() || params.isAggregateData() ) { grid.addHeader( new GridHeader( DimensionalObject.DATA_COLLAPSED_DIM_ID, DataQueryParams.DISPLAY_NAME_DATA_X, String.class.getName(), false, true ) ); } else { for ( QueryItem item : params.getItems() ) { String legendSet = item.hasLegendSet() ? item.getLegendSet().getUid() : null; grid.addHeader( new GridHeader( item.getItem().getUid(), item.getItem().getName(), item.getTypeAsString(), false, true, item.getOptionSetUid(), legendSet ) ); } } for ( DimensionalObject dimension : params.getDimensions() ) { grid.addHeader( new GridHeader( dimension.getDimension(), dimension.getDisplayName(), String.class.getName(), false, true ) ); } grid.addHeader( new GridHeader( VALUE_ID, VALUE_HEADER_NAME, Double.class.getName(), false, false ) ); if ( params.isIncludeNumDen() ) { grid.addHeader( new GridHeader( NUMERATOR_ID, NUMERATOR_HEADER_NAME, Double.class.getName(), false, false ) ) .addHeader( new GridHeader( DENOMINATOR_ID, DENOMINATOR_HEADER_NAME, Double.class.getName(), false, false ) ) .addHeader( new GridHeader( FACTOR_ID, FACTOR_HEADER_NAME, Double.class.getName(), false, false ) ); } // ----------------------------------------------------------------- // Data // ----------------------------------------------------------------- Timer timer = new Timer().start().disablePrint(); List<EventQueryParams> queries = queryPlanner.planAggregateQuery( params ); timer.getSplitTime( "Planned event query, got partitions: " + params.getPartitions() ); for ( EventQueryParams query : queries ) { analyticsManager.getAggregatedEventData( query, grid, maxLimit ); } timer.getTime( "Got aggregated events" ); if ( maxLimit > 0 && grid.getHeight() > maxLimit ) { throw new IllegalQueryException( "Number of rows produced by query is larger than the max limit: " + maxLimit ); } // ----------------------------------------------------------------- // Limit and sort, done again due to potential multiple partitions // ----------------------------------------------------------------- if ( params.hasSortOrder() ) { grid.sortGrid( 1, params.getSortOrderAsInt() ); } if ( params.hasLimit() && grid.getHeight() > params.getLimit() ) { grid.limitGrid( params.getLimit() ); } } // --------------------------------------------------------------------- // Meta-data // --------------------------------------------------------------------- if ( !params.isSkipMeta() ) { Map<String, Object> metaData = new HashMap<>(); metaData.put( AnalyticsMetaDataKey.NAMES.getKey(), getUidNameMap( params ) ); metaData.put( PERIOD_DIM_ID, getDimensionalItemIds( params.getDimensionOrFilterItems( PERIOD_DIM_ID ) ) ); metaData.put( ORGUNIT_DIM_ID, getDimensionalItemIds( params.getDimensionOrFilterItems( ORGUNIT_DIM_ID ) ) ); User user = securityManager.getCurrentUser( params ); List<OrganisationUnit> organisationUnits = asTypedList( params.getDimensionOrFilterItems( ORGUNIT_DIM_ID ) ); Collection<OrganisationUnit> roots = user != null ? user.getOrganisationUnits() : null; if ( params.isHierarchyMeta() ) { metaData.put( AnalyticsMetaDataKey.ORG_UNIT_HIERARCHY.getKey(), getParentGraphMap( organisationUnits, roots ) ); } if ( params.isShowHierarchy() ) { metaData.put( AnalyticsMetaDataKey.ORG_UNIT_NAME_HIERARCHY.getKey(), getParentNameGraphMap( organisationUnits, roots, true ) ); } grid.setMetaData( metaData ); } return grid; } @Override public Grid getAggregatedEventData( AnalyticalObject object ) { EventQueryParams params = eventDataQueryService.getFromAnalyticalObject( (EventAnalyticalObject) object ); return getAggregatedEventData( params ); } @Override public Grid getEvents( EventQueryParams params ) { securityManager.decideAccessEventQuery( params ); queryPlanner.validate( params ); params.replacePeriodsWithStartEndDates(); Grid grid = new ListGrid(); // --------------------------------------------------------------------- // Headers // --------------------------------------------------------------------- grid.addHeader( new GridHeader( ITEM_EVENT, "Event", String.class.getName(), false, true ) ) .addHeader( new GridHeader( ITEM_PROGRAM_STAGE, "Program stage", String.class.getName(), false, true ) ) .addHeader( new GridHeader( ITEM_EXECUTION_DATE, "Event date", String.class.getName(), false, true ) ) .addHeader( new GridHeader( ITEM_LONGITUDE, "Longitude", Double.class.getName(), false, true ) ) .addHeader( new GridHeader( ITEM_LATITUDE, "Latitude", Double.class.getName(), false, true ) ) .addHeader( new GridHeader( ITEM_ORG_UNIT_NAME, "Organisation unit name", String.class.getName(), false, true ) ) .addHeader( new GridHeader( ITEM_ORG_UNIT_CODE, "Organisation unit code", String.class.getName(), false, true ) ); for ( DimensionalObject dimension : params.getDimensions() ) { grid.addHeader( new GridHeader( dimension.getDimension(), dimension.getDisplayName(), String.class.getName(), false, true ) ); } for ( QueryItem item : params.getItems() ) { grid.addHeader( new GridHeader( item.getItem().getUid(), item.getItem().getName(), item.getTypeAsString(), false, true, item.getOptionSetUid(), item.getLegendSetUid() ) ); } // --------------------------------------------------------------------- // Data // --------------------------------------------------------------------- Timer timer = new Timer().start().disablePrint(); params = queryPlanner.planEventQuery( params ); timer.getSplitTime( "Planned event query, got partitions: " + params.getPartitions() ); long count = 0; if ( params.getPartitions().hasAny() ) { if ( params.isPaging() ) { count += analyticsManager.getEventCount( params ); } analyticsManager.getEvents( params, grid, queryPlanner.getMaxLimit() ); timer.getTime( "Got events " + grid.getHeight() ); } // --------------------------------------------------------------------- // Meta-data // --------------------------------------------------------------------- Map<String, Object> metaData = new HashMap<>(); metaData.put( AnalyticsMetaDataKey.NAMES.getKey(), getUidNameMap( params ) ); User user = securityManager.getCurrentUser( params ); Collection<OrganisationUnit> roots = user != null ? user.getOrganisationUnits() : null; if ( params.isHierarchyMeta() ) { Map<String, String> parentMap = getParentGraphMap( asTypedList( params.getDimensionOrFilterItems( ORGUNIT_DIM_ID ) ), roots ); metaData.put( AnalyticsMetaDataKey.ORG_UNIT_HIERARCHY.getKey(), parentMap ); } if ( params.isPaging() ) { Pager pager = new Pager( params.getPageWithDefault(), count, params.getPageSizeWithDefault() ); metaData.put( AnalyticsMetaDataKey.PAGER.getKey(), pager ); } return grid.setMetaData( metaData ); } @Override public Grid getEventClusters( EventQueryParams params ) { if ( !databaseInfo.isSpatialSupport() ) { throw new IllegalQueryException( "Spatial database support is not enabled" ); } params = new EventQueryParams.Builder( params ) .withGeometryOnly( true ) .build(); securityManager.decideAccess( params ); queryPlanner.validate( params ); params.replacePeriodsWithStartEndDates(); Grid grid = new ListGrid(); // --------------------------------------------------------------------- // Headers // --------------------------------------------------------------------- grid.addHeader( new GridHeader( ITEM_COUNT, "Count", Long.class.getName(), false, false ) ) .addHeader( new GridHeader( ITEM_CENTER, "Center", String.class.getName(), false, false ) ) .addHeader( new GridHeader( ITEM_EXTENT, "Extent", String.class.getName(), false, false ) ) .addHeader( new GridHeader( ITEM_POINTS, "Points", String.class.getName(), false, false ) ); // --------------------------------------------------------------------- // Data // --------------------------------------------------------------------- params = queryPlanner.planEventQuery( params ); analyticsManager.getEventClusters( params, grid, queryPlanner.getMaxLimit() ); return grid; } @Override public Rectangle getRectangle( EventQueryParams params ) { if ( !databaseInfo.isSpatialSupport() ) { throw new IllegalQueryException( "Spatial database support is not enabled" ); } params = new EventQueryParams.Builder( params ) .withGeometryOnly( true ) .build(); securityManager.decideAccess( params ); queryPlanner.validate( params ); params.replacePeriodsWithStartEndDates(); params = queryPlanner.planEventQuery( params ); return analyticsManager.getRectangle( params ); } // ------------------------------------------------------------------------- // Supportive methods // ------------------------------------------------------------------------- private Map<String, String> getUidNameMap( EventQueryParams params ) { Map<String, String> map = new HashMap<>(); Program program = params.getProgram(); ProgramStage stage = params.getProgramStage(); map.put( program.getUid(), program.getDisplayProperty( params.getDisplayProperty() ) ); if ( stage != null ) { map.put( stage.getUid(), stage.getName() ); } else { for ( ProgramStage st : program.getProgramStages() ) { map.put( st.getUid(), st.getName() ); } } if ( params.hasValueDimension() ) { map.put( params.getValue().getUid(), params.getValue().getDisplayProperty( params.getDisplayProperty() ) ); } map.putAll( getUidNameMap( params.getItems(), params.getDisplayProperty() ) ); map.putAll( getUidNameMap( params.getItemFilters(), params.getDisplayProperty() ) ); map.putAll( getUidNameMap( params.getDimensions(), params.isHierarchyMeta(), params.getDisplayProperty() ) ); map.putAll( getUidNameMap( params.getFilters(), params.isHierarchyMeta(), params.getDisplayProperty() ) ); map.putAll( IdentifiableObjectUtils.getUidNameMap( params.getLegends() ) ); return map; } private Map<String, String> getUidNameMap( List<QueryItem> queryItems, DisplayProperty displayProperty ) { Map<String, String> map = new HashMap<>(); for ( QueryItem item : queryItems ) { map.put( item.getItem().getUid(), item.getItem().getDisplayProperty( displayProperty ) ); } return map; } private Map<String, String> getUidNameMap( List<DimensionalObject> dimensions, boolean hierarchyMeta, DisplayProperty displayProperty ) { Map<String, String> map = new HashMap<>(); for ( DimensionalObject dimension : dimensions ) { boolean hierarchy = hierarchyMeta && DimensionType.ORGANISATION_UNIT.equals( dimension.getDimensionType() ); for ( DimensionalItemObject object : dimension.getItems() ) { Set<DimensionalItemObject> objects = new HashSet<>(); objects.add( object ); if ( hierarchy ) { OrganisationUnit unit = (OrganisationUnit) object; objects.addAll( unit.getAncestors() ); } map.putAll( NameableObjectUtils.getUidDisplayPropertyMap( objects, displayProperty ) ); } map.put( dimension.getDimension(), dimension.getDisplayProperty( displayProperty ) ); } return map; } }
Event query, long/lat rounding
dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/event/data/DefaultEventAnalyticsService.java
Event query, long/lat rounding
Java
mit
a2979b5170214e8cb024f34142cc57d3d1a8ba55
0
obraliar/jabref,jhshinn/jabref,Siedlerchr/jabref,grimes2/jabref,Braunch/jabref,oscargus/jabref,oscargus/jabref,mairdl/jabref,tschechlovdev/jabref,shitikanth/jabref,Mr-DLib/jabref,grimes2/jabref,motokito/jabref,grimes2/jabref,motokito/jabref,sauliusg/jabref,zellerdev/jabref,zellerdev/jabref,tobiasdiez/jabref,JabRef/jabref,zellerdev/jabref,jhshinn/jabref,jhshinn/jabref,zellerdev/jabref,Mr-DLib/jabref,sauliusg/jabref,mairdl/jabref,mredaelli/jabref,obraliar/jabref,JabRef/jabref,mredaelli/jabref,shitikanth/jabref,ayanai1/jabref,mredaelli/jabref,jhshinn/jabref,mairdl/jabref,Braunch/jabref,JabRef/jabref,ayanai1/jabref,Siedlerchr/jabref,shitikanth/jabref,obraliar/jabref,JabRef/jabref,Siedlerchr/jabref,grimes2/jabref,sauliusg/jabref,motokito/jabref,zellerdev/jabref,grimes2/jabref,bartsch-dev/jabref,oscargus/jabref,tschechlovdev/jabref,mairdl/jabref,Braunch/jabref,bartsch-dev/jabref,Mr-DLib/jabref,mairdl/jabref,Braunch/jabref,tobiasdiez/jabref,mredaelli/jabref,ayanai1/jabref,shitikanth/jabref,oscargus/jabref,ayanai1/jabref,Braunch/jabref,obraliar/jabref,bartsch-dev/jabref,Siedlerchr/jabref,oscargus/jabref,Mr-DLib/jabref,bartsch-dev/jabref,shitikanth/jabref,motokito/jabref,sauliusg/jabref,jhshinn/jabref,ayanai1/jabref,Mr-DLib/jabref,bartsch-dev/jabref,motokito/jabref,tschechlovdev/jabref,tschechlovdev/jabref,tschechlovdev/jabref,tobiasdiez/jabref,mredaelli/jabref,obraliar/jabref,tobiasdiez/jabref
/* Copyright (C) 2003-2014 JabRef contributors. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package net.sf.jabref; import com.jgoodies.looks.plastic.Plastic3DLookAndFeel; import com.jgoodies.looks.plastic.theme.SkyBluer; import java.awt.Font; import java.awt.Frame; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Vector; import java.util.prefs.BackingStoreException; import javax.swing.*; import javax.swing.plaf.FontUIResource; import net.sf.jabref.export.AutoSaveManager; import net.sf.jabref.export.ExportFormats; import net.sf.jabref.export.FileActions; import net.sf.jabref.export.IExportFormat; import net.sf.jabref.export.SaveException; import net.sf.jabref.export.SaveSession; import net.sf.jabref.imports.*; import net.sf.jabref.plugin.PluginCore; import net.sf.jabref.plugin.PluginInstaller; import net.sf.jabref.plugin.SidePanePlugin; import net.sf.jabref.plugin.core.JabRefPlugin; import net.sf.jabref.plugin.core.generated._JabRefPlugin; import net.sf.jabref.plugin.core.generated._JabRefPlugin.EntryFetcherExtension; import net.sf.jabref.remote.RemoteListener; import net.sf.jabref.wizard.auximport.AuxCommandLine; import com.sun.jna.Native; import com.sun.jna.NativeLong; import com.sun.jna.Pointer; import com.sun.jna.WString; import com.sun.jna.ptr.PointerByReference; /** * JabRef Main Class - The application gets started here. * */ public class JabRef { public static JabRef singleton; public static RemoteListener remoteListener = null; public static JabRefFrame jrf; public static Frame splashScreen = null; boolean graphicFailure = false; public static final int MAX_DIALOG_WARNINGS = 10; private JabRefCLI cli; public static void main(String[] args) { new JabRef(args); } protected JabRef(String[] args) { singleton = this; JabRefPreferences prefs = JabRefPreferences.getInstance(); // See if there are plugins scheduled for deletion: if (prefs.hasKey("deletePlugins") && (prefs.get("deletePlugins").length() > 0)) { String[] toDelete = prefs.getStringArray("deletePlugins"); PluginInstaller.deletePluginsOnStartup(toDelete); prefs.put("deletePlugins", ""); } if (prefs.getBoolean("useProxy")) { // NetworkTab.java ensures that proxyHostname and proxyPort are not null System.getProperties().put("http.proxyHost", prefs.get("proxyHostname")); System.getProperties().put("http.proxyPort", prefs.get("proxyPort")); // currently, the following cannot be configured if (prefs.get("proxyUsername") != null) { System.getProperties().put("http.proxyUser", prefs.get("proxyUsername")); System.getProperties().put("http.proxyPassword", prefs.get("proxyPassword")); } } else { // The following two lines signal that the system proxy settings // should be used: System.setProperty("java.net.useSystemProxies", "true"); System.getProperties().put("proxySet", "true"); } Globals.startBackgroundTasks(); Globals.setupLogging(); Globals.prefs = prefs; String langStr = prefs.get("language"); String[] parts = langStr.split("_"); String language, country; if (parts.length == 1) { language = langStr; country = ""; } else { language = parts[0]; country = parts[1]; } Globals.setLanguage(language, country); Globals.prefs.setLanguageDependentDefaultValues(); /* * The Plug-in System is started automatically on the first call to * PluginCore.getManager(). * * Plug-ins are activated on the first call to their getInstance method. */ // Update which fields should be treated as numeric, based on preferences: BibtexFields.setNumericFieldsFromPrefs(); /* Build list of Import and Export formats */ Globals.importFormatReader.resetImportFormats(); BibtexEntryType.loadCustomEntryTypes(prefs); ExportFormats.initAllExports(); // Read list(s) of journal names and abbreviations: Globals.initializeJournalNames(); // Check for running JabRef if (Globals.prefs.getBoolean("useRemoteServer")) { remoteListener = RemoteListener.openRemoteListener(this); if (remoteListener == null) { // Unless we are alone, try to contact already running JabRef: if (RemoteListener.sendToActiveJabRefInstance(args)) { /* * We have successfully sent our command line options * through the socket to another JabRef instance. So we * assume it's all taken care of, and quit. */ System.out.println( Globals.lang("Arguments passed on to running JabRef instance. Shutting down.")); System.exit(0); } } else { // No listener found, thus we are the first instance to be // started. remoteListener.start(); } } /* * See if the user has a personal journal list set up. If so, add these * journal names and abbreviations to the list: */ String personalJournalList = prefs.get("personalJournalList"); if (personalJournalList != null && !personalJournalList.isEmpty()) { try { Globals.journalAbbrev.readJournalList(new File( personalJournalList)); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, Globals.lang("Journal file not found") + ": " + e.getMessage(), Globals.lang("Error opening file"), JOptionPane.ERROR_MESSAGE); Globals.prefs.put("personalJournalList", ""); } } // override used newline character with the one stored in the preferences // The preferences return the system newline character sequence as default Globals.NEWLINE = Globals.prefs.get(JabRefPreferences.NEWLINE); Globals.NEWLINE_LENGTH = Globals.NEWLINE.length(); if (Globals.ON_WIN) { // Set application user model id so that pinning JabRef to the Win7/8 taskbar works // Based on http://stackoverflow.com/a/1928830 setCurrentProcessExplicitAppUserModelID("JabRef." + Globals.VERSION); //System.out.println(getCurrentProcessExplicitAppUserModelID()); } openWindow(processArguments(args, true)); } // Do not use this code in release version, it contains some memory leaks public static String getCurrentProcessExplicitAppUserModelID() { final PointerByReference r = new PointerByReference(); if (GetCurrentProcessExplicitAppUserModelID(r).longValue() == 0) { final Pointer p = r.getValue(); return p.getString(0, true); // here we leak native memory by lazyness } return "N/A"; } public static void setCurrentProcessExplicitAppUserModelID(final String appID) { if (SetCurrentProcessExplicitAppUserModelID(new WString(appID)).longValue() != 0) throw new RuntimeException("unable to set current process explicit AppUserModelID to: " + appID); } private static native NativeLong GetCurrentProcessExplicitAppUserModelID(PointerByReference appID); private static native NativeLong SetCurrentProcessExplicitAppUserModelID(WString appID); static { if (Globals.ON_WIN) { Native.register("shell32"); } } public Vector<ParserResult> processArguments(String[] args, boolean initialStartup) { cli = new JabRefCLI(args); if (initialStartup && cli.isShowVersion()) { cli.options.displayVersion(); cli.disableGui.setInvoked(true); } if (initialStartup && cli.isHelp()) { System.out.println("jabref [options] [bibtex-file]\n"); System.out.println(cli.getHelp()); String importFormats = Globals.importFormatReader.getImportFormatList(); System.out.println(Globals.lang("Available import formats") + ":\n" + importFormats); String outFormats = ExportFormats.getConsoleExportList(70, 20, "\t"); System.out.println(Globals.lang("Available export formats") + ": " + outFormats + "."); System.exit(0); } boolean commandmode = cli.isDisableGui() || cli.fetcherEngine.isInvoked(); // First we quickly scan the command line parameters for any that signal // that the GUI // should not be opened. This is used to decide whether we should show the // splash screen or not. if (initialStartup && !commandmode && !cli.isDisableSplash()) { try { splashScreen = SplashScreen.splash(); } catch (Throwable ex) { graphicFailure = true; System.err.println(Globals.lang("Unable to create graphical interface") + "."); } } // Check if we should reset all preferences to default values: if (cli.defPrefs.isInvoked()) { String value = cli.defPrefs.getStringValue(); if (value.trim().equals("all")) { try { System.out.println(Globals.lang("Setting all preferences to default values.")); Globals.prefs.clear(); } catch (BackingStoreException e) { System.err.println(Globals.lang("Unable to clear preferences.")); e.printStackTrace(); } } else { String[] keys = value.split(","); for (String key : keys) { if (Globals.prefs.hasKey(key.trim())) { System.out.println(Globals.lang("Resetting preference key '%0'", key.trim())); Globals.prefs.clear(key.trim()); } else { System.out.println(Globals.lang("Unknown preference key '%0'", key.trim())); } } } } // Check if we should import preferences from a file: if (cli.importPrefs.isInvoked()) { try { Globals.prefs.importPreferences(cli.importPrefs.getStringValue()); BibtexEntryType.loadCustomEntryTypes(Globals.prefs); ExportFormats.initAllExports(); } catch (IOException ex) { Util.pr(ex.getMessage()); } } // Vector to put imported/loaded database(s) in. Vector<ParserResult> loaded = new Vector<ParserResult>(); Vector<String> toImport = new Vector<String>(); if (!cli.isBlank() && (cli.getLeftOver().length > 0)) { for (String aLeftOver : cli.getLeftOver()) { // Leftover arguments that have a "bib" extension are interpreted as // bib files to open. Other files, and files that could not be opened // as bib, we try to import instead. boolean bibExtension = aLeftOver.toLowerCase().endsWith("bib"); ParserResult pr = null; if (bibExtension) pr = openBibFile(aLeftOver, false); if ((pr == null) || (pr == ParserResult.INVALID_FORMAT)) { // We will try to import this file. Normally we // will import it into a new tab, but if this import has // been initiated by another instance through the remote // listener, we will instead import it into the current database. // This will enable easy integration with web browers that can // open a reference file in JabRef. if (initialStartup) { toImport.add(aLeftOver); } else { ParserResult res = importToOpenBase(aLeftOver); if (res != null) loaded.add(res); else loaded.add(ParserResult.INVALID_FORMAT); } } else if (pr != ParserResult.FILE_LOCKED) loaded.add(pr); } } if (!cli.isBlank() && cli.importFile.isInvoked()) { toImport.add(cli.importFile.getStringValue()); } for (String filenameString : toImport) { ParserResult pr = importFile(filenameString); if (pr != null) loaded.add(pr); } if (!cli.isBlank() && cli.importToOpenBase.isInvoked()) { ParserResult res = importToOpenBase(cli.importToOpenBase.getStringValue()); if (res != null) loaded.add(res); } if (!cli.isBlank() && cli.fetcherEngine.isInvoked()) { ParserResult res = fetch(cli.fetcherEngine.getStringValue()); if (res != null) loaded.add(res); } if(cli.exportMatches.isInvoked()) { if (loaded.size() > 0) { String[] data = cli.exportMatches.getStringValue().split(","); String searchTerm = data[0].replace("\\$"," "); //enables blanks within the search term: //? stands for a blank ParserResult pr = loaded.elementAt(loaded.size() - 1); BibtexDatabase dataBase = pr.getDatabase(); SearchManagerNoGUI smng = new SearchManagerNoGUI(searchTerm, dataBase); BibtexDatabase newBase = smng.getDBfromMatches(); //newBase contains only match entries //export database if (newBase != null && newBase.getEntryCount() > 0) { String formatName = null; IExportFormat format = null; //read in the export format, take default format if no format entered switch (data.length){ case(3):{ formatName = data[2]; break; } case (2):{ //default ExportFormat: HTML table (with Abstract & BibTeX) formatName = "tablerefsabsbib"; break; } default:{ System.err.println(Globals.lang("Output file missing").concat(". \n \t ").concat("Usage").concat(": ") + JabRefCLI.exportMatchesSyntax); System.exit(0); } } //end switch //export new database format = ExportFormats.getExportFormat(formatName); if (format != null) { // We have an ExportFormat instance: try { System.out.println(Globals.lang("Exporting") + ": " + data[1]); format.performExport(newBase, pr.getMetaData(), data[1], pr.getEncoding(), null); } catch (Exception ex) { System.err.println(Globals.lang("Could not export file") + " '" + data[1] + "': " + ex.getMessage()); } } else System.err.println(Globals.lang("Unknown export format") + ": " + formatName); } /*end if newBase != null*/ else { System.err.println(Globals.lang("No search matches.")); } } else { System.err.println(Globals.lang("The output option depends on a valid input option.")); } //end if(loaded.size > 0) } //end exportMatches invoked if (cli.exportFile.isInvoked()) { if (loaded.size() > 0) { String[] data = cli.exportFile.getStringValue().split(","); if (data.length == 1) { // This signals that the latest import should be stored in BibTeX // format to the given file. if (loaded.size() > 0) { ParserResult pr = loaded.elementAt(loaded.size() - 1); if (!pr.isInvalid()) { try { System.out.println(Globals.lang("Saving") + ": " + data[0]); SaveSession session = FileActions.saveDatabase(pr.getDatabase(), pr.getMetaData(), new File(data[0]), Globals.prefs, false, false, Globals.prefs.get("defaultEncoding"), false); // Show just a warning message if encoding didn't work for all characters: if (!session.getWriter().couldEncodeAll()) System.err.println(Globals.lang("Warning")+": "+ Globals.lang("The chosen encoding '%0' could not encode the following characters: ", session.getEncoding())+session.getWriter().getProblemCharacters()); session.commit(); } catch (SaveException ex) { System.err.println(Globals.lang("Could not save file") + " '" + data[0] + "': " + ex.getMessage()); } } } else System.err.println(Globals.lang( "The output option depends on a valid import option.")); } else if (data.length == 2) { // This signals that the latest import should be stored in the given // format to the given file. ParserResult pr = loaded.elementAt(loaded.size() - 1); // Set the global variable for this database's file directory before exporting, // so formatters can resolve linked files correctly. // (This is an ugly hack!) File theFile = pr.getFile(); if (!theFile.isAbsolute()) theFile = theFile.getAbsoluteFile(); MetaData metaData = pr.getMetaData(); metaData.setFile(theFile); Globals.prefs.fileDirForDatabase = metaData.getFileDirectory(GUIGlobals.FILE_FIELD); Globals.prefs.databaseFile = metaData.getFile(); System.out.println(Globals.lang("Exporting") + ": " + data[0]); IExportFormat format = ExportFormats.getExportFormat(data[1]); if (format != null) { // We have an ExportFormat instance: try { format.performExport(pr.getDatabase(), pr.getMetaData(), data[0], pr.getEncoding(), null); } catch (Exception ex) { System.err.println(Globals.lang("Could not export file") + " '" + data[0] + "': " + ex.getMessage()); } } else System.err.println(Globals.lang("Unknown export format") + ": " + data[1]); } } else System.err.println(Globals.lang( "The output option depends on a valid import option.")); } //Util.pr(": Finished export"); if (cli.exportPrefs.isInvoked()) { try { Globals.prefs.exportPreferences(cli.exportPrefs.getStringValue()); } catch (IOException ex) { Util.pr(ex.getMessage()); } } if (!cli.isBlank() && cli.auxImExport.isInvoked()) { boolean usageMsg = false; if (loaded.size() > 0) // bibtex file loaded { String[] data = cli.auxImExport.getStringValue().split(","); if (data.length == 2) { ParserResult pr = loaded.firstElement(); AuxCommandLine acl = new AuxCommandLine(data[0], pr.getDatabase()); BibtexDatabase newBase = acl.perform(); boolean notSavedMsg = false; // write an output, if something could be resolved if (newBase != null) { if (newBase.getEntryCount() > 0) { String subName = Util.getCorrectFileName(data[1], "bib"); try { System.out.println(Globals.lang("Saving") + ": " + subName); SaveSession session = FileActions.saveDatabase(newBase, new MetaData(), // no Metadata new File(subName), Globals.prefs, false, false, Globals.prefs.get("defaultEncoding"), false); // Show just a warning message if encoding didn't work for all characters: if (!session.getWriter().couldEncodeAll()) System.err.println(Globals.lang("Warning")+": "+ Globals.lang("The chosen encoding '%0' could not encode the following characters: ", session.getEncoding())+session.getWriter().getProblemCharacters()); session.commit(); } catch (SaveException ex) { System.err.println(Globals.lang("Could not save file") + " '" + subName + "': " + ex.getMessage()); } notSavedMsg = true; } } if (!notSavedMsg) System.out.println(Globals.lang("no database generated")); } else usageMsg = true; } else usageMsg = true; if (usageMsg) { System.out.println(Globals.lang("no base-bibtex-file specified")); System.out.println(Globals.lang("usage") + " :"); System.out.println( "jabref --aux infile[.aux],outfile[.bib] base-bibtex-file"); } } return loaded; } /** * Run an entry fetcher from the command line. * * Note that this only works headlessly if the EntryFetcher does not show * any GUI. * * @param fetchCommand * A string containing both the fetcher to use (id of * EntryFetcherExtension minus Fetcher) and the search query, * separated by a : * @return A parser result containing the entries fetched or null if an * error occurred. */ protected ParserResult fetch(String fetchCommand) { if (fetchCommand == null || !fetchCommand.contains(":") || fetchCommand.split(":").length != 2) { System.out.println(Globals.lang("Expected syntax for --fetch='<name of fetcher>:<query>'")); System.out.println(Globals.lang("The following fetchers are available:")); return null; } String engine = fetchCommand.split(":")[0]; String query = fetchCommand.split(":")[1]; EntryFetcher fetcher = null; for (EntryFetcherExtension e : JabRefPlugin.getInstance(PluginCore.getManager()) .getEntryFetcherExtensions()) { if (engine.toLowerCase().equals(e.getId().replaceAll("Fetcher", "").toLowerCase())) fetcher = e.getEntryFetcher(); } if (fetcher == null) { System.out.println(Globals.lang("Could not find fetcher '%0'", engine)); System.out.println(Globals.lang("The following fetchers are available:")); for (EntryFetcherExtension e : JabRefPlugin.getInstance(PluginCore.getManager()) .getEntryFetcherExtensions()) { System.out.println(" " + e.getId().replaceAll("Fetcher", "").toLowerCase()); } return null; } System.out.println(Globals.lang("Running Query '%0' with fetcher '%1'.", query, engine) + " " + Globals.lang("Please wait...")); Collection<BibtexEntry> result = new ImportInspectionCommandLine().query(query, fetcher); if (result == null || result.size() == 0) { System.out.println(Globals.lang( "Query '%0' with fetcher '%1' did not return any results.", query, engine)); return null; } return new ParserResult(result); } private void setLookAndFeel() { try { String lookFeel; String systemLnF = UIManager.getSystemLookAndFeelClassName(); if (Globals.prefs.getBoolean("useDefaultLookAndFeel")) { // Use system Look & Feel by default lookFeel = systemLnF; } else { lookFeel = Globals.prefs.get("lookAndFeel"); } // At all cost, avoid ending up with the Metal look and feel: if (lookFeel.equals("javax.swing.plaf.metal.MetalLookAndFeel")) { Plastic3DLookAndFeel lnf = new Plastic3DLookAndFeel(); Plastic3DLookAndFeel.setCurrentTheme(new SkyBluer()); com.jgoodies.looks.Options.setPopupDropShadowEnabled(true); UIManager.setLookAndFeel(lnf); } else { try { UIManager.setLookAndFeel(lookFeel); } catch (Exception e) { // javax.swing.UnsupportedLookAndFeelException (sure; see bug #1278) or ClassNotFoundException (unsure) may be thrown // specified look and feel does not exist on the classpath, so use system l&f UIManager.setLookAndFeel(systemLnF); // also set system l&f as default Globals.prefs.put("lookAndFeel", systemLnF); // notify the user JOptionPane.showMessageDialog(jrf, Globals.lang("Unable to find the requested Look & Feel and thus the default one is used."), Globals.lang("Warning"), JOptionPane.WARNING_MESSAGE); } } } catch (Exception e) { e.printStackTrace(); } // In JabRef v2.8, we did it only on NON-Mac. Now, we try on all platforms boolean overrideDefaultFonts = Globals.prefs.getBoolean("overrideDefaultFonts"); if (overrideDefaultFonts) { int fontSize = Globals.prefs.getInt("menuFontSize"); UIDefaults defaults = UIManager.getDefaults(); Enumeration<Object> keys = defaults.keys(); Double zoomLevel = null; while (keys.hasMoreElements()) { Object key = keys.nextElement(); if ((key instanceof String) && (((String) key).endsWith(".font"))) { FontUIResource font = (FontUIResource) UIManager.get(key); if (zoomLevel == null) { // zoomLevel not yet set, calculate it based on the first found font zoomLevel = (double) fontSize / (double) font.getSize(); } font = new FontUIResource(font.getName(), font.getStyle(), fontSize); defaults.put(key, font); } } if (zoomLevel != null) { GUIGlobals.zoomLevel = zoomLevel; } } } public void openWindow(Vector<ParserResult> loaded) { if (!graphicFailure && !cli.isDisableGui()) { // Call the method performCompatibilityUpdate(), which does any // necessary changes for users with a preference set from an older // Jabref version. Util.performCompatibilityUpdate(); // Set up custom or default icon theme: GUIGlobals.setUpIconTheme(); // TODO: remove temporary registering of external file types? Globals.prefs.updateExternalFileTypes(); // This property is set to make the Mac OSX Java VM move the menu bar to // the top // of the screen, where Mac users expect it to be. System.setProperty("apple.laf.useScreenMenuBar", "true"); // Set antialiasing on everywhere. This only works in JRE >= 1.5. // Or... it doesn't work, period. //System.setProperty("swing.aatext", "true"); // TODO test and maybe remove this! I found this commented out with no additional info ( [email protected] ) // Set the Look & Feel for Swing. try { setLookAndFeel(); } catch (Throwable e) { e.printStackTrace(); } // If the option is enabled, open the last edited databases, if any. if (!cli.isBlank() && Globals.prefs.getBoolean("openLastEdited") && (Globals.prefs.get("lastEdited") != null)) { // How to handle errors in the databases to open? String[] names = Globals.prefs.getStringArray("lastEdited"); lastEdLoop: for (String name : names) { File fileToOpen = new File(name); for (int j = 0; j < loaded.size(); j++) { ParserResult pr = loaded.elementAt(j); if ((pr.getFile() != null) && pr.getFile().equals(fileToOpen)) continue lastEdLoop; } if (fileToOpen.exists()) { ParserResult pr = openBibFile(name, false); if (pr != null) { if (pr == ParserResult.INVALID_FORMAT) { System.out.println(Globals.lang("Error opening file") + " '" + fileToOpen.getPath() + "'"); } else if (pr != ParserResult.FILE_LOCKED) loaded.add(pr); } } } } GUIGlobals.init(); GUIGlobals.CURRENTFONT = new Font(Globals.prefs.get("fontFamily"), Globals.prefs.getInt("fontStyle"), Globals.prefs.getInt("fontSize")); //Util.pr(": Initializing frame"); jrf = new JabRefFrame(); // Add all loaded databases to the frame: boolean first = true; List<File> postponed = new ArrayList<File>(); List<ParserResult> failed = new ArrayList<ParserResult>(); List<ParserResult> toOpenTab = new ArrayList<ParserResult>(); if (loaded.size() > 0) { for (Iterator<ParserResult> i = loaded.iterator(); i.hasNext();){ ParserResult pr = i.next(); if (pr.isInvalid()) { failed.add(pr); i.remove(); } else if (!pr.isPostponedAutosaveFound()) { if (pr.toOpenTab()) { // things to be appended to an opened tab should be done after opening all tabs // add them to the list toOpenTab.add(pr); } else { jrf.addParserResult(pr, first); first = false; } } else { i.remove(); postponed.add(pr.getFile()); } } } // finally add things to the currently opened tab for (ParserResult pr: toOpenTab) { jrf.addParserResult(pr, first); first = false; } if (cli.isLoadSession()) jrf.loadSessionAction.actionPerformed(new java.awt.event.ActionEvent( jrf, 0, "")); if (splashScreen != null) {// do this only if splashscreen was actually created splashScreen.dispose(); splashScreen = null; } /*JOptionPane.showMessageDialog(null, Globals.lang("Please note that this " +"is an early beta version. Do not use it without backing up your files!"), Globals.lang("Beta version"), JOptionPane.WARNING_MESSAGE);*/ // Start auto save timer: if (Globals.prefs.getBoolean("autoSave")) Globals.startAutoSaveManager(jrf); // If we are set to remember the window location, we also remember the maximised // state. This needs to be set after the window has been made visible, so we // do it here: if (Globals.prefs.getBoolean("windowMaximised")) { jrf.setExtendedState(JFrame.MAXIMIZED_BOTH); } jrf.setVisible(true); if (Globals.prefs.getBoolean("windowMaximised")) { jrf.setExtendedState(JFrame.MAXIMIZED_BOTH); } // TEST TEST TEST TEST TEST TEST startSidePanePlugins(jrf); for (ParserResult pr : failed) { String message = "<html>"+Globals.lang("Error opening file '%0'.", pr.getFile().getName()) +"<p>"+pr.getErrorMessage()+"</html>"; JOptionPane.showMessageDialog(jrf, message, Globals.lang("Error opening file"), JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < loaded.size(); i++) { ParserResult pr = loaded.elementAt(i); if (Globals.prefs.getBoolean("displayKeyWarningDialogAtStartup") && pr.hasWarnings()) { String[] wrns = pr.warnings(); StringBuilder wrn = new StringBuilder(); for (int j = 0; j<Math.min(MAX_DIALOG_WARNINGS, wrns.length); j++) wrn.append(j + 1).append(". ").append(wrns[j]).append("\n"); if (wrns.length > MAX_DIALOG_WARNINGS) { wrn.append("... "); wrn.append(Globals.lang("%0 warnings", String.valueOf(wrns.length))); } else if (wrn.length() > 0) wrn.deleteCharAt(wrn.length() - 1); jrf.showBaseAt(i); JOptionPane.showMessageDialog(jrf, wrn.toString(), Globals.lang("Warnings")+" ("+pr.getFile().getName()+")", JOptionPane.WARNING_MESSAGE); } } // After adding the databases, go through each and see if // any post open actions need to be done. For instance, checking // if we found new entry types that can be imported, or checking // if the database contents should be modified due to new features // in this version of JabRef. // Note that we have to check whether i does not go over baseCount(). // This is because importToOpen might have been used, which adds to // loaded, but not to baseCount() for (int i = 0; (i < loaded.size()) && (i < jrf.baseCount()); i++) { ParserResult pr = loaded.elementAt(i); BasePanel panel = jrf.baseAt(i); OpenDatabaseAction.performPostOpenActions(panel, pr, true); } //Util.pr(": Finished adding panels"); // If any database loading was postponed due to an autosave, schedule them // for handing now: if (postponed.size() > 0) { AutosaveStartupPrompter asp = new AutosaveStartupPrompter(jrf, postponed); SwingUtilities.invokeLater(asp); } if (loaded.size() > 0) { jrf.tabbedPane.setSelectedIndex(0); new FocusRequester(((BasePanel) jrf.tabbedPane.getComponentAt(0)).mainTable); } } else System.exit(0); } /** * Go through all registered instances of SidePanePlugin, and register them * in the SidePaneManager. * * @param jrf The JabRefFrame. */ private void startSidePanePlugins(JabRefFrame jrf) { JabRefPlugin jabrefPlugin = JabRefPlugin.getInstance(PluginCore.getManager()); List<_JabRefPlugin.SidePanePluginExtension> plugins = jabrefPlugin.getSidePanePluginExtensions(); for (_JabRefPlugin.SidePanePluginExtension extension : plugins) { SidePanePlugin plugin = extension.getSidePanePlugin(); plugin.init(jrf, jrf.sidePaneManager); SidePaneComponent comp = plugin.getSidePaneComponent(); jrf.sidePaneManager.register(comp.getName(), comp); jrf.addPluginMenuItem(plugin.getMenuItem()); } } public static ParserResult openBibFile(String name, boolean ignoreAutosave) { Globals.logger(Globals.lang("Opening") + ": " + name); File file = new File(name); if (!file.exists()) { ParserResult pr = new ParserResult(null, null, null); pr.setFile(file); pr.setInvalid(true); System.err.println(Globals.lang("Error")+": "+Globals.lang("File not found")); return pr; } try { if (!ignoreAutosave) { boolean autoSaveFound = AutoSaveManager.newerAutoSaveExists(file); if (autoSaveFound) { // We have found a newer autosave. Make a note of this, so it can be // handled after startup: ParserResult postp = new ParserResult(null, null, null); postp.setPostponedAutosaveFound(true); postp.setFile(file); return postp; } } if (!Util.waitForFileLock(file, 10)) { System.out.println(Globals.lang("Error opening file")+" '"+name+"'. "+ "File is locked by another JabRef instance."); return ParserResult.FILE_LOCKED; } String encoding = Globals.prefs.get("defaultEncoding"); ParserResult pr = OpenDatabaseAction.loadDatabase(file, encoding); if (pr == null) { pr = new ParserResult(null, null, null); pr.setFile(file); pr.setInvalid(true); return pr; } pr.setFile(file); if (pr.hasWarnings()) { String[] warn = pr.warnings(); for (String aWarn : warn) System.out.println(Globals.lang("Warning") + ": " + aWarn); } return pr; } catch (Throwable ex) { ParserResult pr = new ParserResult(null, null, null); pr.setFile(file); pr.setInvalid(true); pr.setErrorMessage(ex.getMessage()); return pr; } } public static ParserResult importFile(String argument){ String[] data = argument.split(","); try { if ((data.length > 1) && !"*".equals(data[1])) { System.out.println(Globals.lang("Importing") + ": " + data[0]); try { List<BibtexEntry> entries; if (Globals.ON_WIN) { entries = Globals.importFormatReader.importFromFile(data[1], data[0], jrf); } else { entries = Globals.importFormatReader.importFromFile( data[1], data[0].replaceAll("~", System.getProperty("user.home")), jrf ); } return new ParserResult(entries); } catch (IllegalArgumentException ex) { System.err.println(Globals.lang("Unknown import format")+": "+data[1]); return null; } } else { // * means "guess the format": System.out.println(Globals.lang("Importing in unknown format") + ": " + data[0]); ImportFormatReader.UnknownFormatImport importResult; if (Globals.ON_WIN) { importResult = Globals.importFormatReader.importUnknownFormat(data[0]); } else { importResult = Globals.importFormatReader.importUnknownFormat( data[0].replaceAll("~", System.getProperty("user.home"))); } if (importResult != null){ System.out.println(Globals.lang("Format used") + ": " + importResult.format); return importResult.parserResult; } else { System.out.println(Globals.lang( "Could not find a suitable import format.")); } } } catch (IOException ex) { System.err.println(Globals.lang("Error opening file") + " '" + data[0] + "': " + ex.getLocalizedMessage()); } return null; } /** * Will open a file (like importFile), but will also request JabRef to focus on this database * @param argument See importFile. * @return ParserResult with setToOpenTab(true) */ public static ParserResult importToOpenBase(String argument) { ParserResult result = importFile(argument); if (result != null) result.setToOpenTab(true); return result; } }
src/main/java/net/sf/jabref/JabRef.java
/* Copyright (C) 2003-2014 JabRef contributors. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package net.sf.jabref; import com.jgoodies.looks.plastic.Plastic3DLookAndFeel; import com.jgoodies.looks.plastic.theme.SkyBluer; import java.awt.Font; import java.awt.Frame; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Vector; import java.util.prefs.BackingStoreException; import javax.swing.*; import javax.swing.plaf.FontUIResource; import net.sf.jabref.export.AutoSaveManager; import net.sf.jabref.export.ExportFormats; import net.sf.jabref.export.FileActions; import net.sf.jabref.export.IExportFormat; import net.sf.jabref.export.SaveException; import net.sf.jabref.export.SaveSession; import net.sf.jabref.imports.*; import net.sf.jabref.plugin.PluginCore; import net.sf.jabref.plugin.PluginInstaller; import net.sf.jabref.plugin.SidePanePlugin; import net.sf.jabref.plugin.core.JabRefPlugin; import net.sf.jabref.plugin.core.generated._JabRefPlugin; import net.sf.jabref.plugin.core.generated._JabRefPlugin.EntryFetcherExtension; import net.sf.jabref.remote.RemoteListener; import net.sf.jabref.wizard.auximport.AuxCommandLine; import com.sun.jna.Native; import com.sun.jna.NativeLong; import com.sun.jna.Pointer; import com.sun.jna.WString; import com.sun.jna.ptr.PointerByReference; /** * JabRef Main Class - The application gets started here. * */ public class JabRef { public static JabRef singleton; public static RemoteListener remoteListener = null; public static JabRefFrame jrf; public static Frame splashScreen = null; boolean graphicFailure = false; public static final int MAX_DIALOG_WARNINGS = 10; private JabRefCLI cli; public static void main(String[] args) { new JabRef(args); } protected JabRef(String[] args) { singleton = this; JabRefPreferences prefs = JabRefPreferences.getInstance(); // See if there are plugins scheduled for deletion: if (prefs.hasKey("deletePlugins") && (prefs.get("deletePlugins").length() > 0)) { String[] toDelete = prefs.getStringArray("deletePlugins"); PluginInstaller.deletePluginsOnStartup(toDelete); prefs.put("deletePlugins", ""); } if (prefs.getBoolean("useProxy")) { // NetworkTab.java ensures that proxyHostname and proxyPort are not null System.getProperties().put("http.proxyHost", prefs.get("proxyHostname")); System.getProperties().put("http.proxyPort", prefs.get("proxyPort")); // currently, the following cannot be configured if (prefs.get("proxyUsername") != null) { System.getProperties().put("http.proxyUser", prefs.get("proxyUsername")); System.getProperties().put("http.proxyPassword", prefs.get("proxyPassword")); } } else { // The following two lines signal that the system proxy settings // should be used: System.setProperty("java.net.useSystemProxies", "true"); System.getProperties().put("proxySet", "true"); } Globals.startBackgroundTasks(); Globals.setupLogging(); Globals.prefs = prefs; String langStr = prefs.get("language"); String[] parts = langStr.split("_"); String language, country; if (parts.length == 1) { language = langStr; country = ""; } else { language = parts[0]; country = parts[1]; } Globals.setLanguage(language, country); Globals.prefs.setLanguageDependentDefaultValues(); /* * The Plug-in System is started automatically on the first call to * PluginCore.getManager(). * * Plug-ins are activated on the first call to their getInstance method. */ // Update which fields should be treated as numeric, based on preferences: BibtexFields.setNumericFieldsFromPrefs(); /* Build list of Import and Export formats */ Globals.importFormatReader.resetImportFormats(); BibtexEntryType.loadCustomEntryTypes(prefs); ExportFormats.initAllExports(); // Read list(s) of journal names and abbreviations: Globals.initializeJournalNames(); // Check for running JabRef if (Globals.prefs.getBoolean("useRemoteServer")) { remoteListener = RemoteListener.openRemoteListener(this); if (remoteListener == null) { // Unless we are alone, try to contact already running JabRef: if (RemoteListener.sendToActiveJabRefInstance(args)) { /* * We have successfully sent our command line options * through the socket to another JabRef instance. So we * assume it's all taken care of, and quit. */ System.out.println( Globals.lang("Arguments passed on to running JabRef instance. Shutting down.")); System.exit(0); } } else { // No listener found, thus we are the first instance to be // started. remoteListener.start(); } } /* * See if the user has a personal journal list set up. If so, add these * journal names and abbreviations to the list: */ String personalJournalList = prefs.get("personalJournalList"); if (personalJournalList != null && !personalJournalList.isEmpty()) { try { Globals.journalAbbrev.readJournalList(new File( personalJournalList)); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, Globals.lang("Journal file not found") + ": " + e.getMessage(), Globals.lang("Error opening file"), JOptionPane.ERROR_MESSAGE); Globals.prefs.put("personalJournalList", ""); } } // override used newline character with the one stored in the preferences // The preferences return the system newline character sequence as default Globals.NEWLINE = Globals.prefs.get(JabRefPreferences.NEWLINE); Globals.NEWLINE_LENGTH = Globals.NEWLINE.length(); if (Globals.ON_WIN) { // Set application user model id so that pinning JabRef to the Win7/8 taskbar works // Based on http://stackoverflow.com/a/1928830 setCurrentProcessExplicitAppUserModelID("JabRef." + Globals.VERSION); //System.out.println(getCurrentProcessExplicitAppUserModelID()); } openWindow(processArguments(args, true)); } // Do not use this code in release version, it contains some memory leaks public static String getCurrentProcessExplicitAppUserModelID() { final PointerByReference r = new PointerByReference(); if (GetCurrentProcessExplicitAppUserModelID(r).longValue() == 0) { final Pointer p = r.getValue(); return p.getString(0, true); // here we leak native memory by lazyness } return "N/A"; } public static void setCurrentProcessExplicitAppUserModelID(final String appID) { if (SetCurrentProcessExplicitAppUserModelID(new WString(appID)).longValue() != 0) throw new RuntimeException("unable to set current process explicit AppUserModelID to: " + appID); } private static native NativeLong GetCurrentProcessExplicitAppUserModelID(PointerByReference appID); private static native NativeLong SetCurrentProcessExplicitAppUserModelID(WString appID); static { if (Globals.ON_WIN) { Native.register("shell32"); } } public Vector<ParserResult> processArguments(String[] args, boolean initialStartup) { cli = new JabRefCLI(args); if (initialStartup && cli.isShowVersion()) { cli.options.displayVersion(); cli.disableGui.setInvoked(true); } if (initialStartup && cli.isHelp()) { System.out.println("jabref [options] [bibtex-file]\n"); System.out.println(cli.getHelp()); String importFormats = Globals.importFormatReader.getImportFormatList(); System.out.println(Globals.lang("Available import formats") + ":\n" + importFormats); String outFormats = ExportFormats.getConsoleExportList(70, 20, "\t"); System.out.println(Globals.lang("Available export formats") + ": " + outFormats + "."); System.exit(0); } boolean commandmode = cli.isDisableGui() || cli.fetcherEngine.isInvoked(); // First we quickly scan the command line parameters for any that signal // that the GUI // should not be opened. This is used to decide whether we should show the // splash screen or not. if (initialStartup && !commandmode && !cli.isDisableSplash()) { try { splashScreen = SplashScreen.splash(); } catch (Throwable ex) { graphicFailure = true; System.err.println(Globals.lang("Unable to create graphical interface") + "."); } } // Check if we should reset all preferences to default values: if (cli.defPrefs.isInvoked()) { String value = cli.defPrefs.getStringValue(); if (value.trim().equals("all")) { try { System.out.println(Globals.lang("Setting all preferences to default values.")); Globals.prefs.clear(); } catch (BackingStoreException e) { System.err.println(Globals.lang("Unable to clear preferences.")); e.printStackTrace(); } } else { String[] keys = value.split(","); for (String key : keys) { if (Globals.prefs.hasKey(key.trim())) { System.out.println(Globals.lang("Resetting preference key '%0'", key.trim())); Globals.prefs.clear(key.trim()); } else { System.out.println(Globals.lang("Unknown preference key '%0'", key.trim())); } } } } // Check if we should import preferences from a file: if (cli.importPrefs.isInvoked()) { try { Globals.prefs.importPreferences(cli.importPrefs.getStringValue()); BibtexEntryType.loadCustomEntryTypes(Globals.prefs); ExportFormats.initAllExports(); } catch (IOException ex) { Util.pr(ex.getMessage()); } } // Vector to put imported/loaded database(s) in. Vector<ParserResult> loaded = new Vector<ParserResult>(); Vector<String> toImport = new Vector<String>(); if (!cli.isBlank() && (cli.getLeftOver().length > 0)) { for (String aLeftOver : cli.getLeftOver()) { // Leftover arguments that have a "bib" extension are interpreted as // bib files to open. Other files, and files that could not be opened // as bib, we try to import instead. boolean bibExtension = aLeftOver.toLowerCase().endsWith("bib"); ParserResult pr = null; if (bibExtension) pr = openBibFile(aLeftOver, false); if ((pr == null) || (pr == ParserResult.INVALID_FORMAT)) { // We will try to import this file. Normally we // will import it into a new tab, but if this import has // been initiated by another instance through the remote // listener, we will instead import it into the current database. // This will enable easy integration with web browers that can // open a reference file in JabRef. if (initialStartup) { toImport.add(aLeftOver); } else { ParserResult res = importToOpenBase(aLeftOver); if (res != null) loaded.add(res); else loaded.add(ParserResult.INVALID_FORMAT); } } else if (pr != ParserResult.FILE_LOCKED) loaded.add(pr); } } if (!cli.isBlank() && cli.importFile.isInvoked()) { toImport.add(cli.importFile.getStringValue()); } for (String filenameString : toImport) { ParserResult pr = importFile(filenameString); if (pr != null) loaded.add(pr); } if (!cli.isBlank() && cli.importToOpenBase.isInvoked()) { ParserResult res = importToOpenBase(cli.importToOpenBase.getStringValue()); if (res != null) loaded.add(res); } if (!cli.isBlank() && cli.fetcherEngine.isInvoked()) { ParserResult res = fetch(cli.fetcherEngine.getStringValue()); if (res != null) loaded.add(res); } if(cli.exportMatches.isInvoked()) { if (loaded.size() > 0) { String[] data = cli.exportMatches.getStringValue().split(","); String searchTerm = data[0].replace("\\$"," "); //enables blanks within the search term: //? stands for a blank ParserResult pr = loaded.elementAt(loaded.size() - 1); BibtexDatabase dataBase = pr.getDatabase(); SearchManagerNoGUI smng = new SearchManagerNoGUI(searchTerm, dataBase); BibtexDatabase newBase = smng.getDBfromMatches(); //newBase contains only match entries //export database if (newBase != null && newBase.getEntryCount() > 0) { String formatName = null; IExportFormat format = null; //read in the export format, take default format if no format entered switch (data.length){ case(3):{ formatName = data[2]; break; } case (2):{ //default ExportFormat: HTML table (with Abstract & BibTeX) formatName = "tablerefsabsbib"; break; } default:{ System.err.println(Globals.lang("Output file missing").concat(". \n \t ").concat("Usage").concat(": ") + JabRefCLI.exportMatchesSyntax); System.exit(0); } } //end switch //export new database format = ExportFormats.getExportFormat(formatName); if (format != null) { // We have an ExportFormat instance: try { System.out.println(Globals.lang("Exporting") + ": " + data[1]); format.performExport(newBase, pr.getMetaData(), data[1], pr.getEncoding(), null); } catch (Exception ex) { System.err.println(Globals.lang("Could not export file") + " '" + data[1] + "': " + ex.getMessage()); } } else System.err.println(Globals.lang("Unknown export format") + ": " + formatName); } /*end if newBase != null*/ else { System.err.println(Globals.lang("No search matches.")); } } else { System.err.println(Globals.lang("The output option depends on a valid input option.")); } //end if(loaded.size > 0) } //end exportMatches invoked if (cli.exportFile.isInvoked()) { if (loaded.size() > 0) { String[] data = cli.exportFile.getStringValue().split(","); if (data.length == 1) { // This signals that the latest import should be stored in BibTeX // format to the given file. if (loaded.size() > 0) { ParserResult pr = loaded.elementAt(loaded.size() - 1); if (!pr.isInvalid()) { try { System.out.println(Globals.lang("Saving") + ": " + data[0]); SaveSession session = FileActions.saveDatabase(pr.getDatabase(), pr.getMetaData(), new File(data[0]), Globals.prefs, false, false, Globals.prefs.get("defaultEncoding"), false); // Show just a warning message if encoding didn't work for all characters: if (!session.getWriter().couldEncodeAll()) System.err.println(Globals.lang("Warning")+": "+ Globals.lang("The chosen encoding '%0' could not encode the following characters: ", session.getEncoding())+session.getWriter().getProblemCharacters()); session.commit(); } catch (SaveException ex) { System.err.println(Globals.lang("Could not save file") + " '" + data[0] + "': " + ex.getMessage()); } } } else System.err.println(Globals.lang( "The output option depends on a valid import option.")); } else if (data.length == 2) { // This signals that the latest import should be stored in the given // format to the given file. ParserResult pr = loaded.elementAt(loaded.size() - 1); // Set the global variable for this database's file directory before exporting, // so formatters can resolve linked files correctly. // (This is an ugly hack!) File theFile = pr.getFile(); if (!theFile.isAbsolute()) theFile = theFile.getAbsoluteFile(); MetaData metaData = pr.getMetaData(); metaData.setFile(theFile); Globals.prefs.fileDirForDatabase = metaData.getFileDirectory(GUIGlobals.FILE_FIELD); Globals.prefs.databaseFile = metaData.getFile(); System.out.println(Globals.lang("Exporting") + ": " + data[0]); IExportFormat format = ExportFormats.getExportFormat(data[1]); if (format != null) { // We have an ExportFormat instance: try { format.performExport(pr.getDatabase(), pr.getMetaData(), data[0], pr.getEncoding(), null); } catch (Exception ex) { System.err.println(Globals.lang("Could not export file") + " '" + data[0] + "': " + ex.getMessage()); } } else System.err.println(Globals.lang("Unknown export format") + ": " + data[1]); } } else System.err.println(Globals.lang( "The output option depends on a valid import option.")); } //Util.pr(": Finished export"); if (cli.exportPrefs.isInvoked()) { try { Globals.prefs.exportPreferences(cli.exportPrefs.getStringValue()); } catch (IOException ex) { Util.pr(ex.getMessage()); } } if (!cli.isBlank() && cli.auxImExport.isInvoked()) { boolean usageMsg = false; if (loaded.size() > 0) // bibtex file loaded { String[] data = cli.auxImExport.getStringValue().split(","); if (data.length == 2) { ParserResult pr = loaded.firstElement(); AuxCommandLine acl = new AuxCommandLine(data[0], pr.getDatabase()); BibtexDatabase newBase = acl.perform(); boolean notSavedMsg = false; // write an output, if something could be resolved if (newBase != null) { if (newBase.getEntryCount() > 0) { String subName = Util.getCorrectFileName(data[1], "bib"); try { System.out.println(Globals.lang("Saving") + ": " + subName); SaveSession session = FileActions.saveDatabase(newBase, new MetaData(), // no Metadata new File(subName), Globals.prefs, false, false, Globals.prefs.get("defaultEncoding"), false); // Show just a warning message if encoding didn't work for all characters: if (!session.getWriter().couldEncodeAll()) System.err.println(Globals.lang("Warning")+": "+ Globals.lang("The chosen encoding '%0' could not encode the following characters: ", session.getEncoding())+session.getWriter().getProblemCharacters()); session.commit(); } catch (SaveException ex) { System.err.println(Globals.lang("Could not save file") + " '" + subName + "': " + ex.getMessage()); } notSavedMsg = true; } } if (!notSavedMsg) System.out.println(Globals.lang("no database generated")); } else usageMsg = true; } else usageMsg = true; if (usageMsg) { System.out.println(Globals.lang("no base-bibtex-file specified")); System.out.println(Globals.lang("usage") + " :"); System.out.println( "jabref --aux infile[.aux],outfile[.bib] base-bibtex-file"); } } return loaded; } /** * Run an entry fetcher from the command line. * * Note that this only works headlessly if the EntryFetcher does not show * any GUI. * * @param fetchCommand * A string containing both the fetcher to use (id of * EntryFetcherExtension minus Fetcher) and the search query, * separated by a : * @return A parser result containing the entries fetched or null if an * error occurred. */ protected ParserResult fetch(String fetchCommand) { if (fetchCommand == null || !fetchCommand.contains(":") || fetchCommand.split(":").length != 2) { System.out.println(Globals.lang("Expected syntax for --fetch='<name of fetcher>:<query>'")); System.out.println(Globals.lang("The following fetchers are available:")); return null; } String engine = fetchCommand.split(":")[0]; String query = fetchCommand.split(":")[1]; EntryFetcher fetcher = null; for (EntryFetcherExtension e : JabRefPlugin.getInstance(PluginCore.getManager()) .getEntryFetcherExtensions()) { if (engine.toLowerCase().equals(e.getId().replaceAll("Fetcher", "").toLowerCase())) fetcher = e.getEntryFetcher(); } if (fetcher == null) { System.out.println(Globals.lang("Could not find fetcher '%0'", engine)); System.out.println(Globals.lang("The following fetchers are available:")); for (EntryFetcherExtension e : JabRefPlugin.getInstance(PluginCore.getManager()) .getEntryFetcherExtensions()) { System.out.println(" " + e.getId().replaceAll("Fetcher", "").toLowerCase()); } return null; } System.out.println(Globals.lang("Running Query '%0' with fetcher '%1'.", query, engine) + " " + Globals.lang("Please wait...")); Collection<BibtexEntry> result = new ImportInspectionCommandLine().query(query, fetcher); if (result == null || result.size() == 0) { System.out.println(Globals.lang( "Query '%0' with fetcher '%1' did not return any results.", query, engine)); return null; } return new ParserResult(result); } private void setLookAndFeel() { try { String lookFeel; String systemLnF = UIManager.getSystemLookAndFeelClassName(); if (Globals.prefs.getBoolean("useDefaultLookAndFeel")) { // Use system Look & Feel by default lookFeel = systemLnF; } else { lookFeel = Globals.prefs.get("lookAndFeel"); } // At all cost, avoid ending up with the Metal look and feel: if (lookFeel.equals("javax.swing.plaf.metal.MetalLookAndFeel")) { Plastic3DLookAndFeel lnf = new Plastic3DLookAndFeel(); Plastic3DLookAndFeel.setCurrentTheme(new SkyBluer()); com.jgoodies.looks.Options.setPopupDropShadowEnabled(true); UIManager.setLookAndFeel(lnf); } else { try { UIManager.setLookAndFeel(lookFeel); } catch(ClassNotFoundException e) { // specified look and feel does not exist on the classpath, so use system l&f UIManager.setLookAndFeel(systemLnF); // also set system l&f as default Globals.prefs.put("lookAndFeel", systemLnF); // notify the user JOptionPane.showMessageDialog(jrf, Globals.lang("Unable to find the requested Look & Feel and thus the default one is used."), Globals.lang("Warning"), JOptionPane.WARNING_MESSAGE); } } } catch (Exception e) { e.printStackTrace(); } // In JabRef v2.8, we did it only on NON-Mac. Now, we try on all platforms boolean overrideDefaultFonts = Globals.prefs.getBoolean("overrideDefaultFonts"); if (overrideDefaultFonts) { int fontSize = Globals.prefs.getInt("menuFontSize"); UIDefaults defaults = UIManager.getDefaults(); Enumeration<Object> keys = defaults.keys(); Double zoomLevel = null; while (keys.hasMoreElements()) { Object key = keys.nextElement(); if ((key instanceof String) && (((String) key).endsWith(".font"))) { FontUIResource font = (FontUIResource) UIManager.get(key); if (zoomLevel == null) { // zoomLevel not yet set, calculate it based on the first found font zoomLevel = (double) fontSize / (double) font.getSize(); } font = new FontUIResource(font.getName(), font.getStyle(), fontSize); defaults.put(key, font); } } if (zoomLevel != null) { GUIGlobals.zoomLevel = zoomLevel; } } } public void openWindow(Vector<ParserResult> loaded) { if (!graphicFailure && !cli.isDisableGui()) { // Call the method performCompatibilityUpdate(), which does any // necessary changes for users with a preference set from an older // Jabref version. Util.performCompatibilityUpdate(); // Set up custom or default icon theme: GUIGlobals.setUpIconTheme(); // TODO: remove temporary registering of external file types? Globals.prefs.updateExternalFileTypes(); // This property is set to make the Mac OSX Java VM move the menu bar to // the top // of the screen, where Mac users expect it to be. System.setProperty("apple.laf.useScreenMenuBar", "true"); // Set antialiasing on everywhere. This only works in JRE >= 1.5. // Or... it doesn't work, period. //System.setProperty("swing.aatext", "true"); // TODO test and maybe remove this! I found this commented out with no additional info ( [email protected] ) // Set the Look & Feel for Swing. try { setLookAndFeel(); } catch (Throwable e) { e.printStackTrace(); } // If the option is enabled, open the last edited databases, if any. if (!cli.isBlank() && Globals.prefs.getBoolean("openLastEdited") && (Globals.prefs.get("lastEdited") != null)) { // How to handle errors in the databases to open? String[] names = Globals.prefs.getStringArray("lastEdited"); lastEdLoop: for (String name : names) { File fileToOpen = new File(name); for (int j = 0; j < loaded.size(); j++) { ParserResult pr = loaded.elementAt(j); if ((pr.getFile() != null) && pr.getFile().equals(fileToOpen)) continue lastEdLoop; } if (fileToOpen.exists()) { ParserResult pr = openBibFile(name, false); if (pr != null) { if (pr == ParserResult.INVALID_FORMAT) { System.out.println(Globals.lang("Error opening file") + " '" + fileToOpen.getPath() + "'"); } else if (pr != ParserResult.FILE_LOCKED) loaded.add(pr); } } } } GUIGlobals.init(); GUIGlobals.CURRENTFONT = new Font(Globals.prefs.get("fontFamily"), Globals.prefs.getInt("fontStyle"), Globals.prefs.getInt("fontSize")); //Util.pr(": Initializing frame"); jrf = new JabRefFrame(); // Add all loaded databases to the frame: boolean first = true; List<File> postponed = new ArrayList<File>(); List<ParserResult> failed = new ArrayList<ParserResult>(); List<ParserResult> toOpenTab = new ArrayList<ParserResult>(); if (loaded.size() > 0) { for (Iterator<ParserResult> i = loaded.iterator(); i.hasNext();){ ParserResult pr = i.next(); if (pr.isInvalid()) { failed.add(pr); i.remove(); } else if (!pr.isPostponedAutosaveFound()) { if (pr.toOpenTab()) { // things to be appended to an opened tab should be done after opening all tabs // add them to the list toOpenTab.add(pr); } else { jrf.addParserResult(pr, first); first = false; } } else { i.remove(); postponed.add(pr.getFile()); } } } // finally add things to the currently opened tab for (ParserResult pr: toOpenTab) { jrf.addParserResult(pr, first); first = false; } if (cli.isLoadSession()) jrf.loadSessionAction.actionPerformed(new java.awt.event.ActionEvent( jrf, 0, "")); if (splashScreen != null) {// do this only if splashscreen was actually created splashScreen.dispose(); splashScreen = null; } /*JOptionPane.showMessageDialog(null, Globals.lang("Please note that this " +"is an early beta version. Do not use it without backing up your files!"), Globals.lang("Beta version"), JOptionPane.WARNING_MESSAGE);*/ // Start auto save timer: if (Globals.prefs.getBoolean("autoSave")) Globals.startAutoSaveManager(jrf); // If we are set to remember the window location, we also remember the maximised // state. This needs to be set after the window has been made visible, so we // do it here: if (Globals.prefs.getBoolean("windowMaximised")) { jrf.setExtendedState(JFrame.MAXIMIZED_BOTH); } jrf.setVisible(true); if (Globals.prefs.getBoolean("windowMaximised")) { jrf.setExtendedState(JFrame.MAXIMIZED_BOTH); } // TEST TEST TEST TEST TEST TEST startSidePanePlugins(jrf); for (ParserResult pr : failed) { String message = "<html>"+Globals.lang("Error opening file '%0'.", pr.getFile().getName()) +"<p>"+pr.getErrorMessage()+"</html>"; JOptionPane.showMessageDialog(jrf, message, Globals.lang("Error opening file"), JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < loaded.size(); i++) { ParserResult pr = loaded.elementAt(i); if (Globals.prefs.getBoolean("displayKeyWarningDialogAtStartup") && pr.hasWarnings()) { String[] wrns = pr.warnings(); StringBuilder wrn = new StringBuilder(); for (int j = 0; j<Math.min(MAX_DIALOG_WARNINGS, wrns.length); j++) wrn.append(j + 1).append(". ").append(wrns[j]).append("\n"); if (wrns.length > MAX_DIALOG_WARNINGS) { wrn.append("... "); wrn.append(Globals.lang("%0 warnings", String.valueOf(wrns.length))); } else if (wrn.length() > 0) wrn.deleteCharAt(wrn.length() - 1); jrf.showBaseAt(i); JOptionPane.showMessageDialog(jrf, wrn.toString(), Globals.lang("Warnings")+" ("+pr.getFile().getName()+")", JOptionPane.WARNING_MESSAGE); } } // After adding the databases, go through each and see if // any post open actions need to be done. For instance, checking // if we found new entry types that can be imported, or checking // if the database contents should be modified due to new features // in this version of JabRef. // Note that we have to check whether i does not go over baseCount(). // This is because importToOpen might have been used, which adds to // loaded, but not to baseCount() for (int i = 0; (i < loaded.size()) && (i < jrf.baseCount()); i++) { ParserResult pr = loaded.elementAt(i); BasePanel panel = jrf.baseAt(i); OpenDatabaseAction.performPostOpenActions(panel, pr, true); } //Util.pr(": Finished adding panels"); // If any database loading was postponed due to an autosave, schedule them // for handing now: if (postponed.size() > 0) { AutosaveStartupPrompter asp = new AutosaveStartupPrompter(jrf, postponed); SwingUtilities.invokeLater(asp); } if (loaded.size() > 0) { jrf.tabbedPane.setSelectedIndex(0); new FocusRequester(((BasePanel) jrf.tabbedPane.getComponentAt(0)).mainTable); } } else System.exit(0); } /** * Go through all registered instances of SidePanePlugin, and register them * in the SidePaneManager. * * @param jrf The JabRefFrame. */ private void startSidePanePlugins(JabRefFrame jrf) { JabRefPlugin jabrefPlugin = JabRefPlugin.getInstance(PluginCore.getManager()); List<_JabRefPlugin.SidePanePluginExtension> plugins = jabrefPlugin.getSidePanePluginExtensions(); for (_JabRefPlugin.SidePanePluginExtension extension : plugins) { SidePanePlugin plugin = extension.getSidePanePlugin(); plugin.init(jrf, jrf.sidePaneManager); SidePaneComponent comp = plugin.getSidePaneComponent(); jrf.sidePaneManager.register(comp.getName(), comp); jrf.addPluginMenuItem(plugin.getMenuItem()); } } public static ParserResult openBibFile(String name, boolean ignoreAutosave) { Globals.logger(Globals.lang("Opening") + ": " + name); File file = new File(name); if (!file.exists()) { ParserResult pr = new ParserResult(null, null, null); pr.setFile(file); pr.setInvalid(true); System.err.println(Globals.lang("Error")+": "+Globals.lang("File not found")); return pr; } try { if (!ignoreAutosave) { boolean autoSaveFound = AutoSaveManager.newerAutoSaveExists(file); if (autoSaveFound) { // We have found a newer autosave. Make a note of this, so it can be // handled after startup: ParserResult postp = new ParserResult(null, null, null); postp.setPostponedAutosaveFound(true); postp.setFile(file); return postp; } } if (!Util.waitForFileLock(file, 10)) { System.out.println(Globals.lang("Error opening file")+" '"+name+"'. "+ "File is locked by another JabRef instance."); return ParserResult.FILE_LOCKED; } String encoding = Globals.prefs.get("defaultEncoding"); ParserResult pr = OpenDatabaseAction.loadDatabase(file, encoding); if (pr == null) { pr = new ParserResult(null, null, null); pr.setFile(file); pr.setInvalid(true); return pr; } pr.setFile(file); if (pr.hasWarnings()) { String[] warn = pr.warnings(); for (String aWarn : warn) System.out.println(Globals.lang("Warning") + ": " + aWarn); } return pr; } catch (Throwable ex) { ParserResult pr = new ParserResult(null, null, null); pr.setFile(file); pr.setInvalid(true); pr.setErrorMessage(ex.getMessage()); return pr; } } public static ParserResult importFile(String argument){ String[] data = argument.split(","); try { if ((data.length > 1) && !"*".equals(data[1])) { System.out.println(Globals.lang("Importing") + ": " + data[0]); try { List<BibtexEntry> entries; if (Globals.ON_WIN) { entries = Globals.importFormatReader.importFromFile(data[1], data[0], jrf); } else { entries = Globals.importFormatReader.importFromFile( data[1], data[0].replaceAll("~", System.getProperty("user.home")), jrf ); } return new ParserResult(entries); } catch (IllegalArgumentException ex) { System.err.println(Globals.lang("Unknown import format")+": "+data[1]); return null; } } else { // * means "guess the format": System.out.println(Globals.lang("Importing in unknown format") + ": " + data[0]); ImportFormatReader.UnknownFormatImport importResult; if (Globals.ON_WIN) { importResult = Globals.importFormatReader.importUnknownFormat(data[0]); } else { importResult = Globals.importFormatReader.importUnknownFormat( data[0].replaceAll("~", System.getProperty("user.home"))); } if (importResult != null){ System.out.println(Globals.lang("Format used") + ": " + importResult.format); return importResult.parserResult; } else { System.out.println(Globals.lang( "Could not find a suitable import format.")); } } } catch (IOException ex) { System.err.println(Globals.lang("Error opening file") + " '" + data[0] + "': " + ex.getLocalizedMessage()); } return null; } /** * Will open a file (like importFile), but will also request JabRef to focus on this database * @param argument See importFile. * @return ParserResult with setToOpenTab(true) */ public static ParserResult importToOpenBase(String argument) { ParserResult result = importFile(argument); if (result != null) result.setToOpenTab(true); return result; } }
Trying to really fix #1278
src/main/java/net/sf/jabref/JabRef.java
Trying to really fix #1278
Java
mit
e2213cd97b5ebdfcaa4356e6458595e96cbfc2da
0
DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android
/* DevicePluginListFragment.java Copyright (c) 2015 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.manager.setting; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import org.deviceconnect.android.manager.BuildConfig; import org.deviceconnect.android.manager.DConnectApplication; import org.deviceconnect.android.manager.DevicePlugin; import org.deviceconnect.android.manager.DevicePluginManager; import org.deviceconnect.android.manager.R; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Device plug-in list fragment. * * @author NTT DOCOMO, INC. */ public class DevicePluginListFragment extends Fragment { /** Adapter. */ private PluginAdapter mPluginAdapter; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onResume() { super.onResume(); updatePluginList(); } /** * Create a PluginContainer from Device Plug-in. * @param pm PackageManager. * @param app ApplicationInfo. * @return Instance of DeviceContainer */ private PluginContainer createContainer(final PackageManager pm, final ApplicationInfo app) { PluginContainer container = new PluginContainer(); container.setLabel(app.loadLabel(pm).toString()); container.setPackageName(app.packageName); try { container.setIcon(pm.getApplicationIcon(app.packageName)); } catch (PackageManager.NameNotFoundException e) { // do nothing. if (BuildConfig.DEBUG) { Log.d("Manager", "Icon is not found."); } } try { PackageInfo info = pm.getPackageInfo(app.packageName, PackageManager.GET_META_DATA); container.setVersion(info.versionName); } catch (PackageManager.NameNotFoundException e) { // do nothing. if (BuildConfig.DEBUG) { Log.d("Manager", "VersionName is not found."); } } return container; } /** * Create a list of plug-in. * @return list of plug-in. */ private List<PluginContainer> createPluginContainers() { List<PluginContainer> containers = new ArrayList<>(); PackageManager pm = getActivity().getPackageManager(); DConnectApplication app = (DConnectApplication) getActivity().getApplication(); DevicePluginManager manager = app.getDevicePluginManager(); for (DevicePlugin plugin : manager.getDevicePlugins()) { try { ApplicationInfo info = pm.getApplicationInfo(plugin.getPackageName(), 0); containers.add(createContainer(pm, info)); } catch (PackageManager.NameNotFoundException e) { continue; } } Collections.sort(containers, new Comparator<PluginContainer>() { @Override public int compare(final PluginContainer o1, final PluginContainer o2) { String a = o1.getLabel(); String b = o2.getLabel(); return a.compareTo(b); } }); return containers; } @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { mPluginAdapter = new PluginAdapter(getActivity(), createPluginContainers()); View rootView = inflater.inflate(R.layout.fragment_devicepluginlist, container, false); ListView listView = (ListView) rootView.findViewById(R.id.listview_pluginlist); listView.setAdapter(mPluginAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { openDevicePluginInformation(mPluginAdapter.getItem(position)); } }); return rootView; } @Override public boolean onOptionsItemSelected(final MenuItem item) { if (android.R.id.home == item.getItemId()) { getActivity().finish(); return true; } return super.onOptionsItemSelected(item); } /** * Update plug-in list. */ public void updatePluginList() { if (mPluginAdapter == null) { return; } if (getActivity() == null) { return; } getActivity().runOnUiThread(new Runnable() { @Override public void run() { mPluginAdapter.clear(); mPluginAdapter.addAll(createPluginContainers()); mPluginAdapter.notifyDataSetChanged(); } }); } /** * Open device plug-in information activity. * * @param container plug-in container */ private void openDevicePluginInformation(final PluginContainer container) { Intent intent = new Intent(); intent.setClass(getActivity(), DevicePluginInfoActivity.class); intent.putExtra(DevicePluginInfoActivity.PACKAGE_NAME, container.getPackageName()); startActivity(intent); } /** * PluginContainer class. */ static class PluginContainer { /** Label. */ private String mLabel; /** Package name. */ private String mPackageName; /** Version. */ private String mVersion; /** Icon. */ private Drawable mIcon; /** * Get plug-in Label. * * @return Plug-in label. */ public String getLabel() { return mLabel; } /** * Set plug-in label. * * @param label Plug-in label. */ public void setLabel(final String label) { if (label == null) { mLabel = "Unknown"; } else { mLabel = label; } } /** * Get plug-in package name. * * @return Plug-in package name. */ public String getPackageName() { return mPackageName; } /** * Set plug-in package name. * * @param name Plug-in package name. */ public void setPackageName(final String name) { mPackageName = name; } /** * Get plug-in version. * * @return Plug-in version */ public String getVersion() { return mVersion; } /** * Set plug-in version. * * @param version Plug-in version */ public void setVersion(final String version) { mVersion = version; } /** * Get plug-in icon. * @return icon */ public Drawable getIcon() { return mIcon; } /** * Set plug-in icon. * @param icon plug-in icon */ public void setIcon(final Drawable icon) { mIcon = icon; } } /** * PluginAdapter class. */ private class PluginAdapter extends ArrayAdapter<PluginContainer> { /** LayoutInflater. */ private LayoutInflater mInflater; /** * Constructor. * * @param context Context. * @param objects Plug-in list object. */ public PluginAdapter(final Context context, final List<PluginContainer> objects) { super(context, 0, objects); mInflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); } @Override public View getView(final int position, final View convertView, final ViewGroup parent) { View cv; if (convertView == null) { cv = mInflater.inflate(R.layout.item_deviceplugin_list, parent, false); } else { cv = convertView; } final PluginContainer plugin = getItem(position); String name = plugin.getLabel(); TextView nameView = (TextView) cv.findViewById(R.id.devicelist_package_name); nameView.setText(name); Drawable icon = plugin.getIcon(); if (icon != null) { ImageView iconView = (ImageView) cv.findViewById(R.id.devicelist_icon); iconView.setImageDrawable(icon); } String version = plugin.getVersion(); TextView versionView = (TextView) cv.findViewById(R.id.devicelist_version); versionView.setText(getString(R.string.activity_devicepluginlist_version) + version); return cv; } } }
dConnectManager/dConnectManager/app/src/main/java/org/deviceconnect/android/manager/setting/DevicePluginListFragment.java
/* DevicePluginListFragment.java Copyright (c) 2015 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.manager.setting; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import org.deviceconnect.android.manager.BuildConfig; import org.deviceconnect.android.manager.DConnectApplication; import org.deviceconnect.android.manager.DevicePlugin; import org.deviceconnect.android.manager.DevicePluginManager; import org.deviceconnect.android.manager.R; import java.util.ArrayList; import java.util.List; /** * Device plug-in list fragment. * * @author NTT DOCOMO, INC. */ public class DevicePluginListFragment extends Fragment { /** Adapter. */ private PluginAdapter mPluginAdapter; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onResume() { super.onResume(); updatePluginList(); } /** * Create a PluginContainer from Device Plug-in. * @param pm PackageManager. * @param app ApplicationInfo. * @return Instance of DeviceContainer */ private PluginContainer createContainer(final PackageManager pm, final ApplicationInfo app) { PluginContainer container = new PluginContainer(); container.setLabel(app.loadLabel(pm).toString()); container.setPackageName(app.packageName); try { container.setIcon(pm.getApplicationIcon(app.packageName)); } catch (PackageManager.NameNotFoundException e) { // do nothing. if (BuildConfig.DEBUG) { Log.d("Manager", "Icon is not found."); } } try { PackageInfo info = pm.getPackageInfo(app.packageName, PackageManager.GET_META_DATA); container.setVersion(info.versionName); } catch (PackageManager.NameNotFoundException e) { // do nothing. if (BuildConfig.DEBUG) { Log.d("Manager", "VersionName is not found."); } } return container; } /** * Create a list of plug-in. * @return list of plug-in. */ private List<PluginContainer> createPluginContainers() { List<PluginContainer> containers = new ArrayList<>(); PackageManager pm = getActivity().getPackageManager(); DConnectApplication app = (DConnectApplication) getActivity().getApplication(); DevicePluginManager manager = app.getDevicePluginManager(); for (DevicePlugin plugin : manager.getDevicePlugins()) { try { ApplicationInfo info = pm.getApplicationInfo(plugin.getPackageName(), 0); containers.add(createContainer(pm, info)); } catch (PackageManager.NameNotFoundException e) { continue; } } return containers; } @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { mPluginAdapter = new PluginAdapter(getActivity(), createPluginContainers()); View rootView = inflater.inflate(R.layout.fragment_devicepluginlist, container, false); ListView listView = (ListView) rootView.findViewById(R.id.listview_pluginlist); listView.setAdapter(mPluginAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { openDevicePluginInformation(mPluginAdapter.getItem(position)); } }); return rootView; } @Override public boolean onOptionsItemSelected(final MenuItem item) { if (android.R.id.home == item.getItemId()) { getActivity().finish(); return true; } return super.onOptionsItemSelected(item); } /** * Update plug-in list. */ public void updatePluginList() { if (mPluginAdapter == null) { return; } if (getActivity() == null) { return; } getActivity().runOnUiThread(new Runnable() { @Override public void run() { mPluginAdapter.clear(); mPluginAdapter.addAll(createPluginContainers()); mPluginAdapter.notifyDataSetChanged(); } }); } /** * Open device plug-in information activity. * * @param container plug-in container */ private void openDevicePluginInformation(final PluginContainer container) { Intent intent = new Intent(); intent.setClass(getActivity(), DevicePluginInfoActivity.class); intent.putExtra(DevicePluginInfoActivity.PACKAGE_NAME, container.getPackageName()); startActivity(intent); } /** * PluginContainer class. */ static class PluginContainer { /** Label. */ private String mLabel; /** Package name. */ private String mPackageName; /** Version. */ private String mVersion; /** Icon. */ private Drawable mIcon; /** * Get plug-in Label. * * @return Plug-in label. */ public String getLabel() { return mLabel; } /** * Set plug-in label. * * @param label Plug-in label. */ public void setLabel(final String label) { if (label == null) { mLabel = "Unknown"; } else { mLabel = label; } } /** * Get plug-in package name. * * @return Plug-in package name. */ public String getPackageName() { return mPackageName; } /** * Set plug-in package name. * * @param name Plug-in package name. */ public void setPackageName(final String name) { mPackageName = name; } /** * Get plug-in version. * * @return Plug-in version */ public String getVersion() { return mVersion; } /** * Set plug-in version. * * @param version Plug-in version */ public void setVersion(final String version) { mVersion = version; } /** * Get plug-in icon. * @return icon */ public Drawable getIcon() { return mIcon; } /** * Set plug-in icon. * @param icon plug-in icon */ public void setIcon(final Drawable icon) { mIcon = icon; } } /** * PluginAdapter class. */ private class PluginAdapter extends ArrayAdapter<PluginContainer> { /** LayoutInflater. */ private LayoutInflater mInflater; /** * Constructor. * * @param context Context. * @param objects Plug-in list object. */ public PluginAdapter(final Context context, final List<PluginContainer> objects) { super(context, 0, objects); mInflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); } @Override public View getView(final int position, final View convertView, final ViewGroup parent) { View cv; if (convertView == null) { cv = mInflater.inflate(R.layout.item_deviceplugin_list, parent, false); } else { cv = convertView; } final PluginContainer plugin = getItem(position); String name = plugin.getLabel(); TextView nameView = (TextView) cv.findViewById(R.id.devicelist_package_name); nameView.setText(name); Drawable icon = plugin.getIcon(); if (icon != null) { ImageView iconView = (ImageView) cv.findViewById(R.id.devicelist_icon); iconView.setImageDrawable(icon); } String version = plugin.getVersion(); TextView versionView = (TextView) cv.findViewById(R.id.devicelist_version); versionView.setText(getString(R.string.activity_devicepluginlist_version) + version); return cv; } } }
デバイスプラグイン一覧の並び順をソート
dConnectManager/dConnectManager/app/src/main/java/org/deviceconnect/android/manager/setting/DevicePluginListFragment.java
デバイスプラグイン一覧の並び順をソート
Java
mit
9ed663020be6da403ada319e3a053c2b2c58ae2a
0
yDelouis/selfoss-android
package fr.ydelouis.selfoss.view; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.AttributeSet; import android.util.TypedValue; import android.widget.TextView; import fr.ydelouis.selfoss.R; public class AutoFitTextView extends TextView { private static final float THRESHOLD = 0.5f; private enum Mode { Width, Height, Both, None } private int minTextSize = 1; private int maxTextSize = 1000; private Mode mode = Mode.None; private boolean inComputation; private int widthMeasureSpec; private int heightMeasureSpec; public AutoFitTextView(Context context) { super(context); } public AutoFitTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public AutoFitTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray tAttrs = context.obtainStyledAttributes(attrs, R.styleable.AutoFitTextView, defStyle, 0); maxTextSize = tAttrs.getDimensionPixelSize(R.styleable.AutoFitTextView_maxTextSize, maxTextSize); minTextSize = tAttrs.getDimensionPixelSize(R.styleable.AutoFitTextView_minTextSize, minTextSize); tAttrs.recycle(); } private void resizeText() { if (getWidth() <= 0 || getHeight() <= 0) return; if(mode == Mode.None) return; final int targetWidth = getWidth(); final int targetHeight = getHeight(); inComputation = true; float higherSize = maxTextSize; float lowerSize = minTextSize; float textSize = getTextSize(); while(higherSize - lowerSize > THRESHOLD) { textSize = (higherSize + lowerSize) / 2; if (isTooBig(textSize, targetWidth, targetHeight)) { higherSize = textSize; } else { lowerSize = textSize; } } setTextSize(TypedValue.COMPLEX_UNIT_PX, lowerSize); measure(widthMeasureSpec, heightMeasureSpec); inComputation = false; } private boolean isTooBig(float textSize, int targetWidth, int targetHeight) { setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize); measure(0, 0); if(mode == Mode.Both) return getMeasuredWidth() >= targetWidth || getMeasuredHeight() >= targetHeight; if(mode == Mode.Width) return getMeasuredWidth() >= targetWidth; else return getMeasuredHeight() >= targetHeight; } private Mode getMode(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); if(widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY) return Mode.Both; if(widthMode == MeasureSpec.EXACTLY) return Mode.Width; if(heightMode == MeasureSpec.EXACTLY) return Mode.Height; return Mode.None; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if(!inComputation) { this.widthMeasureSpec = widthMeasureSpec; this.heightMeasureSpec = heightMeasureSpec; mode = getMode(widthMeasureSpec, heightMeasureSpec); resizeText(); } } @Override protected int getSuggestedMinimumWidth() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { return getMinimumWidth(); } Drawable background = getBackground(); setBackground(null); int minWidth = super.getSuggestedMinimumWidth(); setBackground(background); return minWidth; } @Override protected int getSuggestedMinimumHeight() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { return getMinimumHeight(); } Drawable background = getBackground(); setBackground(null); int minHeight = super.getSuggestedMinimumHeight(); setBackground(background); return minHeight; } @Override @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public void setBackground(Drawable background) { if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) super.setBackground(background); else setBackgroundDrawable(background); } @Override protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) { resizeText(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { if (w != oldw || h != oldh) resizeText(); } public int getMinTextSize() { return minTextSize; } public void setMinTextSize(int minTextSize) { this.minTextSize = minTextSize; resizeText(); } public int getMaxTextSize() { return maxTextSize; } public void setMaxTextSize(int maxTextSize) { this.maxTextSize = maxTextSize; resizeText(); } }
app/src/main/java/fr/ydelouis/selfoss/view/AutoFitTextView.java
package fr.ydelouis.selfoss.view; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.AttributeSet; import android.util.TypedValue; import android.widget.TextView; import fr.ydelouis.selfoss.R; public class AutoFitTextView extends TextView { private static final float THRESHOLD = 0.5f; private enum Mode { Width, Height, Both, None } private int minTextSize = 1; private int maxTextSize = 1000; private Mode mode = Mode.None; private boolean inComputation; private int widthMeasureSpec; private int heightMeasureSpec; public AutoFitTextView(Context context) { super(context); } public AutoFitTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public AutoFitTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray tAttrs = context.obtainStyledAttributes(attrs, R.styleable.AutoFitTextView, defStyle, 0); maxTextSize = tAttrs.getDimensionPixelSize(R.styleable.AutoFitTextView_maxTextSize, maxTextSize); minTextSize = tAttrs.getDimensionPixelSize(R.styleable.AutoFitTextView_minTextSize, minTextSize); tAttrs.recycle(); } private void resizeText() { if (getWidth() <= 0 || getHeight() <= 0) return; if(mode == Mode.None) return; final int targetWidth = getWidth(); final int targetHeight = getHeight(); inComputation = true; float higherSize = maxTextSize; float lowerSize = minTextSize; float textSize = getTextSize(); while(higherSize - lowerSize > THRESHOLD) { textSize = (higherSize + lowerSize) / 2; if (isTooBig(textSize, targetWidth, targetHeight)) { higherSize = textSize; } else { lowerSize = textSize; } } setTextSize(TypedValue.COMPLEX_UNIT_PX, lowerSize); measure(widthMeasureSpec, heightMeasureSpec); inComputation = false; } private boolean isTooBig(float textSize, int targetWidth, int targetHeight) { setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize); measure(0, 0); if(mode == Mode.Both) return getMeasuredWidth() >= targetWidth || getMeasuredHeight() >= targetHeight; if(mode == Mode.Width) return getMeasuredWidth() >= targetWidth; else return getMeasuredHeight() >= targetHeight; } private Mode getMode(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); if(widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY) return Mode.Both; if(widthMode == MeasureSpec.EXACTLY) return Mode.Width; if(heightMode == MeasureSpec.EXACTLY) return Mode.Height; return Mode.None; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if(!inComputation) { this.widthMeasureSpec = widthMeasureSpec; this.heightMeasureSpec = heightMeasureSpec; mode = getMode(widthMeasureSpec, heightMeasureSpec); resizeText(); } } @Override protected int getSuggestedMinimumWidth() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { return getMinimumWidth(); } Drawable background = getBackground(); setBackground(null); int minWidth = super.getSuggestedMinimumWidth(); setBackground(background); return minWidth; } @Override protected int getSuggestedMinimumHeight() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { return getMinimumHeight(); } Drawable background = getBackground(); setBackground(null); int minHeight = super.getSuggestedMinimumHeight(); setBackground(background); return minHeight; } @Override @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public void setBackground(Drawable background) { if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) super.setBackground(background); else setBackgroundDrawable(background); } @Override protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) { resizeText(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { if (w != oldw || h != oldh) resizeText(); } public int getMinTextSize() { return minTextSize; } public void setMinTextSize(int minTextSize) { this.minTextSize = minTextSize; resizeText(); } public int getMaxTextSize() { return maxTextSize; } public void setMaxTextSize(int maxTextSize) { this.maxTextSize = maxTextSize; resizeText(); } }
Fix compile warning
app/src/main/java/fr/ydelouis/selfoss/view/AutoFitTextView.java
Fix compile warning
Java
mit
e6f1654163ceff6add8ec93932b76e86f9a0cd27
0
carpikes/ingsw1-eftaios,carpikes/ingsw1-eftaios
package it.polimi.ingsw.client; import it.polimi.ingsw.client.cli.CLIView; import it.polimi.ingsw.client.network.Connection; import it.polimi.ingsw.client.network.ConnectionFactory; import it.polimi.ingsw.client.network.OnReceiveListener; import it.polimi.ingsw.game.GameMap; import it.polimi.ingsw.game.network.GameCommand; import it.polimi.ingsw.game.network.GameOpcode; import it.polimi.ingsw.game.network.GameStartInfo; import it.polimi.ingsw.game.network.ViewCommand; import it.polimi.ingsw.game.network.InfoOpcode; import it.polimi.ingsw.game.network.CoreOpcode; import it.polimi.ingsw.game.network.Opcode; import java.awt.Point; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** Client controller * @author Alain Carlucci ([email protected]) * @since May 18, 2015 */ public class GameController implements OnReceiveListener { private static final Logger LOG = Logger.getLogger(GameController.class.getName()); /** The view */ private View mView; /** The connection */ private Connection mConn; /** List of incoming packets/events */ private final LinkedBlockingQueue<GameCommand> mQueue; private final LinkedBlockingQueue<List<ViewCommand>> mViewQueue; /** True if the client must be shut down */ private boolean mStopEvent = false; private GameStartInfo mGameInfo = null; private Integer mMyTurn = null; private String mMyUsername = null; private List<Integer> listOfCards = new ArrayList<>(); private int mCurTurn = 0; /** The constructor */ public GameController(String[] args) { boolean mViewSet = false; String[] viewList = ViewFactory.getViewList(); if(args.length == 1) { for(int i = 0; i < viewList.length; i++) { String v = viewList[i]; if(v.equalsIgnoreCase(args[0])) { mView = ViewFactory.getView( this, i ); mViewSet = true; break; } } } if(!mViewSet) { CLIView tempView = new CLIView(this); int viewCode = tempView.askView( viewList ); mView = ViewFactory.getView(this, viewCode); } mQueue = new LinkedBlockingQueue<GameCommand>(); mViewQueue = new LinkedBlockingQueue<>(); new Thread(new Runnable() { @Override public void run() { try { while(isRunning()) { List<ViewCommand> cmd = mViewQueue.poll(100, TimeUnit.MILLISECONDS); if(cmd != null) mView.handleCommand(cmd); // TO BE CHANGED TO -> handleCommands() } } catch(InterruptedException e) { LOG.log(Level.FINEST, e.toString(), e); } GameController.this.stop(); mView.close(); } }).start(); } protected void enqueueViewCommand(List<ViewCommand> arrayList) { try { mViewQueue.put(arrayList); } catch(InterruptedException e) { LOG.log(Level.FINEST, e.toString(), e); } } /** Main loop */ public void run() { if(mView == null) return; if(!askInfo()) return; try { mConn.connect(); while(!mConn.isOnline()) Thread.sleep(100); mView.run(); while(!mStopEvent) { GameCommand cmd = mQueue.poll(1, TimeUnit.SECONDS); if(cmd == null) continue; processCommand(cmd); } mView.close(); } catch (IOException e) { mView.showError(e.toString()); LOG.log(Level.FINER, e.toString(), e); } catch (InterruptedException e) { LOG.log(Level.FINER, e.toString(), e); } stop(); return; } private boolean askInfo() { mView.startup(); String[] connList = ConnectionFactory.getConnectionList(); int conn = mView.askConnectionType(connList); mConn = ConnectionFactory.getConnection(conn); if(mConn == null) return false; mConn.setOnReceiveListener(this); String host = mView.askHost(); if(host == null || host.trim().length() == 0) return false; mConn.setHost(host.trim()); return true; } private void processCommand(GameCommand cmd) { String curUser = null; if(mGameInfo != null && mGameInfo.getPlayersList() != null) curUser = mGameInfo.getPlayersList()[mCurTurn].getUsername(); Opcode op = cmd.getOpcode(); if(op instanceof CoreOpcode) { parseCoreCmd(cmd); } else if(op instanceof GameOpcode) { parseGameCmd(cmd, curUser); } else if(op instanceof InfoOpcode) { parseInfoCmd(cmd, curUser); } } /* These commmands below are sent while game is running * and the map is loaded. * * TODO: Add a check into each state if the used variables are initialized. * Or, instead, a giant try-catch might be useful. * * @param cmd The command * @param curUser Current username */ @SuppressWarnings("unchecked") private void parseGameCmd(GameCommand cmd, String curUser) { Object obj = null; GameOpcode gop = (GameOpcode) cmd.getOpcode(); if(cmd.getArgs().length > 0) obj = cmd.getArgs()[0]; switch(gop) { case CMD_SC_AVAILABLE_COMMANDS: if(obj != null && obj instanceof ArrayList<?>) { List<?> tmp = (List<?>) obj; if(!tmp.isEmpty() && tmp.get(0) instanceof ViewCommand) enqueueViewCommand((List<ViewCommand>) tmp); } break; case CMD_SC_ADRENALINE_WRONG_STATE: break; case CMD_SC_CANNOT_USE_OBJ_CARD: break; case CMD_SC_DANGEROUS_CARD_DRAWN: break; case CMD_SC_DISCARD_OBJECT_CARD: break; case CMD_SC_END_OF_TURN: break; case CMD_SC_MOVE_DONE: break; case CMD_SC_OBJECT_CARD_OBTAINED: if(obj != null && obj instanceof Integer) { listOfCards.add( (Integer)obj ); mView.notifyObjectCardListChange( listOfCards ); } break; case CMD_SC_MOVE_INVALID: case CMD_SC_START_TURN: break; case CMD_SC_UPDATE_LOCAL_INFO: break; case CMD_SC_LOSE: mView.showInfo(null, "YOU'VE JUST LOST THE GAME. <3"); break; case CMD_SC_WIN: mView.showInfo(null, "You won! Congrats!"); break; default: break; } } /** Parse an InfoCommand * * @param cmd The command * @param curUser Current username */ @SuppressWarnings("unchecked") private void parseInfoCmd(GameCommand cmd, String curUser) { InfoOpcode op = (InfoOpcode) cmd.getOpcode(); switch(op) { case INFO_END_GAME: if(cmd.getArgs().length == 2) { Object obj = cmd.getArgs()[0]; Object obj2 = cmd.getArgs()[1]; if(cmd.getArgs()[0] != null && cmd.getArgs()[0] instanceof ArrayList<?> && obj2 != null && obj2 instanceof ArrayList<?>) { List<Integer> winnerList = (List<Integer>) obj; List<Integer> loserList = (List<Integer>) obj2; mView.showEnding(winnerList, loserList); stop(); } } break; case INFO_GOT_A_NEW_OBJ_CARD: mView.showInfo(curUser, "Draw new object card!"); break; case INFO_HAS_MOVED: mView.showInfo(curUser, "Player has moved"); break; case INFO_PLAYER_ATTACKED: if(cmd.getArgs().length == 3 && cmd.getArgs()[0] instanceof Point && cmd.getArgs()[1] instanceof ArrayList<?> && cmd.getArgs()[2] instanceof ArrayList<?>) { Point p = (Point) cmd.getArgs()[0]; mView.showInfo(curUser, "Player just attacked in sector " + mGameInfo.getMap().pointToString(p)); List<Integer> killedList = (List<Integer>) cmd.getArgs()[1]; if(killedList == null || killedList.isEmpty()) mView.showInfo(curUser, "Nobody has been killed"); else for(Integer i : killedList) mView.showInfo(curUser, mGameInfo.getPlayersList()[i].getUsername() + " has been killed"); List<Integer> defendedList = (List<Integer>) cmd.getArgs()[2]; if(defendedList != null && !defendedList.isEmpty()) for(Integer i : defendedList) mView.showInfo(curUser, mGameInfo.getPlayersList()[i].getUsername() + " has been attacked, but survived"); } break; case INFO_LOSER: mView.showInfo(curUser, "This player lost the game"); break; case INFO_NOISE: if(cmd.getArgs().length == 1) { Object obj = cmd.getArgs()[0]; if(obj != null && obj instanceof Point) { Point p = (Point) obj; mView.showNoiseInSector(curUser, p); } } break; case INFO_OBJ_CARD_USED: if(cmd.getArgs().length == 2 && cmd.getArgs()[1] instanceof String) { String name = (String) cmd.getArgs()[1]; mView.showInfo(curUser, "Used the object card '" + name + "'"); } else mView.showInfo(curUser, "Used a weird object card without a valid name"); break; case INFO_SILENCE: mView.showInfo(curUser, "Extracted dangerous card: Silence."); break; case INFO_SPOTLIGHT: mView.showInfo(curUser, "Spotlight. Not implemented yet"); // TODO here break; case INFO_START_TURN: if(cmd.getArgs().length == 1 && cmd.getArgs()[0] != null && cmd.getArgs()[0] instanceof Integer) { mCurTurn = (Integer) cmd.getArgs()[0]; if(mCurTurn == mMyTurn) mView.onMyTurn(); else mView.onOtherTurn(mGameInfo.getPlayersList()[mCurTurn].getUsername()); } break; case INFO_USED_HATCH: if(cmd.getArgs().length == 1 && cmd.getArgs()[0] != null && cmd.getArgs()[0] instanceof Point) { mGameInfo.getMap().useHatch((Point) cmd.getArgs()[0]); // TODO mView.notifyMapUpdate(); mView.showInfo(curUser, "Used a hatch"); } break; case INFO_WINNER: mView.showInfo(curUser, "This player won the game!"); break; default: break; } } /** Parse a CoreCommand * * @param cmd The command */ private void parseCoreCmd(GameCommand cmd) { String msg = ""; CoreOpcode lop = (CoreOpcode) cmd.getOpcode(); Object obj = null; if(cmd.getArgs().length > 0) obj = cmd.getArgs()[0]; switch(lop) { case CMD_SC_TIME: if(obj != null && obj instanceof Integer) mView.updateLoginTime((Integer) obj); break; case CMD_SC_STAT: if(obj != null && obj instanceof Integer) mView.updateLoginStat((Integer) obj); break; case CMD_SC_USERFAIL: msg = "Another player is using your name. Choose another one."; case CMD_SC_CHOOSEUSER: do { mMyUsername = mView.askUsername("".equals(msg)?"Choose a username":msg); if(mMyUsername != null) mMyUsername = mMyUsername.trim(); } while(mMyUsername == null || mMyUsername.length() == 0); mConn.sendPacket(new GameCommand(CoreOpcode.CMD_CS_USERNAME, mMyUsername)); break; case CMD_SC_USEROK: mView.showInfo(null, "Username accepted. Waiting for other players..."); break; case CMD_SC_MAPFAIL: case CMD_SC_CHOOSEMAP: Integer chosenMap; do { chosenMap = mView.askMap((String[])cmd.getArgs()); } while(chosenMap == null); mConn.sendPacket(new GameCommand(CoreOpcode.CMD_CS_LOADMAP, chosenMap)); break; case CMD_SC_MAPOK: break; case CMD_SC_RUN: runGame(obj); break; case CMD_BYE: stop(); break; case CMD_SC_FULL: mView.showError("Server is full. Try again later"); stop(); break; default: break; } } /** This method handles an incoming packet */ @Override public void onReceive(GameCommand obj) { synchronized(mQueue) { mQueue.add(obj); } } /** This method handles a disconnect event */ @Override public void onDisconnect() { stop(); } public boolean isRunning() { return !mStopEvent; } public void stop() { mStopEvent = true; } public GameMap getMap() { return mGameInfo.getMap(); } public void onMapPositionChosen(Point mCurHexCoords) { mConn.sendPacket(new GameCommand(GameOpcode.CMD_CS_CHOSEN_MAP_POSITION, mCurHexCoords)); } public void drawDangerousCard() { mConn.sendPacket(GameOpcode.CMD_CS_DRAW_DANGEROUS_CARD); } public void endTurn() { mConn.sendPacket(GameOpcode.CMD_CS_END_TURN); } public void attack() { mConn.sendPacket(GameOpcode.CMD_CS_ATTACK); } /** * @param choice */ public void sendChosenObjectCard(int choice) { mConn.sendPacket(new GameCommand(GameOpcode.CMD_CS_CHOSEN_OBJECT_CARD, choice)); } public void sendDiscardObjectCard(int choice) { mConn.sendPacket(new GameCommand(GameOpcode.CMD_CS_DISCARD_OBJECT_CARD, choice)); } private void runGame(Object obj) { if (obj != null && obj instanceof GameStartInfo) { mGameInfo = (GameStartInfo) obj; for(int i = 0; i < mGameInfo.getPlayersList().length; i++) { if(mGameInfo.getPlayersList()[i].getUsername().equals(mMyUsername)) { mMyTurn = i; break; } } mView.switchToMainScreen(mGameInfo); } else throw new RuntimeException("Can't get game infos!"); } }
ingsw/src/main/java/it/polimi/ingsw/client/GameController.java
package it.polimi.ingsw.client; import it.polimi.ingsw.client.cli.CLIView; import it.polimi.ingsw.client.network.Connection; import it.polimi.ingsw.client.network.ConnectionFactory; import it.polimi.ingsw.client.network.OnReceiveListener; import it.polimi.ingsw.game.GameMap; import it.polimi.ingsw.game.network.GameCommand; import it.polimi.ingsw.game.network.GameOpcode; import it.polimi.ingsw.game.network.GameStartInfo; import it.polimi.ingsw.game.network.ViewCommand; import it.polimi.ingsw.game.network.InfoOpcode; import it.polimi.ingsw.game.network.CoreOpcode; import it.polimi.ingsw.game.network.Opcode; import java.awt.Point; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** Client controller * @author Alain Carlucci ([email protected]) * @since May 18, 2015 */ public class GameController implements OnReceiveListener { private static final Logger LOG = Logger.getLogger(GameController.class.getName()); /** The view */ private View mView; /** The connection */ private Connection mConn; /** List of incoming packets/events */ private final LinkedBlockingQueue<GameCommand> mQueue; private final LinkedBlockingQueue<List<ViewCommand>> mViewQueue; /** True if the client must be shut down */ private boolean mStopEvent = false; private GameStartInfo mGameInfo = null; private Integer mMyTurn = null; private String mMyUsername = null; private List<Integer> listOfCards = new ArrayList<>(); private int mCurTurn = 0; /** The constructor */ public GameController(String[] args) { boolean mViewSet = false; String[] viewList = ViewFactory.getViewList(); if(args.length == 1) { for(int i = 0; i < viewList.length; i++) { String v = viewList[i]; if(v.equalsIgnoreCase(args[0])) { mView = ViewFactory.getView( this, i ); mViewSet = true; break; } } } if(!mViewSet) { CLIView tempView = new CLIView(this); int viewCode = tempView.askView( viewList ); mView = ViewFactory.getView(this, viewCode); } mQueue = new LinkedBlockingQueue<GameCommand>(); mViewQueue = new LinkedBlockingQueue<>(); new Thread(new Runnable() { @Override public void run() { try { while(isRunning()) { List<ViewCommand> cmd = mViewQueue.poll(100, TimeUnit.MILLISECONDS); if(cmd != null) mView.handleCommand(cmd); // TO BE CHANGED TO -> handleCommands() } } catch(InterruptedException e) { LOG.log(Level.FINEST, e.toString(), e); } GameController.this.stop(); mView.close(); } }).start(); } protected void enqueueViewCommand(List<ViewCommand> arrayList) { try { mViewQueue.put(arrayList); } catch(InterruptedException e) { LOG.log(Level.FINEST, e.toString(), e); } } /** Main loop */ public void run() { if(mView == null) return; if(!askInfo()) return; try { mConn.connect(); while(!mConn.isOnline()) Thread.sleep(100); mView.run(); while(!mStopEvent) { GameCommand cmd = mQueue.poll(1, TimeUnit.SECONDS); if(cmd == null) continue; processCommand(cmd); } mView.close(); } catch (IOException e) { mView.showError(e.toString()); LOG.log(Level.FINER, e.toString(), e); } catch (InterruptedException e) { LOG.log(Level.FINER, e.toString(), e); } stop(); return; } private boolean askInfo() { mView.startup(); String[] connList = ConnectionFactory.getConnectionList(); int conn = mView.askConnectionType(connList); mConn = ConnectionFactory.getConnection(conn); if(mConn == null) return false; mConn.setOnReceiveListener(this); String host = mView.askHost(); if(host == null || host.trim().length() == 0) return false; mConn.setHost(host.trim()); return true; } private void processCommand(GameCommand cmd) { String curUser = null; if(mGameInfo != null && mGameInfo.getPlayersList() != null) curUser = mGameInfo.getPlayersList()[mCurTurn].getUsername(); Opcode op = cmd.getOpcode(); if(op instanceof CoreOpcode) { parseCoreCmd(cmd); } else if(op instanceof GameOpcode) { parseGameCmd(cmd, curUser); } else if(op instanceof InfoOpcode) { parseInfoCmd(cmd, curUser); } } /* These commmands below are sent while game is running * and the map is loaded. * * TODO: Add a check into each state if the used variables are initialized. * Or, instead, a giant try-catch might be useful. * * @param cmd The command * @param curUser Current username */ @SuppressWarnings("unchecked") private void parseGameCmd(GameCommand cmd, String curUser) { Object obj = null; GameOpcode gop = (GameOpcode) cmd.getOpcode(); if(cmd.getArgs().length > 0) obj = cmd.getArgs()[0]; switch(gop) { case CMD_SC_AVAILABLE_COMMANDS: if(obj != null && obj instanceof ArrayList<?>) { List<?> tmp = (List<?>) obj; if(!tmp.isEmpty() && tmp.get(0) instanceof ViewCommand) enqueueViewCommand((List<ViewCommand>) tmp); } break; case CMD_SC_ADRENALINE_WRONG_STATE: break; case CMD_SC_CANNOT_USE_OBJ_CARD: break; case CMD_SC_DANGEROUS_CARD_DRAWN: break; case CMD_SC_DISCARD_OBJECT_CARD: break; case CMD_SC_END_OF_TURN: break; case CMD_SC_MOVE_DONE: break; case CMD_SC_OBJECT_CARD_OBTAINED: if(obj != null && obj instanceof Integer) { listOfCards.add( (Integer)obj ); mView.notifyObjectCardListChange( listOfCards ); } break; case CMD_SC_MOVE_INVALID: case CMD_SC_START_TURN: break; case CMD_SC_UPDATE_LOCAL_INFO: break; case CMD_SC_LOSE: mView.showInfo(null, "YOU'VE JUST LOST THE GAME. <3"); break; case CMD_SC_WIN: mView.showInfo(null, "You won! Congrats!"); break; default: break; } } /** Parse an InfoCommand * * @param cmd The command * @param curUser Current username */ @SuppressWarnings("unchecked") private void parseInfoCmd(GameCommand cmd, String curUser) { InfoOpcode op = (InfoOpcode) cmd.getOpcode(); switch(op) { case INFO_END_GAME: if(cmd.getArgs().length == 2) { Object obj = cmd.getArgs()[0]; Object obj2 = cmd.getArgs()[1]; if(cmd.getArgs()[0] != null && cmd.getArgs()[0] instanceof ArrayList<?> && obj2 != null && obj2 instanceof ArrayList<?>) { List<Integer> winnerList = (List<Integer>) obj; List<Integer> loserList = (List<Integer>) obj2; mView.showEnding(winnerList, loserList); stop(); } } break; case INFO_GOT_A_NEW_OBJ_CARD: mView.showInfo(curUser, "Draw new object card!"); break; case INFO_HAS_MOVED: mView.showInfo(curUser, "Player has moved"); break; case INFO_PLAYER_ATTACKED: if(cmd.getArgs().length == 2 && cmd.getArgs()[0] instanceof Point && cmd.getArgs()[1] instanceof ArrayList<?>) { Point p = (Point) cmd.getArgs()[0]; List<Integer> killedList = (List<Integer>) cmd.getArgs()[1]; mView.showInfo(curUser, "Player just attacked in sector " + mGameInfo.getMap().pointToString(p)); if(killedList == null || killedList.isEmpty()) mView.showInfo(curUser, "Nobody has been killed"); else for(Integer i : killedList) mView.showInfo(curUser, mGameInfo.getPlayersList()[i].getUsername() + " has been killed"); } break; case INFO_LOSER: mView.showInfo(curUser, "This player lost the game"); break; case INFO_NOISE: if(cmd.getArgs().length == 1) { Object obj = cmd.getArgs()[0]; if(obj != null && obj instanceof Point) { Point p = (Point) obj; mView.showNoiseInSector(curUser, p); } } break; case INFO_OBJ_CARD_USED: if(cmd.getArgs().length == 2 && cmd.getArgs()[1] instanceof String) { String name = (String) cmd.getArgs()[1]; mView.showInfo(curUser, "Used the object card '" + name + "'"); } else mView.showInfo(curUser, "Used a weird object card without a valid name"); break; case INFO_SILENCE: mView.showInfo(curUser, "Extracted dangerous card: Silence."); break; case INFO_SPOTLIGHT: mView.showInfo(curUser, "Spotlight. Not implemented yet"); // TODO here break; case INFO_START_TURN: if(cmd.getArgs().length == 1 && cmd.getArgs()[0] != null && cmd.getArgs()[0] instanceof Integer) { mCurTurn = (Integer) cmd.getArgs()[0]; if(mCurTurn == mMyTurn) mView.onMyTurn(); else mView.onOtherTurn(mGameInfo.getPlayersList()[mCurTurn].getUsername()); } break; case INFO_USED_HATCH: if(cmd.getArgs().length == 1 && cmd.getArgs()[0] != null && cmd.getArgs()[0] instanceof Point) { mGameInfo.getMap().useHatch((Point) cmd.getArgs()[0]); // TODO mView.notifyMapUpdate(); mView.showInfo(curUser, "Used a hatch"); } break; case INFO_WINNER: mView.showInfo(curUser, "This player won the game!"); break; default: break; } } /** Parse a CoreCommand * * @param cmd The command */ private void parseCoreCmd(GameCommand cmd) { String msg = ""; CoreOpcode lop = (CoreOpcode) cmd.getOpcode(); Object obj = null; if(cmd.getArgs().length > 0) obj = cmd.getArgs()[0]; switch(lop) { case CMD_SC_TIME: if(obj != null && obj instanceof Integer) mView.updateLoginTime((Integer) obj); break; case CMD_SC_STAT: if(obj != null && obj instanceof Integer) mView.updateLoginStat((Integer) obj); break; case CMD_SC_USERFAIL: msg = "Another player is using your name. Choose another one."; case CMD_SC_CHOOSEUSER: do { mMyUsername = mView.askUsername("".equals(msg)?"Choose a username":msg); if(mMyUsername != null) mMyUsername = mMyUsername.trim(); } while(mMyUsername == null || mMyUsername.length() == 0); mConn.sendPacket(new GameCommand(CoreOpcode.CMD_CS_USERNAME, mMyUsername)); break; case CMD_SC_USEROK: mView.showInfo(null, "Username accepted. Waiting for other players..."); break; case CMD_SC_MAPFAIL: case CMD_SC_CHOOSEMAP: Integer chosenMap; do { chosenMap = mView.askMap((String[])cmd.getArgs()); } while(chosenMap == null); mConn.sendPacket(new GameCommand(CoreOpcode.CMD_CS_LOADMAP, chosenMap)); break; case CMD_SC_MAPOK: break; case CMD_SC_RUN: runGame(obj); break; case CMD_BYE: stop(); break; case CMD_SC_FULL: mView.showError("Server is full. Try again later"); stop(); break; default: break; } } /** This method handles an incoming packet */ @Override public void onReceive(GameCommand obj) { synchronized(mQueue) { mQueue.add(obj); } } /** This method handles a disconnect event */ @Override public void onDisconnect() { stop(); } public boolean isRunning() { return !mStopEvent; } public void stop() { mStopEvent = true; } public GameMap getMap() { return mGameInfo.getMap(); } public void onMapPositionChosen(Point mCurHexCoords) { mConn.sendPacket(new GameCommand(GameOpcode.CMD_CS_CHOSEN_MAP_POSITION, mCurHexCoords)); } public void drawDangerousCard() { mConn.sendPacket(GameOpcode.CMD_CS_DRAW_DANGEROUS_CARD); } public void endTurn() { mConn.sendPacket(GameOpcode.CMD_CS_END_TURN); } public void attack() { mConn.sendPacket(GameOpcode.CMD_CS_ATTACK); } /** * @param choice */ public void sendChosenObjectCard(int choice) { mConn.sendPacket(new GameCommand(GameOpcode.CMD_CS_CHOSEN_OBJECT_CARD, choice)); } public void sendDiscardObjectCard(int choice) { mConn.sendPacket(new GameCommand(GameOpcode.CMD_CS_DISCARD_OBJECT_CARD, choice)); } private void runGame(Object obj) { if (obj != null && obj instanceof GameStartInfo) { mGameInfo = (GameStartInfo) obj; for(int i = 0; i < mGameInfo.getPlayersList().length; i++) { if(mGameInfo.getPlayersList()[i].getUsername().equals(mMyUsername)) { mMyTurn = i; break; } } mView.switchToMainScreen(mGameInfo); } else throw new RuntimeException("Can't get game infos!"); } }
Fix bug during attack
ingsw/src/main/java/it/polimi/ingsw/client/GameController.java
Fix bug during attack
Java
mit
8c6969b6ac682474d414b58279b7e5d3fae97be2
0
felHR85/UsbSerial,felHR85/UsbSerial,felHR85/UsbSerial
package com.felhr.usbserial; import java.util.concurrent.atomic.AtomicBoolean; import com.felhr.deviceids.CH34xIds; import com.felhr.deviceids.CP210xIds; import com.felhr.deviceids.FTDISioIds; import com.felhr.deviceids.PL2303Ids; import android.hardware.usb.UsbConstants; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbEndpoint; import android.hardware.usb.UsbInterface; import android.hardware.usb.UsbRequest; public abstract class UsbSerialDevice implements UsbSerialInterface { private static final String CLASS_ID = UsbSerialDevice.class.getSimpleName(); private static boolean mr1Version; protected final UsbDevice device; protected final UsbDeviceConnection connection; protected static final int USB_TIMEOUT = 5000; protected SerialBuffer serialBuffer; protected WorkerThread workerThread; protected WriteThread writeThread; protected ReadThread readThread; // Endpoints for synchronous read and write operations private UsbEndpoint inEndpoint; private UsbEndpoint outEndpoint; protected boolean asyncMode; // Get Android version if version < 4.3 It is not going to be asynchronous read operations static { if(android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) mr1Version = true; else mr1Version = false; } public UsbSerialDevice(UsbDevice device, UsbDeviceConnection connection) { this.device = device; this.connection = connection; this.asyncMode = true; serialBuffer = new SerialBuffer(mr1Version); } public static UsbSerialDevice createUsbSerialDevice(UsbDevice device, UsbDeviceConnection connection) { return createUsbSerialDevice(device, connection, -1); } public static UsbSerialDevice createUsbSerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface) { /* * It checks given vid and pid and will return a custom driver or a CDC serial driver. * When CDC is returned open() method is even more important, its response will inform about if it can be really * opened as a serial device with a generic CDC serial driver */ int vid = device.getVendorId(); int pid = device.getProductId(); if(FTDISioIds.isDeviceSupported(vid, pid)) return new FTDISerialDevice(device, connection, iface); else if(CP210xIds.isDeviceSupported(vid, pid)) return new CP2102SerialDevice(device, connection, iface); else if(PL2303Ids.isDeviceSupported(vid, pid)) return new PL2303SerialDevice(device, connection, iface); else if(CH34xIds.isDeviceSupported(vid, pid)) return new CH34xSerialDevice(device, connection, iface); else if(isCdcDevice(device)) return new CDCSerialDevice(device, connection, iface); else return null; } public static boolean isSupported(UsbDevice device) { int vid = device.getVendorId(); int pid = device.getProductId(); if(FTDISioIds.isDeviceSupported(vid, pid)) return true; else if(CP210xIds.isDeviceSupported(vid, pid)) return true; else if(PL2303Ids.isDeviceSupported(vid, pid)) return true; else if(CH34xIds.isDeviceSupported(vid, pid)) return true; else if(isCdcDevice(device)) return true; else return false; } // Common Usb Serial Operations (I/O Asynchronous) @Override public abstract boolean open(); @Override public void write(byte[] buffer) { if(asyncMode) serialBuffer.putWriteBuffer(buffer); } /** * <p> * Use this setter <strong>before</strong> calling {@link #open()} to override the default baud rate defined in this particular class. * </p> * * <p> * This is a workaround for devices where calling {@link #setBaudRate(int)} has no effect once {@link #open()} has been called. * </p> * * @param initialBaudRate baud rate to be used when initializing the serial connection */ public void setInitialBaudRate(int initialBaudRate) { // this class does not implement initialBaudRate } /** * Classes that do not implement {@link #setInitialBaudRate(int)} should always return -1 * * @return initial baud rate used when initializing the serial connection */ public int getInitialBaudRate() { return -1; } @Override public int read(UsbReadCallback mCallback) { if(!asyncMode) return -1; if(mr1Version) { workerThread.setCallback(mCallback); workerThread.getUsbRequest().queue(serialBuffer.getReadBuffer(), SerialBuffer.DEFAULT_READ_BUFFER_SIZE); }else { readThread.setCallback(mCallback); //readThread.start(); } return 0; } @Override public abstract void close(); // Common Usb Serial Operations (I/O Synchronous) @Override public abstract boolean syncOpen(); @Override public abstract void syncClose(); @Override public int syncWrite(byte[] buffer, int timeout) { if(!asyncMode) { if(buffer == null) return 0; return connection.bulkTransfer(outEndpoint, buffer, buffer.length, timeout); }else { return -1; } } @Override public int syncRead(byte[] buffer, int timeout) { if(asyncMode) { return -1; } if (buffer == null) return 0; return connection.bulkTransfer(inEndpoint, buffer, buffer.length, timeout); } // Serial port configuration @Override public abstract void setBaudRate(int baudRate); @Override public abstract void setDataBits(int dataBits); @Override public abstract void setStopBits(int stopBits); @Override public abstract void setParity(int parity); @Override public abstract void setFlowControl(int flowControl); //Debug options public void debug(boolean value) { if(serialBuffer != null) serialBuffer.debug(value); } private boolean isFTDIDevice() { return (this instanceof FTDISerialDevice); } public static boolean isCdcDevice(UsbDevice device) { int iIndex = device.getInterfaceCount(); for(int i=0;i<=iIndex-1;i++) { UsbInterface iface = device.getInterface(i); if(iface.getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA) return true; } return false; } /* * WorkerThread waits for request notifications from IN endpoint */ protected class WorkerThread extends Thread { private UsbSerialDevice usbSerialDevice; private UsbReadCallback callback; private UsbRequest requestIN; private AtomicBoolean working; public WorkerThread(UsbSerialDevice usbSerialDevice) { this.usbSerialDevice = usbSerialDevice; working = new AtomicBoolean(true); } @Override public void run() { while(working.get()) { UsbRequest request = connection.requestWait(); if(request != null && request.getEndpoint().getType() == UsbConstants.USB_ENDPOINT_XFER_BULK && request.getEndpoint().getDirection() == UsbConstants.USB_DIR_IN) { byte[] data = serialBuffer.getDataReceived(); // FTDI devices reserves two first bytes of an IN endpoint with info about // modem and Line. if(isFTDIDevice()) { ((FTDISerialDevice) usbSerialDevice).ftdiUtilities.checkModemStatus(data); //Check the Modem status serialBuffer.clearReadBuffer(); if(data.length > 2) { data = ((FTDISerialDevice) usbSerialDevice).ftdiUtilities.adaptArray(data); onReceivedData(data); } }else { // Clear buffer, execute the callback serialBuffer.clearReadBuffer(); onReceivedData(data); } // Queue a new request requestIN.queue(serialBuffer.getReadBuffer(), SerialBuffer.DEFAULT_READ_BUFFER_SIZE); } } } public void setCallback(UsbReadCallback callback) { this.callback = callback; } public void setUsbRequest(UsbRequest request) { this.requestIN = request; } public UsbRequest getUsbRequest() { return requestIN; } private void onReceivedData(byte[] data) { if(callback != null) callback.onReceivedData(data); } public void stopWorkingThread() { working.set(false); } } protected class WriteThread extends Thread { private UsbEndpoint outEndpoint; private AtomicBoolean working; public WriteThread() { working = new AtomicBoolean(true); } @Override public void run() { while(working.get()) { byte[] data = serialBuffer.getWriteBuffer(); connection.bulkTransfer(outEndpoint, data, data.length, USB_TIMEOUT); } } public void setUsbEndpoint(UsbEndpoint outEndpoint) { this.outEndpoint = outEndpoint; } public void stopWriteThread() { working.set(false); } } protected class ReadThread extends Thread { private UsbSerialDevice usbSerialDevice; private UsbReadCallback callback; private UsbEndpoint inEndpoint; private AtomicBoolean working; public ReadThread(UsbSerialDevice usbSerialDevice) { this.usbSerialDevice = usbSerialDevice; working = new AtomicBoolean(true); } public void setCallback(UsbReadCallback callback) { this.callback = callback; } @Override public void run() { byte[] dataReceived = null; while(working.get()) { int numberBytes; if(inEndpoint != null) numberBytes = connection.bulkTransfer(inEndpoint, serialBuffer.getBufferCompatible(), SerialBuffer.DEFAULT_READ_BUFFER_SIZE, 0); else numberBytes = 0; if(numberBytes > 0) { dataReceived = serialBuffer.getDataReceivedCompatible(numberBytes); // FTDI devices reserve two first bytes of an IN endpoint with info about // modem and Line. if(isFTDIDevice()) { ((FTDISerialDevice) usbSerialDevice).ftdiUtilities.checkModemStatus(dataReceived); if(dataReceived.length > 2) { dataReceived = ((FTDISerialDevice) usbSerialDevice).ftdiUtilities.adaptArray(dataReceived); onReceivedData(dataReceived); } }else { onReceivedData(dataReceived); } } } } public void setUsbEndpoint(UsbEndpoint inEndpoint) { this.inEndpoint = inEndpoint; } public void stopReadThread() { working.set(false); } private void onReceivedData(byte[] data) { if(callback != null) callback.onReceivedData(data); } } protected void setSyncParams(UsbEndpoint inEndpoint, UsbEndpoint outEndpoint) { this.inEndpoint = inEndpoint; this.outEndpoint = outEndpoint; } protected void setThreadsParams(UsbRequest request, UsbEndpoint endpoint) { if(mr1Version) { workerThread.setUsbRequest(request); writeThread.setUsbEndpoint(endpoint); }else { readThread.setUsbEndpoint(request.getEndpoint()); writeThread.setUsbEndpoint(endpoint); } } /* * Kill workingThread; This must be called when closing a device */ protected void killWorkingThread() { if(mr1Version && workerThread != null) { workerThread.stopWorkingThread(); workerThread = null; }else if(!mr1Version && readThread != null) { readThread.stopReadThread(); readThread = null; } } /* * Restart workingThread if it has been killed before */ protected void restartWorkingThread() { if(mr1Version && workerThread == null) { workerThread = new WorkerThread(this); workerThread.start(); while(!workerThread.isAlive()){} // Busy waiting }else if(!mr1Version && readThread == null) { readThread = new ReadThread(this); readThread.start(); while(!readThread.isAlive()){} // Busy waiting } } protected void killWriteThread() { if(writeThread != null) { writeThread.stopWriteThread(); writeThread = null; serialBuffer.resetWriteBuffer(); } } protected void restartWriteThread() { if(writeThread == null) { writeThread = new WriteThread(); writeThread.start(); while(!writeThread.isAlive()){} // Busy waiting } } }
usbserial/src/main/java/com/felhr/usbserial/UsbSerialDevice.java
package com.felhr.usbserial; import java.util.concurrent.atomic.AtomicBoolean; import com.felhr.deviceids.CH34xIds; import com.felhr.deviceids.CP210xIds; import com.felhr.deviceids.FTDISioIds; import com.felhr.deviceids.PL2303Ids; import android.hardware.usb.UsbConstants; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbEndpoint; import android.hardware.usb.UsbInterface; import android.hardware.usb.UsbRequest; public abstract class UsbSerialDevice implements UsbSerialInterface { private static final String CLASS_ID = UsbSerialDevice.class.getSimpleName(); private static boolean mr1Version; protected final UsbDevice device; protected final UsbDeviceConnection connection; protected static final int USB_TIMEOUT = 5000; protected SerialBuffer serialBuffer; protected WorkerThread workerThread; protected WriteThread writeThread; protected ReadThread readThread; // Endpoints for synchronous read and write operations private UsbEndpoint inEndpoint; private UsbEndpoint outEndpoint; protected boolean asyncMode; // Get Android version if version < 4.3 It is not going to be asynchronous read operations static { if(android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) mr1Version = true; else mr1Version = false; } public UsbSerialDevice(UsbDevice device, UsbDeviceConnection connection) { this.device = device; this.connection = connection; this.asyncMode = true; serialBuffer = new SerialBuffer(mr1Version); } public static UsbSerialDevice createUsbSerialDevice(UsbDevice device, UsbDeviceConnection connection) { return createUsbSerialDevice(device, connection, -1); } public static UsbSerialDevice createUsbSerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface) { /* * It checks given vid and pid and will return a custom driver or a CDC serial driver. * When CDC is returned open() method is even more important, its response will inform about if it can be really * opened as a serial device with a generic CDC serial driver */ int vid = device.getVendorId(); int pid = device.getProductId(); if(FTDISioIds.isDeviceSupported(vid, pid)) return new FTDISerialDevice(device, connection, iface); else if(CP210xIds.isDeviceSupported(vid, pid)) return new CP2102SerialDevice(device, connection, iface); else if(PL2303Ids.isDeviceSupported(vid, pid)) return new PL2303SerialDevice(device, connection, iface); else if(CH34xIds.isDeviceSupported(vid, pid)) return new CH34xSerialDevice(device, connection, iface); else if(isCdcDevice(device)) return new CDCSerialDevice(device, connection, iface); else return null; } public static boolean isSupported(UsbDevice device) { int vid = device.getVendorId(); int pid = device.getProductId(); if(FTDISioIds.isDeviceSupported(vid, pid)) return true; else if(CP210xIds.isDeviceSupported(vid, pid)) return true; else if(PL2303Ids.isDeviceSupported(vid, pid)) return true; else if(CH34xIds.isDeviceSupported(vid, pid)) return true; else if(isCdcDevice(device)) return true; else return false; } // Common Usb Serial Operations (I/O Asynchronous) @Override public abstract boolean open(); @Override public void write(byte[] buffer) { if(asyncMode) serialBuffer.putWriteBuffer(buffer); } @Override public int read(UsbReadCallback mCallback) { if(!asyncMode) return -1; if(mr1Version) { workerThread.setCallback(mCallback); workerThread.getUsbRequest().queue(serialBuffer.getReadBuffer(), SerialBuffer.DEFAULT_READ_BUFFER_SIZE); }else { readThread.setCallback(mCallback); //readThread.start(); } return 0; } @Override public abstract void close(); // Common Usb Serial Operations (I/O Synchronous) @Override public abstract boolean syncOpen(); @Override public abstract void syncClose(); @Override public int syncWrite(byte[] buffer, int timeout) { if(!asyncMode) { if(buffer == null) return 0; return connection.bulkTransfer(outEndpoint, buffer, buffer.length, timeout); }else { return -1; } } @Override public int syncRead(byte[] buffer, int timeout) { if(asyncMode) { return -1; } if (buffer == null) return 0; return connection.bulkTransfer(inEndpoint, buffer, buffer.length, timeout); } // Serial port configuration @Override public abstract void setBaudRate(int baudRate); @Override public abstract void setDataBits(int dataBits); @Override public abstract void setStopBits(int stopBits); @Override public abstract void setParity(int parity); @Override public abstract void setFlowControl(int flowControl); //Debug options public void debug(boolean value) { if(serialBuffer != null) serialBuffer.debug(value); } private boolean isFTDIDevice() { return (this instanceof FTDISerialDevice); } public static boolean isCdcDevice(UsbDevice device) { int iIndex = device.getInterfaceCount(); for(int i=0;i<=iIndex-1;i++) { UsbInterface iface = device.getInterface(i); if(iface.getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA) return true; } return false; } /* * WorkerThread waits for request notifications from IN endpoint */ protected class WorkerThread extends Thread { private UsbSerialDevice usbSerialDevice; private UsbReadCallback callback; private UsbRequest requestIN; private AtomicBoolean working; public WorkerThread(UsbSerialDevice usbSerialDevice) { this.usbSerialDevice = usbSerialDevice; working = new AtomicBoolean(true); } @Override public void run() { while(working.get()) { UsbRequest request = connection.requestWait(); if(request != null && request.getEndpoint().getType() == UsbConstants.USB_ENDPOINT_XFER_BULK && request.getEndpoint().getDirection() == UsbConstants.USB_DIR_IN) { byte[] data = serialBuffer.getDataReceived(); // FTDI devices reserves two first bytes of an IN endpoint with info about // modem and Line. if(isFTDIDevice()) { ((FTDISerialDevice) usbSerialDevice).ftdiUtilities.checkModemStatus(data); //Check the Modem status serialBuffer.clearReadBuffer(); if(data.length > 2) { data = ((FTDISerialDevice) usbSerialDevice).ftdiUtilities.adaptArray(data); onReceivedData(data); } }else { // Clear buffer, execute the callback serialBuffer.clearReadBuffer(); onReceivedData(data); } // Queue a new request requestIN.queue(serialBuffer.getReadBuffer(), SerialBuffer.DEFAULT_READ_BUFFER_SIZE); } } } public void setCallback(UsbReadCallback callback) { this.callback = callback; } public void setUsbRequest(UsbRequest request) { this.requestIN = request; } public UsbRequest getUsbRequest() { return requestIN; } private void onReceivedData(byte[] data) { if(callback != null) callback.onReceivedData(data); } public void stopWorkingThread() { working.set(false); } } protected class WriteThread extends Thread { private UsbEndpoint outEndpoint; private AtomicBoolean working; public WriteThread() { working = new AtomicBoolean(true); } @Override public void run() { while(working.get()) { byte[] data = serialBuffer.getWriteBuffer(); connection.bulkTransfer(outEndpoint, data, data.length, USB_TIMEOUT); } } public void setUsbEndpoint(UsbEndpoint outEndpoint) { this.outEndpoint = outEndpoint; } public void stopWriteThread() { working.set(false); } } protected class ReadThread extends Thread { private UsbSerialDevice usbSerialDevice; private UsbReadCallback callback; private UsbEndpoint inEndpoint; private AtomicBoolean working; public ReadThread(UsbSerialDevice usbSerialDevice) { this.usbSerialDevice = usbSerialDevice; working = new AtomicBoolean(true); } public void setCallback(UsbReadCallback callback) { this.callback = callback; } @Override public void run() { byte[] dataReceived = null; while(working.get()) { int numberBytes; if(inEndpoint != null) numberBytes = connection.bulkTransfer(inEndpoint, serialBuffer.getBufferCompatible(), SerialBuffer.DEFAULT_READ_BUFFER_SIZE, 0); else numberBytes = 0; if(numberBytes > 0) { dataReceived = serialBuffer.getDataReceivedCompatible(numberBytes); // FTDI devices reserve two first bytes of an IN endpoint with info about // modem and Line. if(isFTDIDevice()) { ((FTDISerialDevice) usbSerialDevice).ftdiUtilities.checkModemStatus(dataReceived); if(dataReceived.length > 2) { dataReceived = ((FTDISerialDevice) usbSerialDevice).ftdiUtilities.adaptArray(dataReceived); onReceivedData(dataReceived); } }else { onReceivedData(dataReceived); } } } } public void setUsbEndpoint(UsbEndpoint inEndpoint) { this.inEndpoint = inEndpoint; } public void stopReadThread() { working.set(false); } private void onReceivedData(byte[] data) { if(callback != null) callback.onReceivedData(data); } } protected void setSyncParams(UsbEndpoint inEndpoint, UsbEndpoint outEndpoint) { this.inEndpoint = inEndpoint; this.outEndpoint = outEndpoint; } protected void setThreadsParams(UsbRequest request, UsbEndpoint endpoint) { if(mr1Version) { workerThread.setUsbRequest(request); writeThread.setUsbEndpoint(endpoint); }else { readThread.setUsbEndpoint(request.getEndpoint()); writeThread.setUsbEndpoint(endpoint); } } /* * Kill workingThread; This must be called when closing a device */ protected void killWorkingThread() { if(mr1Version && workerThread != null) { workerThread.stopWorkingThread(); workerThread = null; }else if(!mr1Version && readThread != null) { readThread.stopReadThread(); readThread = null; } } /* * Restart workingThread if it has been killed before */ protected void restartWorkingThread() { if(mr1Version && workerThread == null) { workerThread = new WorkerThread(this); workerThread.start(); while(!workerThread.isAlive()){} // Busy waiting }else if(!mr1Version && readThread == null) { readThread = new ReadThread(this); readThread.start(); while(!readThread.isAlive()){} // Busy waiting } } protected void killWriteThread() { if(writeThread != null) { writeThread.stopWriteThread(); writeThread = null; serialBuffer.resetWriteBuffer(); } } protected void restartWriteThread() { if(writeThread == null) { writeThread = new WriteThread(); writeThread.start(); while(!writeThread.isAlive()){} // Busy waiting } } }
subclasses can now implement support for initial baud rate (see issue #91)
usbserial/src/main/java/com/felhr/usbserial/UsbSerialDevice.java
subclasses can now implement support for initial baud rate (see issue #91)
Java
cc0-1.0
99014699fb350850f1d84cc78d568d591a003ee5
0
wyldmods/ToolUtilities
package org.wyldmods.toolutilities.common.handlers; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemPickaxe; import net.minecraft.item.ItemSpade; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; import net.minecraft.network.INetHandler; import net.minecraft.network.play.client.C07PacketPlayerDigging; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.event.world.BlockEvent.BreakEvent; import org.wyldmods.toolutilities.common.Config; import org.wyldmods.toolutilities.common.ToolUpgrade; import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; public class AOEMining { @SubscribeEvent(priority = EventPriority.HIGHEST) public void mineAOE(BreakEvent event) { int x = event.x, y = event.y, z = event.z; EntityPlayer player = event.getPlayer(); if (player != null) { ItemStack current = player.getCurrentEquippedItem(); if (current != null && !event.world.isRemote) { if (current.getItem() instanceof ItemPickaxe || current.getItem() instanceof ItemSpade) { if (ToolUpgrade.THREExONE.isOn(current) && canHarvestBlock(player, event.block, event.block, event.blockMetadata, x, y, z)) { MovingObjectPosition mop = raytraceFromEntity(event.world, player, false, 4.5D); if (mop.sideHit != 0 && mop.sideHit != 1) { int[][] mineArray = { { 0, 1, 0 }, { 0, -1, 0 } }; mineOutEverything(mineArray, event); } } if (ToolUpgrade.THREExTHREE.isOn(current) && canHarvestBlock(player, event.block, event.block, event.blockMetadata, x, y, z)) { // 3x3 time! MovingObjectPosition mop = raytraceFromEntity(event.world, player, false, 4.5D); switch (mop.sideHit) { case 0: // Bottom int[][] mineArrayBottom = { { 1, 0, 1 }, { 1, 0, 0 }, { 1, 0, -1 }, { 0, 0, 1 }, { 0, 0, -1 }, { -1, 0, 1 }, { -1, 0, 0 }, { -1, 0, -1 } }; mineOutEverything(mineArrayBottom, event); break; case 1: // Top int[][] mineArrayTop = { { 1, 0, 1 }, { 1, 0, 0 }, { 1, 0, -1 }, { 0, 0, 1 }, { 0, 0, -1 }, { -1, 0, 1 }, { -1, 0, 0 }, { -1, 0, -1 } }; mineOutEverything(mineArrayTop, event); break; case 2: // South int[][] mineArraySouth = { { -1, 1, 0 }, { -1, 0, 0 }, { -1, -1, 0 }, { 0, 1, 0 }, { 0, -1, 0 }, { 1, 1, 0 }, { 1, 0, 0 }, { 1, -1, 0 } }; mineOutEverything(mineArraySouth, event); break; case 3: // North int[][] mineArrayNorth = { { -1, 1, 0 }, { -1, 0, 0 }, { -1, -1, 0 }, { 0, 1, 0 }, { 0, -1, 0 }, { 1, 1, 0 }, { 1, 0, 0 }, { 1, -1, 0 } }; mineOutEverything(mineArrayNorth, event); break; case 4: // East int[][] mineArrayEast = { { 0, 1, 1 }, { 0, 0, 1 }, { 0, -1, 1 }, { 0, 1, 0 }, { 0, -1, 0 }, { 0, 1, -1 }, { 0, 0, -1 }, { 0, -1, -1 } }; mineOutEverything(mineArrayEast, event); break; case 5: // West int[][] mineArrayWest = { { 0, 1, 1 }, { 0, 0, 1 }, { 0, -1, 1 }, { 0, 1, 0 }, { 0, -1, 0 }, { 0, 1, -1 }, { 0, 0, -1 }, { 0, -1, -1 } }; mineOutEverything(mineArrayWest, event); break; } } } } } return; } public void mineOutEverything(int[][] locations, BreakEvent event) { EntityPlayer player = event.getPlayer(); ItemStack current = player.getCurrentEquippedItem(); for (int i = 0; i < locations.length; i++) { Block miningBlock = event.world.getBlock(event.x + locations[i][0], event.y + locations[i][1], event.z + locations[i][2]); int meta = event.world.getBlockMetadata(event.x + locations[i][0], event.y + locations[i][1], event.z + locations[i][2]); if (canHarvestBlock(player, event.block, miningBlock, meta, event.x, event.y, event.z)) { mineBlock(event.world, event.x + locations[i][0], event.y + locations[i][1], event.z + locations[i][2], event.world.getBlockMetadata(event.x + locations[i][0], event.y + locations[i][1], event.z + locations[i][2]), player, miningBlock); current.damageItem(1, player); player.addExhaustion((float) 0.025); if (current.getItemDamage() >= (current.getMaxDamage() - 1)) // Off by one { player.destroyCurrentEquippedItem(); return; } } } } public static MovingObjectPosition raytraceFromEntity(World world, Entity player, boolean par3, double range) { // 100% borrowed from Tinkers Construct (CC0 license). float f = 1.0F; float f1 = player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * f; float f2 = player.prevRotationYaw + (player.rotationYaw - player.prevRotationYaw) * f; double d0 = player.prevPosX + (player.posX - player.prevPosX) * (double) f; double d1 = player.prevPosY + (player.posY - player.prevPosY) * (double) f; if (!world.isRemote && player instanceof EntityPlayer) d1 += 1.62D; double d2 = player.prevPosZ + (player.posZ - player.prevPosZ) * (double) f; Vec3 vec3 = Vec3.createVectorHelper(d0, d1, d2); float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI); float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI); float f5 = -MathHelper.cos(-f1 * 0.017453292F); float f6 = MathHelper.sin(-f1 * 0.017453292F); float f7 = f4 * f5; float f8 = f3 * f5; double d3 = range; if (player instanceof EntityPlayerMP) { d3 = ((EntityPlayerMP) player).theItemInWorldManager.getBlockReachDistance(); } Vec3 vec31 = vec3.addVector((double) f7 * d3, (double) f6 * d3, (double) f8 * d3); return world.func_147447_a(vec3, vec31, par3, !par3, par3); } public void mineBlock(World world, int x, int y, int z, int meta, EntityPlayer player, Block block) { // Workaround for dropping experience boolean silktouch = EnchantmentHelper.getSilkTouchModifier(player); int fortune = EnchantmentHelper.getFortuneModifier(player); int exp = block.getExpDrop(world, meta, fortune); block.onBlockHarvested(world, x, y, z, meta, player); if (block.removedByPlayer(world, player, x, y, z, true)) { block.onBlockDestroyedByPlayer(world, x, y, z, meta); block.harvestBlock(world, player, x, y, z, meta); // Workaround for dropping experience if (!silktouch) block.dropXpOnBlockBreak(world, x, y, z, exp); if (world.isRemote) { INetHandler handler = FMLClientHandler.instance().getClientPlayHandler(); if (handler != null && handler instanceof NetHandlerPlayClient) { NetHandlerPlayClient handlerClient = (NetHandlerPlayClient) handler; handlerClient.addToSendQueue(new C07PacketPlayerDigging(0, x, y, z, Minecraft.getMinecraft().objectMouseOver.sideHit)); handlerClient.addToSendQueue(new C07PacketPlayerDigging(2, x, y, z, Minecraft.getMinecraft().objectMouseOver.sideHit)); } } else if (Config.noisyBlocks) { world.playAuxSFX(2001, x, y, z, Block.getIdFromBlock(block) + (meta << 12)); } } } private boolean canHarvestBlock(EntityPlayer player, Block origBlock, Block block, int meta, int x, int y, int z) { ItemStack current = player.getCurrentEquippedItem(); if (current == null) return false; String toolClass; if (current.getItem() instanceof ItemPickaxe) { toolClass = "pickaxe"; } else { toolClass = "shovel"; } float hardness = block.getBlockHardness(player.worldObj, x, y, z); float digSpeed = ((ItemTool)current.getItem()).getDigSpeed(current, block, meta); //It works. It just does. return (digSpeed>1.0F && block.getHarvestLevel(meta) <= ((ItemTool)current.getItem()).getHarvestLevel(current, toolClass) &&origBlock.getBlockHardness(player.worldObj, x, y, z) >= hardness - 1.5); } }
src/main/java/org/wyldmods/toolutilities/common/handlers/AOEMining.java
package org.wyldmods.toolutilities.common.handlers; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemPickaxe; import net.minecraft.item.ItemSpade; import net.minecraft.item.ItemStack; import net.minecraft.network.INetHandler; import net.minecraft.network.play.client.C07PacketPlayerDigging; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.event.world.BlockEvent.BreakEvent; import org.wyldmods.toolutilities.common.Config; import org.wyldmods.toolutilities.common.ToolUpgrade; import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; public class AOEMining { @SubscribeEvent(priority = EventPriority.HIGHEST) public void mineAOE(BreakEvent event) { int x = event.x, y = event.y, z = event.z; EntityPlayer player = event.getPlayer(); if (player != null) { ItemStack current = player.getCurrentEquippedItem(); if (current != null && !event.world.isRemote) { if (current.getItem() instanceof ItemPickaxe || current.getItem() instanceof ItemSpade) { if (ToolUpgrade.THREExONE.isOn(current) && canHarvestBlock(player, event.block, event.block, event.blockMetadata, x, y, z)) { MovingObjectPosition mop = raytraceFromEntity(event.world, player, false, 4.5D); if (mop.sideHit != 0 && mop.sideHit != 1) { int[][] mineArray = { { 0, 1, 0 }, { 0, -1, 0 } }; mineOutEverything(mineArray, event); } } if (ToolUpgrade.THREExTHREE.isOn(current) && canHarvestBlock(player, event.block, event.block, event.blockMetadata, x, y, z)) { // 3x3 time! MovingObjectPosition mop = raytraceFromEntity(event.world, player, false, 4.5D); switch (mop.sideHit) { case 0: // Bottom int[][] mineArrayBottom = { { 1, 0, 1 }, { 1, 0, 0 }, { 1, 0, -1 }, { 0, 0, 1 }, { 0, 0, -1 }, { -1, 0, 1 }, { -1, 0, 0 }, { -1, 0, -1 } }; mineOutEverything(mineArrayBottom, event); break; case 1: // Top int[][] mineArrayTop = { { 1, 0, 1 }, { 1, 0, 0 }, { 1, 0, -1 }, { 0, 0, 1 }, { 0, 0, -1 }, { -1, 0, 1 }, { -1, 0, 0 }, { -1, 0, -1 } }; mineOutEverything(mineArrayTop, event); break; case 2: // South int[][] mineArraySouth = { { -1, 1, 0 }, { -1, 0, 0 }, { -1, -1, 0 }, { 0, 1, 0 }, { 0, -1, 0 }, { 1, 1, 0 }, { 1, 0, 0 }, { 1, -1, 0 } }; mineOutEverything(mineArraySouth, event); break; case 3: // North int[][] mineArrayNorth = { { -1, 1, 0 }, { -1, 0, 0 }, { -1, -1, 0 }, { 0, 1, 0 }, { 0, -1, 0 }, { 1, 1, 0 }, { 1, 0, 0 }, { 1, -1, 0 } }; mineOutEverything(mineArrayNorth, event); break; case 4: // East int[][] mineArrayEast = { { 0, 1, 1 }, { 0, 0, 1 }, { 0, -1, 1 }, { 0, 1, 0 }, { 0, -1, 0 }, { 0, 1, -1 }, { 0, 0, -1 }, { 0, -1, -1 } }; mineOutEverything(mineArrayEast, event); break; case 5: // West int[][] mineArrayWest = { { 0, 1, 1 }, { 0, 0, 1 }, { 0, -1, 1 }, { 0, 1, 0 }, { 0, -1, 0 }, { 0, 1, -1 }, { 0, 0, -1 }, { 0, -1, -1 } }; mineOutEverything(mineArrayWest, event); break; } } } } } return; } public void mineOutEverything(int[][] locations, BreakEvent event) { EntityPlayer player = event.getPlayer(); ItemStack current = player.getCurrentEquippedItem(); for (int i = 0; i < locations.length; i++) { Block miningBlock = event.world.getBlock(event.x + locations[i][0], event.y + locations[i][1], event.z + locations[i][2]); int meta = event.world.getBlockMetadata(event.x + locations[i][0], event.y + locations[i][1], event.z + locations[i][2]); if (canHarvestBlock(player, event.block, miningBlock, meta, event.x, event.y, event.z)) { mineBlock(event.world, event.x + locations[i][0], event.y + locations[i][1], event.z + locations[i][2], event.world.getBlockMetadata(event.x + locations[i][0], event.y + locations[i][1], event.z + locations[i][2]), player, miningBlock); current.damageItem(1, player); player.addExhaustion((float) 0.025); if (current.getItemDamage() >= (current.getMaxDamage() - 1)) // Off by one { player.destroyCurrentEquippedItem(); return; } } } } public static MovingObjectPosition raytraceFromEntity(World world, Entity player, boolean par3, double range) { // 100% borrowed from Tinkers Construct (CC0 license). float f = 1.0F; float f1 = player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * f; float f2 = player.prevRotationYaw + (player.rotationYaw - player.prevRotationYaw) * f; double d0 = player.prevPosX + (player.posX - player.prevPosX) * (double) f; double d1 = player.prevPosY + (player.posY - player.prevPosY) * (double) f; if (!world.isRemote && player instanceof EntityPlayer) d1 += 1.62D; double d2 = player.prevPosZ + (player.posZ - player.prevPosZ) * (double) f; Vec3 vec3 = Vec3.createVectorHelper(d0, d1, d2); float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI); float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI); float f5 = -MathHelper.cos(-f1 * 0.017453292F); float f6 = MathHelper.sin(-f1 * 0.017453292F); float f7 = f4 * f5; float f8 = f3 * f5; double d3 = range; if (player instanceof EntityPlayerMP) { d3 = ((EntityPlayerMP) player).theItemInWorldManager.getBlockReachDistance(); } Vec3 vec31 = vec3.addVector((double) f7 * d3, (double) f6 * d3, (double) f8 * d3); return world.func_147447_a(vec3, vec31, par3, !par3, par3); } public void mineBlock(World world, int x, int y, int z, int meta, EntityPlayer player, Block block) { // Workaround for dropping experience boolean silktouch = EnchantmentHelper.getSilkTouchModifier(player); int fortune = EnchantmentHelper.getFortuneModifier(player); int exp = block.getExpDrop(world, meta, fortune); block.onBlockHarvested(world, x, y, z, meta, player); if (block.removedByPlayer(world, player, x, y, z, true)) { block.onBlockDestroyedByPlayer(world, x, y, z, meta); block.harvestBlock(world, player, x, y, z, meta); // Workaround for dropping experience if (!silktouch) block.dropXpOnBlockBreak(world, x, y, z, exp); if (world.isRemote) { INetHandler handler = FMLClientHandler.instance().getClientPlayHandler(); if (handler != null && handler instanceof NetHandlerPlayClient) { NetHandlerPlayClient handlerClient = (NetHandlerPlayClient) handler; handlerClient.addToSendQueue(new C07PacketPlayerDigging(0, x, y, z, Minecraft.getMinecraft().objectMouseOver.sideHit)); handlerClient.addToSendQueue(new C07PacketPlayerDigging(2, x, y, z, Minecraft.getMinecraft().objectMouseOver.sideHit)); } } else if (Config.noisyBlocks) { world.playAuxSFX(2001, x, y, z, Block.getIdFromBlock(block) + (meta << 12)); } } } private boolean canHarvestBlock(EntityPlayer player, Block origBlock, Block block, int meta, int x, int y, int z) { ItemStack current = player.getCurrentEquippedItem(); if (current == null) return false; if (block.getHarvestTool(meta) != null && current.getItem().getToolClasses(current).contains(block.getHarvestTool(meta))) { int harvestLevel = block.getHarvestLevel(meta); float hardness = block.getBlockHardness(player.worldObj, x, y, z); return harvestLevel <= current.getItem().getHarvestLevel(current, block.getHarvestTool(meta)) && origBlock.getBlockHardness(player.worldObj, x, y, z) >= hardness - 1.5; } return false; } }
Fixed harvesting with strange chisel Seriously, it's really strange.
src/main/java/org/wyldmods/toolutilities/common/handlers/AOEMining.java
Fixed harvesting with strange chisel
Java
mpl-2.0
add27e4e3bc59fdfb572404f3ea0a0a76638638c
0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
/* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ package com.sun.star.wiki; import javax.swing.text.html.*; import javax.swing.text.MutableAttributeSet; public class EditPageParser extends HTMLEditorKit.ParserCallback { protected String m_sEditTime = ""; protected String m_sEditToken = ""; protected String m_sLoginToken = ""; protected String m_sMainURL = ""; private boolean m_bHTMLStartFound = false; private boolean m_bInHead = false; protected int m_nWikiArticleStart = -1; protected int m_nWikiArticleEnd = -1; protected int m_nHTMLArticleStart = -1; protected int m_nHTMLArticleEnd = -1; protected int m_nNoArticleInd = -1; protected int m_nErrorInd = -1; @Override public void handleComment( char[] data,int pos ) { // insert code to handle comments } @Override public void handleEndTag( HTML.Tag t,int pos ) { if ( t == HTML.Tag.TEXTAREA ) { m_nWikiArticleEnd = pos; } else if ( t == HTML.Tag.DIV ) { if ( m_bHTMLStartFound ) { m_nHTMLArticleStart = pos+6; m_bHTMLStartFound = false; } } else if ( t == HTML.Tag.HEAD ) { m_bInHead = false; } } @Override public void handleError( String errorMsg,int pos ) { } @Override public void handleSimpleTag( HTML.Tag t, MutableAttributeSet a,int pos ) { // insert code to handle simple tags if ( t == HTML.Tag.INPUT ) { String sName = ( String ) a.getAttribute( HTML.Attribute.NAME ); if ( sName != null ) { if ( sName.equalsIgnoreCase( "wpEdittime" ) ) { this.m_sEditTime = ( String ) a.getAttribute( HTML.Attribute.VALUE ); } else if ( sName.equalsIgnoreCase( "wpEditToken" ) ) { this.m_sEditToken = ( String ) a.getAttribute( HTML.Attribute.VALUE ); } else if ( sName.equalsIgnoreCase( "wpLoginToken" ) ) { this.m_sLoginToken = ( String ) a.getAttribute( HTML.Attribute.VALUE ); } } } else if ( t == HTML.Tag.LINK ) { if ( m_bInHead ) { String sName = ( String ) a.getAttribute( HTML.Attribute.HREF ); if ( sName != null ) { int nIndexStart = sName.indexOf( "index.php" ); // get the main URL from the first header-link with index.php // the link with "action=edit" inside is preferable if ( nIndexStart>= 0 && ( m_sMainURL.length() == 0 || sName.indexOf( "action=edit" ) >= 0 ) ) { m_sMainURL = sName.substring( 0, nIndexStart ); } } } } } @Override public void handleStartTag( HTML.Tag t, MutableAttributeSet a,int pos ) { // insert code to handle starting tags String sClass; if ( t == HTML.Tag.HEAD ) { m_bInHead = true; } if ( t == HTML.Tag.TEXTAREA ) { String sName = ( String ) a.getAttribute( HTML.Attribute.NAME ); if ( sName != null ) { if ( sName.equalsIgnoreCase( "wpTextbox1" ) ) { m_nWikiArticleStart = pos; } } } else if ( t == HTML.Tag.DIV ) { String sId = ( String ) a.getAttribute( HTML.Attribute.ID ); sClass = ( String ) a.getAttribute( HTML.Attribute.CLASS ); if ( sId != null ) { if ( sId.equalsIgnoreCase( "contentSub" ) ) { m_bHTMLStartFound = true; } } if ( sClass != null ) { if ( sClass.equalsIgnoreCase( "printfooter" ) ) { m_nHTMLArticleEnd = pos; } else if ( sClass.equalsIgnoreCase( "noarticletext" ) ) { m_nNoArticleInd = pos; } else if ( sClass.equalsIgnoreCase( "errorbox" ) ) { m_nErrorInd = pos; } } } else if ( t == HTML.Tag.P ) { sClass = ( String ) a.getAttribute( HTML.Attribute.CLASS ); if ( sClass != null && sClass.equalsIgnoreCase( "error" ) ) { m_nErrorInd = pos; } } } }
swext/mediawiki/src/com/sun/star/wiki/EditPageParser.java
/* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ package com.sun.star.wiki; import javax.swing.text.html.*; import javax.swing.text.MutableAttributeSet; public class EditPageParser extends HTMLEditorKit.ParserCallback { protected String m_sEditTime = ""; protected String m_sEditToken = ""; protected String m_sLoginToken = ""; protected String m_sMainURL = ""; private boolean m_bHTMLStartFound = false; private boolean m_bInHead = false; protected int m_nWikiArticleStart = -1; protected int m_nWikiArticleEnd = -1; protected int m_nHTMLArticleStart = -1; protected int m_nHTMLArticleEnd = -1; protected int m_nNoArticleInd = -1; protected int m_nErrorInd = -1; @Override public void handleComment( char[] data,int pos ) { // insert code to handle comments } @Override public void handleEndTag( HTML.Tag t,int pos ) { if ( t == HTML.Tag.TEXTAREA ) { m_nWikiArticleEnd = pos; } else if ( t == HTML.Tag.DIV ) { if ( m_bHTMLStartFound ) { m_nHTMLArticleStart = pos+6; m_bHTMLStartFound = false; } } else if ( t == HTML.Tag.HEAD ) { m_bInHead = false; } } @Override public void handleError( String errorMsg,int pos ) { } @Override public void handleSimpleTag( HTML.Tag t, MutableAttributeSet a,int pos ) { // insert code to handle simple tags if ( t == HTML.Tag.INPUT ) { String sName = ( String ) a.getAttribute( HTML.Attribute.NAME ); if ( sName != null ) { if ( sName.equalsIgnoreCase( "wpEdittime" ) ) { this.m_sEditTime = ( String ) a.getAttribute( HTML.Attribute.VALUE ); } else if ( sName.equalsIgnoreCase( "wpEditToken" ) ) { this.m_sEditToken = ( String ) a.getAttribute( HTML.Attribute.VALUE ); } else if ( sName.equalsIgnoreCase( "wpLoginToken" ) ) { this.m_sLoginToken = ( String ) a.getAttribute( HTML.Attribute.VALUE ); } } } else if ( t == HTML.Tag.LINK ) { if ( m_bInHead ) { String sName = ( String ) a.getAttribute( HTML.Attribute.HREF ); if ( sName != null ) { int nIndexStart = sName.indexOf( "index.php" ); // get the main URL from the first header-link with index.php // the link with "action=edit" inside is preferable if ( nIndexStart>= 0 && ( m_sMainURL.length() == 0 || sName.indexOf( "action=edit" ) >= 0 ) ) { m_sMainURL = sName.substring( 0, nIndexStart ); } } } } } @Override public void handleStartTag( HTML.Tag t, MutableAttributeSet a,int pos ) { // insert code to handle starting tags String sName = ""; String sId = ""; String sClass = ""; if ( t == HTML.Tag.HEAD ) { m_bInHead = true; } if ( t == HTML.Tag.TEXTAREA ) { sName = ( String ) a.getAttribute( HTML.Attribute.NAME ); if ( sName != null ) { if ( sName.equalsIgnoreCase( "wpTextbox1" ) ) { m_nWikiArticleStart = pos; } } } else if ( t == HTML.Tag.DIV ) { sId = ( String ) a.getAttribute( HTML.Attribute.ID ); sClass = ( String ) a.getAttribute( HTML.Attribute.CLASS ); if ( sId != null ) { if ( sId.equalsIgnoreCase( "contentSub" ) ) { m_bHTMLStartFound = true; } } if ( sClass != null ) { if ( sClass.equalsIgnoreCase( "printfooter" ) ) { m_nHTMLArticleEnd = pos; } else if ( sClass.equalsIgnoreCase( "noarticletext" ) ) { m_nNoArticleInd = pos; } else if ( sClass.equalsIgnoreCase( "errorbox" ) ) { m_nErrorInd = pos; } } } else if ( t == HTML.Tag.P ) { sClass = ( String ) a.getAttribute( HTML.Attribute.CLASS ); if ( sClass != null && sClass.equalsIgnoreCase( "error" ) ) { m_nErrorInd = pos; } } } }
mediawiki: the assigned value is never used Change-Id: Icb2c4477b96c6bab9004b9c7ead2272b86e78dfb Reviewed-on: https://gerrit.libreoffice.org/11297 Reviewed-by: Noel Grandin <[email protected]> Tested-by: Noel Grandin <[email protected]>
swext/mediawiki/src/com/sun/star/wiki/EditPageParser.java
mediawiki: the assigned value is never used
Java
agpl-3.0
22dc9758dc2df6f4f0009bcab375c26ba606a10e
0
roskens/opennms-pre-github,tdefilip/opennms,aihua/opennms,rdkgit/opennms,rdkgit/opennms,tdefilip/opennms,roskens/opennms-pre-github,rdkgit/opennms,aihua/opennms,roskens/opennms-pre-github,rdkgit/opennms,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,roskens/opennms-pre-github,tdefilip/opennms,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,tdefilip/opennms,roskens/opennms-pre-github,tdefilip/opennms,aihua/opennms,rdkgit/opennms,aihua/opennms,aihua/opennms,rdkgit/opennms,roskens/opennms-pre-github,rdkgit/opennms,aihua/opennms,aihua/opennms,rdkgit/opennms,rdkgit/opennms,rdkgit/opennms,tdefilip/opennms,tdefilip/opennms,roskens/opennms-pre-github,tdefilip/opennms,tdefilip/opennms
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2009-2011 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <[email protected]> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.provision.service.dns; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; 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 javax.xml.bind.JAXBException; import org.apache.commons.io.IOExceptionWithCause; import org.apache.commons.lang.StringUtils; import org.opennms.core.utils.LogUtils; import org.opennms.core.utils.ThreadCategory; import org.opennms.core.xml.JaxbUtils; import org.opennms.netmgt.provision.persist.requisition.Requisition; import org.opennms.netmgt.provision.persist.requisition.RequisitionInterface; import org.opennms.netmgt.provision.persist.requisition.RequisitionMonitoredService; import org.opennms.netmgt.provision.persist.requisition.RequisitionNode; import org.xbill.DNS.ARecord; import org.xbill.DNS.Name; import org.xbill.DNS.Record; import org.xbill.DNS.TSIG; import org.xbill.DNS.Type; import org.xbill.DNS.ZoneTransferException; import org.xbill.DNS.ZoneTransferIn; /** * Implementation of <code>java.net.URLConnection</code> for handling * URLs specified in the Provisiond configuration requesting an import * requisition based on the A records of a zone transfer for a DNS server. * * @author <a href="mailto:[email protected]">David Hustace</a> * @version $Id: $ */ public class DnsRequisitionUrlConnection extends URLConnection { private static final String EXPRESSION_ARG = "expression"; private static final String SERVICES_ARG = "services"; private static final String FID_HASH_SRC_ARG = "foreignidhashsource"; private static final String[] HASH_IP_KEYWORDS = { "ip", "addr" }; private static final String[] HASH_LABEL_KEYWORDS = { "name", "label" }; private static final String QUERY_ARG_SEPARATOR = "&"; /** Constant <code>URL_SCHEME="dns://"</code> */ public static final String URL_SCHEME = "dns://"; /** Constant <code>PROTOCOL="dns"</code> */ public static final String PROTOCOL = "dns"; private String m_zone; //TODO implement this private Long m_serial; //TODO implement this private Boolean m_fallback; //TODO implement this private TSIG m_key; private URL m_url; private int m_port; private String m_foreignSource; private int m_foreignIdHashSource; private String[] m_services; private static Map<String, String> m_args; /** * <p>Constructor for DnsRequisitionUrlConnection.</p> * * @param url a {@link java.net.URL} object. * @throws java.net.MalformedURLException if any. */ protected DnsRequisitionUrlConnection(URL url) throws MalformedURLException { super(url); m_args = getUrlArgs(url); validateDnsUrl(url); m_url = url; m_port = url.getPort() == -1 ? 53 : url.getPort(); m_zone = parseZone(url); m_foreignSource = parseForeignSource(url); m_foreignIdHashSource = getForeignIdHashSource(); m_services = getServices(); if (m_zone == null) { throw new IllegalArgumentException("Specified Zone is null"); } m_serial = Long.valueOf(0L); m_fallback = Boolean.FALSE; m_key = null; } /** * Determine services to be provisioned from URL * * @return a String[] of opennms service names */ private String[] getServices() { // TODO validate services against service table of database String[] services = "ICMP,SNMP".split(","); if (getArgs() != null && getArgs().get(SERVICES_ARG) != null) { services = getArgs().get(SERVICES_ARG).split(","); } return services; } /** * Determine source for computing hash for foreignId from URL * * @return a String of "ipAddress" or "nodeLabel" */ private int getForeignIdHashSource() { int result = 0; if (getArgs() != null && getArgs().get(FID_HASH_SRC_ARG) != null) { String hashSourceArg = getArgs().get(FID_HASH_SRC_ARG).toLowerCase(); for (String keyword : HASH_IP_KEYWORDS) { if (hashSourceArg.contains(keyword)) { result = 2; break; } } for (String keyword : HASH_LABEL_KEYWORDS) { if (hashSourceArg.contains(keyword)) { result++; break; } } } return result; } /** * {@inheritDoc} * * This is a no op. */ @Override public void connect() throws IOException { } /** * {@inheritDoc} * * Creates a ByteArrayInputStream implementation of InputStream of the XML marshaled version * of the Requisition class. Calling close on this stream is safe. */ @Override public InputStream getInputStream() throws IOException { InputStream stream = null; try { Requisition r = buildRequisitionFromZoneTransfer(); stream = new ByteArrayInputStream(jaxBMarshal(r).getBytes()); } catch (IOException e) { log().warn("getInputStream: Problem getting input stream: "+e, e); throw e; } catch (Throwable e) { String message = "Problem getting input stream: "+e; log().warn(message, e); throw new IOExceptionWithCause(message,e ); } return stream; } /** * Builds a Requisition based on the A records returned in a zone transfer from the * specified zone. * * @return an instance of the JaxB annotated Requistion class than can be marshaled * into the XML and streamed to the Provisioner * * @throws IOException * @throws ZoneTransferException */ private Requisition buildRequisitionFromZoneTransfer() throws IOException, ZoneTransferException { ZoneTransferIn xfer = null; List<Record> records = null; LogUtils.debugf(this, "connecting to host %s:%d", m_url.getHost(), m_port); try { xfer = ZoneTransferIn.newIXFR(new Name(m_zone), m_serial.longValue(), m_fallback.booleanValue(), m_url.getHost(), m_port, m_key); records = getRecords(xfer); } catch (ZoneTransferException e) // Fallbacking to AXFR { String message = "IXFR not supported trying AXFR: "+e; log().warn(message, e); xfer = ZoneTransferIn.newAXFR(new Name(m_zone), m_url.getHost(), m_key); records = getRecords(xfer); } Requisition r = null; if (records.size() > 0) { //for now, set the foreign source to the specified dns zone r = new Requisition(getForeignSource()); for (Record rec : records) { if (matchingRecord(rec)) { r.insertNode(createRequisitionNode(rec)); } } } return r; } @SuppressWarnings("unchecked") private List<Record> getRecords(ZoneTransferIn xfer) throws IOException, ZoneTransferException { return (List<Record>) xfer.run(); } /** * Creates an instance of the JaxB annotated RequisionNode class. * * @param rec * @return a populated RequisitionNode based on defaults and data from the * A record returned from a DNS zone transfer query. */ private RequisitionNode createRequisitionNode(Record rec) { ARecord arec = (ARecord)rec; String addr = StringUtils.stripStart(arec.getAddress().toString(), "/"); RequisitionNode n = new RequisitionNode(); String host = rec.getName().toString(); String nodeLabel = StringUtils.stripStart(host, "."); n.setBuilding(getForeignSource()); switch(m_foreignIdHashSource) { case 1: n.setForeignId(computeHashCode(nodeLabel)); log().debug("Generating foreignId from hash of nodelabel " + nodeLabel); break; case 2: n.setForeignId(computeHashCode(addr)); log().debug("Generating foreignId from hash of ipAddress " + addr); break; case 3: n.setForeignId(computeHashCode(nodeLabel+addr)); log().debug("Generating foreignId from hash of nodelabel+ipAddress " + nodeLabel + addr); break; default: n.setForeignId(computeHashCode(nodeLabel)); log().debug("Default case: Generating foreignId from hash of nodelabel " + nodeLabel); break; } n.setNodeLabel(nodeLabel); RequisitionInterface i = new RequisitionInterface(); i.setDescr("DNS-A"); i.setIpAddr(addr); i.setSnmpPrimary("P"); i.setManaged(Boolean.TRUE); i.setStatus(Integer.valueOf(1)); for (String service : m_services) { service = service.trim(); i.insertMonitoredService(new RequisitionMonitoredService(service)); log().debug("Adding provisioned service " + service); } n.putInterface(i); return n; } /** * Determines if the record is an A record and if the canonical name * matches the expression supplied in the URL, if one was supplied. * * @param rec * @return boolean if rec should be included in the import requisition */ private boolean matchingRecord(Record rec) { log().info("matchingRecord: checking rec: "+rec+" to see if it should be imported..."); boolean matches = false; if ("A".equals(Type.string(rec.getType()))) { log().debug("matchingRecord: record is a an A record, continuing..."); String expression = determineExpressionFromUrl(getUrl()); if (expression != null) { Pattern p = Pattern.compile(expression); Matcher m = p.matcher(rec.getName().toString()); // Try matching on host name only for backwards compatibility log().debug("matchingRecord: attempting to match hostname: ["+rec.getName().toString()+"] with expression: ["+expression+"]"); if (m.matches()) { matches = true; } else { // include the IP address and try again log().debug("matchingRecord: attempting to match record: ["+rec.getName().toString() +" "+rec.rdataToString()+"] with expression: ["+expression+"]"); m = p.matcher(rec.getName().toString() + " " + rec.rdataToString()); if (m.matches()) { matches = true; } } log().debug("matchingRecord: record matches expression: "+matches); } else { log().debug("matchingRecord: on expression for this zone, returning valid match for this A record..."); matches = true; } } log().info("matchingRecord: record: "+rec+" matches: "+matches); return matches; } /** * Created this in the case that we decide to every do something different with the hashing * to have a lesser likely hood of duplicate foreign ids * @param hashSource * @return */ private String computeHashCode(String hashSource) { String hash = String.valueOf(hashSource.hashCode()); return hash; } /** * Utility to marshal the Requisition class into XML. * * @param r * @return a String of XML encoding the Requisition class * * @throws JAXBException */ private String jaxBMarshal(Requisition r) throws JAXBException { return JaxbUtils.marshal(r); } /** * <p>getZone</p> * * @return a {@link java.lang.String} object. */ public String getZone() { return m_zone; } /** * <p>getSerial</p> * * @return a {@link java.lang.Long} object. */ public Long getSerial() { return m_serial; } /** * <p>setSerial</p> * * @param serial a {@link java.lang.Long} object. */ public void setSerial(Long serial) { m_serial = serial; } /** * <p>getFallback</p> * * @return a {@link java.lang.Boolean} object. */ public Boolean getFallback() { return m_fallback; } /** * <p>setFallback</p> * * @param fallback a {@link java.lang.Boolean} object. */ public void setFallback(Boolean fallback) { m_fallback = fallback; } /** * <p>getKey</p> * * @return a {@link org.xbill.DNS.TSIG} object. */ public TSIG getKey() { return m_key; } /** * <p>setKey</p> * * @param key a {@link org.xbill.DNS.TSIG} object. */ public void setKey(TSIG key) { m_key = key; } /** * <p>getDescription</p> * * @return a {@link java.lang.String} object. */ public String getDescription() { return m_url.toString(); } /** * <p>toString</p> * * @return a {@link java.lang.String} object. */ public String toString() { return getDescription(); } /** * <p>getUrl</p> * * @return a {@link java.net.URL} object. */ public URL getUrl() { return m_url; } public static Map<String, String> getArgs() { return m_args; } /** * <p>determineExpressionFromUrl</p> * * @param url a {@link java.net.URL} object. * @return a {@link java.lang.String} object. */ protected static String determineExpressionFromUrl(URL url) { log().info("determineExpressionFromUrl: finding regex as parameter in query string of URL: "+url); if(getUrlArgs(url) == null) { return null; } else { return getUrlArgs(url).get(EXPRESSION_ARG); } } private static List<String> tokenizeQueryArgs(String query) throws IllegalArgumentException { if (query == null) { throw new IllegalArgumentException("The URL query is null"); } List<String> queryArgs = Arrays.asList(StringUtils.split(query, QUERY_ARG_SEPARATOR)); return queryArgs; } /** * <p>decodeQueryString</p> * * @param url a {@link java.net.URL} object. * @return a {@link java.lang.String} object. */ protected static String decodeQueryString(URL url) { if (url == null || url.getQuery() == null) { throw new IllegalArgumentException("The URL or the URL query is null: "+url); } String query = null; try { query = URLDecoder.decode(url.getQuery(), "UTF-8"); } catch (UnsupportedEncodingException e) { log().error("decodeQueryString: "+e, e); } return query; } /** * Validate the format is: * dns://<host>/<zone>/?expression=<regex> * * there should be only one arguement in the path * there should only be one query parameter * * @param url a {@link java.net.URL} object. * @throws java.net.MalformedURLException if any. */ protected static void validateDnsUrl(URL url) throws MalformedURLException { String path = url.getPath(); path = StringUtils.removeStart(path, "/"); path = StringUtils.removeEnd(path, "/"); if (path == null || StringUtils.countMatches(path, "/") > 1) { throw new MalformedURLException("The specified DNS URL contains invalid path: "+url); } String query = url.getQuery(); if ((query != null) && (determineExpressionFromUrl(url) == null) && (getArgs().get(SERVICES_ARG) == null)) { throw new MalformedURLException("The specified DNS URL contains an invalid query string: "+url); } } /** * Zone should be the first path entity * * dns://<host>/<zone>[/<foreign source>][/<?expression=<regex>> * * @param url a {@link java.net.URL} object. * @return a {@link java.lang.String} object. */ protected static String parseZone(URL url) { String path = url.getPath(); path = StringUtils.removeStart(path, "/"); path = StringUtils.removeEnd(path, "/"); String zone = path; if (path != null && StringUtils.countMatches(path, "/") == 1) { String[] paths = path.split("/"); zone = paths[0]; } return zone; } /** * Foreign Source should be the second path entity, if it exists, otherwise it is * set to the value of the zone. * * dns://<host>/<zone>[/<foreign source>][/<?expression=<regex>> * * @param url a {@link java.net.URL} object. * @return a {@link java.lang.String} object. */ protected static String parseForeignSource(URL url) { String path = url.getPath(); path = StringUtils.removeStart(path, "/"); path = StringUtils.removeEnd(path, "/"); String foreignSource = path; if (path != null && StringUtils.countMatches(path, "/") == 1) { String[] paths = path.split("/"); foreignSource = paths[1]; } return foreignSource; } protected static Map<String, String> getUrlArgs(URL url) { if (url.getQuery() == null) { return null; } //TODO: need to throw exception if query is null String query = decodeQueryString(url); //TODO: need to handle exception List<String> queryArgs = tokenizeQueryArgs(query); Map<String, String> args = new HashMap<String, String>(); for (String queryArg : queryArgs) { String[] argTokens = StringUtils.split(queryArg, '='); if (argTokens.length < 2) { log().warn("getUrlArgs: syntax error in URL query string, missing '=' in query argument: "+queryArg); } else { log().debug("adding arg tokens " + argTokens[0].toLowerCase() + ", " + argTokens[1]); args.put(argTokens[0].toLowerCase(), argTokens[1]); } } return args; } private static ThreadCategory log() { return ThreadCategory.getInstance(DnsRequisitionUrlConnection.class); } /** * <p>setForeignSource</p> * * @param foreignSource a {@link java.lang.String} object. */ public void setForeignSource(String foreignSource) { m_foreignSource = foreignSource; } /** * <p>getForeignSource</p> * * @return a {@link java.lang.String} object. */ public String getForeignSource() { return m_foreignSource; } }
opennms-provision/opennms-provisiond/src/main/java/org/opennms/netmgt/provision/service/dns/DnsRequisitionUrlConnection.java
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2009-2011 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <[email protected]> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.provision.service.dns; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; 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 javax.xml.bind.JAXBException; import org.apache.commons.io.IOExceptionWithCause; import org.apache.commons.lang.StringUtils; import org.opennms.core.utils.LogUtils; import org.opennms.core.utils.ThreadCategory; import org.opennms.core.xml.JaxbUtils; import org.opennms.netmgt.provision.persist.requisition.Requisition; import org.opennms.netmgt.provision.persist.requisition.RequisitionInterface; import org.opennms.netmgt.provision.persist.requisition.RequisitionMonitoredService; import org.opennms.netmgt.provision.persist.requisition.RequisitionNode; import org.xbill.DNS.ARecord; import org.xbill.DNS.Name; import org.xbill.DNS.Record; import org.xbill.DNS.TSIG; import org.xbill.DNS.Type; import org.xbill.DNS.ZoneTransferException; import org.xbill.DNS.ZoneTransferIn; /** * Implementation of <code>java.net.URLConnection</code> for handling * URLs specified in the Provisiond configuration requesting an import * requisition based on the A records of a zone transfer for a DNS server. * * @author <a href="mailto:[email protected]">David Hustace</a> * @version $Id: $ */ public class DnsRequisitionUrlConnection extends URLConnection { private static final String EXPRESSION_ARG = "expression"; private static final String SERVICES_ARG = "services"; private static final String FID_HASH_SRC_ARG = "foreignidhashsource"; private static final String QUERY_ARG_SEPARATOR = "&"; /** Constant <code>URL_SCHEME="dns://"</code> */ public static final String URL_SCHEME = "dns://"; /** Constant <code>PROTOCOL="dns"</code> */ public static final String PROTOCOL = "dns"; private String m_zone; //TODO implement this private Long m_serial; //TODO implement this private Boolean m_fallback; //TODO implement this private TSIG m_key; private URL m_url; private int m_port; private String m_foreignSource; private String m_foreignIdHashSource; private String[] m_services; private static Map<String, String> m_args; /** * <p>Constructor for DnsRequisitionUrlConnection.</p> * * @param url a {@link java.net.URL} object. * @throws java.net.MalformedURLException if any. */ protected DnsRequisitionUrlConnection(URL url) throws MalformedURLException { super(url); m_args = getUrlArgs(url); validateDnsUrl(url); m_url = url; m_port = url.getPort() == -1 ? 53 : url.getPort(); m_zone = parseZone(url); m_foreignSource = parseForeignSource(url); m_foreignIdHashSource = getForeignIdHashSource(); m_services = getServices(); if (m_zone == null) { throw new IllegalArgumentException("Specified Zone is null"); } m_serial = Long.valueOf(0L); m_fallback = Boolean.FALSE; m_key = null; } /** * Determine services to be provisioned from URL * * @return a String[] of opennms service names */ private String[] getServices() { // TODO validate services against service table of database String[] services = "ICMP,SNMP".split(","); if (getArgs() != null && getArgs().get(SERVICES_ARG) != null) { services = getArgs().get(SERVICES_ARG).split(","); } return services; } /** * Determine source for computing hash for foreignId from URL * * @return a String of "ipAddress" or "nodeLabel" */ private String getForeignIdHashSource() { if (getArgs() != null && getArgs().get(FID_HASH_SRC_ARG) != null && "ipAddress".equalsIgnoreCase(getArgs().get(FID_HASH_SRC_ARG).trim())) { return "ipAddress"; } return "nodeLabel"; } /** * {@inheritDoc} * * This is a no op. */ @Override public void connect() throws IOException { } /** * {@inheritDoc} * * Creates a ByteArrayInputStream implementation of InputStream of the XML marshaled version * of the Requisition class. Calling close on this stream is safe. */ @Override public InputStream getInputStream() throws IOException { InputStream stream = null; try { Requisition r = buildRequisitionFromZoneTransfer(); stream = new ByteArrayInputStream(jaxBMarshal(r).getBytes()); } catch (IOException e) { log().warn("getInputStream: Problem getting input stream: "+e, e); throw e; } catch (Throwable e) { String message = "Problem getting input stream: "+e; log().warn(message, e); throw new IOExceptionWithCause(message,e ); } return stream; } /** * Builds a Requisition based on the A records returned in a zone transfer from the * specified zone. * * @return an instance of the JaxB annotated Requistion class than can be marshaled * into the XML and streamed to the Provisioner * * @throws IOException * @throws ZoneTransferException */ private Requisition buildRequisitionFromZoneTransfer() throws IOException, ZoneTransferException { ZoneTransferIn xfer = null; List<Record> records = null; LogUtils.debugf(this, "connecting to host %s:%d", m_url.getHost(), m_port); try { xfer = ZoneTransferIn.newIXFR(new Name(m_zone), m_serial.longValue(), m_fallback.booleanValue(), m_url.getHost(), m_port, m_key); records = getRecords(xfer); } catch (ZoneTransferException e) // Fallbacking to AXFR { String message = "IXFR not supported trying AXFR: "+e; log().warn(message, e); xfer = ZoneTransferIn.newAXFR(new Name(m_zone), m_url.getHost(), m_key); records = getRecords(xfer); } Requisition r = null; if (records.size() > 0) { //for now, set the foreign source to the specified dns zone r = new Requisition(getForeignSource()); for (Record rec : records) { if (matchingRecord(rec)) { r.insertNode(createRequisitionNode(rec)); } } } return r; } @SuppressWarnings("unchecked") private List<Record> getRecords(ZoneTransferIn xfer) throws IOException, ZoneTransferException { return (List<Record>) xfer.run(); } /** * Creates an instance of the JaxB annotated RequisionNode class. * * @param rec * @return a populated RequisitionNode based on defaults and data from the * A record returned from a DNS zone transfer query. */ private RequisitionNode createRequisitionNode(Record rec) { ARecord arec = (ARecord)rec; String addr = StringUtils.stripStart(arec.getAddress().toString(), "/"); RequisitionNode n = new RequisitionNode(); String host = rec.getName().toString(); String nodeLabel = StringUtils.stripStart(host, "."); n.setBuilding(getForeignSource()); if("ipAddress".equals(m_foreignIdHashSource)) { log().debug("Setting foreign ID from hash of IP Address" + addr); n.setForeignId(computeHashCode(addr)); } else { log().debug("Setting foreign ID from hash of node label" + nodeLabel); n.setForeignId(computeHashCode(nodeLabel)); } n.setNodeLabel(nodeLabel); RequisitionInterface i = new RequisitionInterface(); i.setDescr("DNS-A"); i.setIpAddr(addr); i.setSnmpPrimary("P"); i.setManaged(Boolean.TRUE); i.setStatus(Integer.valueOf(1)); for (String service : m_services) { service = service.trim(); i.insertMonitoredService(new RequisitionMonitoredService(service)); log().debug("Adding provisioned service " + service); } n.putInterface(i); return n; } /** * Determines if the record is an A record and if the canonical name * matches the expression supplied in the URL, if one was supplied. * * @param rec * @return boolean if rec should be included in the import requisition */ private boolean matchingRecord(Record rec) { log().info("matchingRecord: checking rec: "+rec+" to see if it should be imported..."); boolean matches = false; if ("A".equals(Type.string(rec.getType()))) { log().debug("matchingRecord: record is a an A record, continuing..."); String expression = determineExpressionFromUrl(getUrl()); if (expression != null) { Pattern p = Pattern.compile(expression); Matcher m = p.matcher(rec.getName().toString()); // Try matching on host name only for backwards compatibility log().debug("matchingRecord: attempting to match hostname: ["+rec.getName().toString()+"] with expression: ["+expression+"]"); if (m.matches()) { matches = true; } else { // include the IP address and try again log().debug("matchingRecord: attempting to match record: ["+rec.getName().toString() +" "+rec.rdataToString()+"] with expression: ["+expression+"]"); m = p.matcher(rec.getName().toString() + " " + rec.rdataToString()); if (m.matches()) { matches = true; } } log().debug("matchingRecord: record matches expression: "+matches); } else { log().debug("matchingRecord: on expression for this zone, returning valid match for this A record..."); matches = true; } } log().info("matchingRecord: record: "+rec+" matches: "+matches); return matches; } /** * Created this in the case that we decide to every do something different with the hashing * to have a lesser likely hood of duplicate foreign ids * @param hashSource * @return */ private String computeHashCode(String hashSource) { String hash = String.valueOf(hashSource.hashCode()); return hash; } /** * Utility to marshal the Requisition class into XML. * * @param r * @return a String of XML encoding the Requisition class * * @throws JAXBException */ private String jaxBMarshal(Requisition r) throws JAXBException { return JaxbUtils.marshal(r); } /** * <p>getZone</p> * * @return a {@link java.lang.String} object. */ public String getZone() { return m_zone; } /** * <p>getSerial</p> * * @return a {@link java.lang.Long} object. */ public Long getSerial() { return m_serial; } /** * <p>setSerial</p> * * @param serial a {@link java.lang.Long} object. */ public void setSerial(Long serial) { m_serial = serial; } /** * <p>getFallback</p> * * @return a {@link java.lang.Boolean} object. */ public Boolean getFallback() { return m_fallback; } /** * <p>setFallback</p> * * @param fallback a {@link java.lang.Boolean} object. */ public void setFallback(Boolean fallback) { m_fallback = fallback; } /** * <p>getKey</p> * * @return a {@link org.xbill.DNS.TSIG} object. */ public TSIG getKey() { return m_key; } /** * <p>setKey</p> * * @param key a {@link org.xbill.DNS.TSIG} object. */ public void setKey(TSIG key) { m_key = key; } /** * <p>getDescription</p> * * @return a {@link java.lang.String} object. */ public String getDescription() { return m_url.toString(); } /** * <p>toString</p> * * @return a {@link java.lang.String} object. */ public String toString() { return getDescription(); } /** * <p>getUrl</p> * * @return a {@link java.net.URL} object. */ public URL getUrl() { return m_url; } public static Map<String, String> getArgs() { return m_args; } /** * <p>determineExpressionFromUrl</p> * * @param url a {@link java.net.URL} object. * @return a {@link java.lang.String} object. */ protected static String determineExpressionFromUrl(URL url) { log().info("determineExpressionFromUrl: finding regex as parameter in query string of URL: "+url); if(getUrlArgs(url) == null) { return null; } else { return getUrlArgs(url).get(EXPRESSION_ARG); } } private static List<String> tokenizeQueryArgs(String query) throws IllegalArgumentException { if (query == null) { throw new IllegalArgumentException("The URL query is null"); } List<String> queryArgs = Arrays.asList(StringUtils.split(query, QUERY_ARG_SEPARATOR)); return queryArgs; } /** * <p>decodeQueryString</p> * * @param url a {@link java.net.URL} object. * @return a {@link java.lang.String} object. */ protected static String decodeQueryString(URL url) { if (url == null || url.getQuery() == null) { throw new IllegalArgumentException("The URL or the URL query is null: "+url); } String query = null; try { query = URLDecoder.decode(url.getQuery(), "UTF-8"); } catch (UnsupportedEncodingException e) { log().error("decodeQueryString: "+e, e); } return query; } /** * Validate the format is: * dns://<host>/<zone>/?expression=<regex> * * there should be only one arguement in the path * there should only be one query parameter * * @param url a {@link java.net.URL} object. * @throws java.net.MalformedURLException if any. */ protected static void validateDnsUrl(URL url) throws MalformedURLException { String path = url.getPath(); path = StringUtils.removeStart(path, "/"); path = StringUtils.removeEnd(path, "/"); if (path == null || StringUtils.countMatches(path, "/") > 1) { throw new MalformedURLException("The specified DNS URL contains invalid path: "+url); } String query = url.getQuery(); if ((query != null) && (determineExpressionFromUrl(url) == null) && (getArgs().get(SERVICES_ARG) == null)) { throw new MalformedURLException("The specified DNS URL contains an invalid query string: "+url); } } /** * Zone should be the first path entity * * dns://<host>/<zone>[/<foreign source>][/<?expression=<regex>> * * @param url a {@link java.net.URL} object. * @return a {@link java.lang.String} object. */ protected static String parseZone(URL url) { String path = url.getPath(); path = StringUtils.removeStart(path, "/"); path = StringUtils.removeEnd(path, "/"); String zone = path; if (path != null && StringUtils.countMatches(path, "/") == 1) { String[] paths = path.split("/"); zone = paths[0]; } return zone; } /** * Foreign Source should be the second path entity, if it exists, otherwise it is * set to the value of the zone. * * dns://<host>/<zone>[/<foreign source>][/<?expression=<regex>> * * @param url a {@link java.net.URL} object. * @return a {@link java.lang.String} object. */ protected static String parseForeignSource(URL url) { String path = url.getPath(); path = StringUtils.removeStart(path, "/"); path = StringUtils.removeEnd(path, "/"); String foreignSource = path; if (path != null && StringUtils.countMatches(path, "/") == 1) { String[] paths = path.split("/"); foreignSource = paths[1]; } return foreignSource; } protected static Map<String, String> getUrlArgs(URL url) { if (url.getQuery() == null) { return null; } //TODO: need to throw exception if query is null String query = decodeQueryString(url); //TODO: need to handle exception List<String> queryArgs = tokenizeQueryArgs(query); Map<String, String> args = new HashMap<String, String>(); for (String queryArg : queryArgs) { String[] argTokens = StringUtils.split(queryArg, '='); if (argTokens.length < 2) { log().warn("getUrlArgs: syntax error in URL query string, missing '=' in query argument: "+queryArg); } else { log().debug("adding arg tokens " + argTokens[0].toLowerCase() + ", " + argTokens[1]); args.put(argTokens[0].toLowerCase(), argTokens[1]); } } return args; } private static ThreadCategory log() { return ThreadCategory.getInstance(DnsRequisitionUrlConnection.class); } /** * <p>setForeignSource</p> * * @param foreignSource a {@link java.lang.String} object. */ public void setForeignSource(String foreignSource) { m_foreignSource = foreignSource; } /** * <p>getForeignSource</p> * * @return a {@link java.lang.String} object. */ public String getForeignSource() { return m_foreignSource; } }
NMS-4801 allow foreign ID to be hash of IP address in DNS provisioning - some add'l cleanup
opennms-provision/opennms-provisiond/src/main/java/org/opennms/netmgt/provision/service/dns/DnsRequisitionUrlConnection.java
NMS-4801 allow foreign ID to be hash of IP address in DNS provisioning - some add'l cleanup
Java
lgpl-2.1
47d39691c5bb3ab4398a4701b3cd757cdf8cfdf9
0
blue-systems-group/project.maybe.polyglot,xcv58/polyglot,liujed/polyglot-eclipse,xcv58/polyglot,xcv58/polyglot,liujed/polyglot-eclipse,liujed/polyglot-eclipse,blue-systems-group/project.maybe.polyglot,blue-systems-group/project.maybe.polyglot,blue-systems-group/project.maybe.polyglot,liujed/polyglot-eclipse,xcv58/polyglot
package polyglot.ast; import polyglot.types.ImportTable; import polyglot.frontend.Source; import java.util.List; /** * A <code>SourceFile</code> is an immutable representations of a Java * language source file. It consists of a package name, a list of * <code>Import</code>s, and a list of <code>GlobalDecl</code>s. */ public interface SourceFile extends Node { /** Get the source's declared package. */ PackageNode package_(); /** Set the source's declared package. */ SourceFile package_(PackageNode package_); /** Get the source's declared imports. * @return A list of {@link polyglot.ast.Import Import}. */ List imports(); /** Set the source's declared imports. * @param imports A list of {@link polyglot.ast.Import Import}. */ SourceFile imports(List imports); /** Get the source's top-level declarations. * @return A list of {@link polyglot.ast.TopLevelDecl TopLevelDecl}. */ List decls(); /** Set the source's top-level declarations. * @param decls A list of {@link polyglot.ast.TopLevelDecl TopLevelDecl}. */ SourceFile decls(List decls); /** Get the source's import table. */ ImportTable importTable(); /** Set the source's import table. */ SourceFile importTable(ImportTable importTable); /** Get the source file. */ Source source(); /** Set the source file. */ SourceFile source(Source source); }
src/polyglot/ast/SourceFile.java
package polyglot.ast; import polyglot.types.ImportTable; import polyglot.frontend.Source; import java.util.List; /** * A <code>SourceFile</code> is an immutable representations of a Java * langauge source file. It consists of a package name, a list of * <code>Import</code>s, and a list of <code>GlobalDecl</code>s. */ public interface SourceFile extends Node { /** Get the source's declared package. */ PackageNode package_(); /** Set the source's declared package. */ SourceFile package_(PackageNode package_); /** Get the source's declared imports. * @return A list of {@link polyglot.ast.Import Import}. */ List imports(); /** Set the source's declared imports. * @param imports A list of {@link polyglot.ast.Import Import}. */ SourceFile imports(List imports); /** Get the source's top-level declarations. * @return A list of {@link polyglot.ast.TopLevelDecl TopLevelDecl}. */ List decls(); /** Set the source's top-level declarations. * @param decls A list of {@link polyglot.ast.TopLevelDecl TopLevelDecl}. */ SourceFile decls(List decls); /** Get the source's import table. */ ImportTable importTable(); /** Set the source's import table. */ SourceFile importTable(ImportTable importTable); /** Get the source file. */ Source source(); /** Set the source file. */ SourceFile source(Source source); }
Fixed a typo.
src/polyglot/ast/SourceFile.java
Fixed a typo.
Java
lgpl-2.1
ad467fdbab3748d531cb256beedc2e2215e09401
0
google-code-export/flies,heather9911/flies,heather9911/flies,google-code-export/flies,google-code-export/flies,google-code-export/flies,heather9911/flies,heather9911/flies
/* * Copyright 2010, Red Hat, Inc. and individual contributors as indicated by the * @author tags. See the copyright.txt file in the distribution for a full * listing of individual contributors. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF * site: http://www.fsf.org. */ package net.openl10n.flies.action; import java.io.Serializable; import java.util.List; import net.openl10n.flies.common.LocaleId; import net.openl10n.flies.model.HAccount; import net.openl10n.flies.model.HLocale; import net.openl10n.flies.service.LanguageTeamService; import net.openl10n.flies.service.LocaleService; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.annotations.Transactional; import org.jboss.seam.core.Events; import org.jboss.seam.faces.FacesMessages; import org.jboss.seam.international.StatusMessage.Severity; import org.jboss.seam.log.Log; import org.jboss.seam.security.management.JpaIdentityStore; @Name("languageTeamAction") @Scope(ScopeType.PAGE) public class LanguageTeamAction implements Serializable { private static final long serialVersionUID = 1L; @In private LanguageTeamService languageTeamServiceImpl; @In private LocaleService localeServiceImpl; @In(required = false, value = JpaIdentityStore.AUTHENTICATED_USER) HAccount authenticatedAccount; @Logger Log log; @In private List<HLocale> memberLanguage; private String language; private HLocale locale; private boolean contained; public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public void initLocale() { contained = false; for (HLocale locale : this.memberLanguage) { if (locale.getLocaleId().getId().equals(language)) { contained = true; break; } } locale = localeServiceImpl.getSupportedLanguageByLocale(new LocaleId(language)); log.info("init language:" + locale.getLocaleId().getId()); log.info("init contained:" + contained); } public boolean getContained() { return contained; } public HLocale getLocale() { return locale; } @Transactional public void joinTribe() { log.debug("starting join tribe"); if (authenticatedAccount == null) { log.error("failed to load auth person"); return; } try { languageTeamServiceImpl.joinLanguageTeam(this.language, authenticatedAccount.getPerson().getId()); Events.instance().raiseEvent("personJoinedTribe"); log.info("{0} joined tribe {1}", authenticatedAccount.getUsername(), this.language); FacesMessages.instance().add("You are now a member of the {0} language team", this.locale.retrieveNativeName()); } catch (Exception e) { FacesMessages.instance().add(Severity.ERROR, e.getMessage()); } } @Transactional public void leaveTribe() { log.debug("starting leave tribe"); if (authenticatedAccount == null) { log.error("failed to load auth person"); return; } languageTeamServiceImpl.leaveLanguageTeam(this.language, authenticatedAccount.getPerson().getId()); Events.instance().raiseEvent("personLeftTribe"); log.info("{0} left tribe {1}", authenticatedAccount.getUsername(), this.language); FacesMessages.instance().add("You have left the {0} language team", this.locale.retrieveNativeName()); } }
flies-war/src/main/java/net/openl10n/flies/action/LanguageTeamAction.java
/* * Copyright 2010, Red Hat, Inc. and individual contributors as indicated by the * @author tags. See the copyright.txt file in the distribution for a full * listing of individual contributors. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF * site: http://www.fsf.org. */ package net.openl10n.flies.action; import java.io.Serializable; import java.util.List; import net.openl10n.flies.common.LocaleId; import net.openl10n.flies.model.HAccount; import net.openl10n.flies.model.HLocale; import net.openl10n.flies.service.LanguageTeamService; import net.openl10n.flies.service.LocaleService; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.annotations.Transactional; import org.jboss.seam.core.Events; import org.jboss.seam.faces.FacesMessages; import org.jboss.seam.international.StatusMessage.Severity; import org.jboss.seam.log.Log; import org.jboss.seam.security.management.JpaIdentityStore; @Name("languageTeamAction") @Scope(ScopeType.PAGE) public class LanguageTeamAction implements Serializable { private static final long serialVersionUID = 1L; @In private LanguageTeamService languageTeamServiceImpl; @In private LocaleService localeServiceImpl; @In(required = false, value = JpaIdentityStore.AUTHENTICATED_USER) HAccount authenticatedAccount; @Logger Log log; @In private List<HLocale> memberLanguage; private String language; private HLocale locale; private boolean contained; public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public void initLocale() { locale = localeServiceImpl.getSupportedLanguageByLocale(new LocaleId(language)); contained = this.memberLanguage.contains(locale); log.debug("init language:" + locale.getLocaleId().getId()); log.debug("init contained:" + contained); } public boolean getContained() { return contained; } public HLocale getLocale() { return locale; } @Transactional public void joinTribe() { log.debug("starting join tribe"); if (authenticatedAccount == null) { log.error("failed to load auth person"); return; } try { languageTeamServiceImpl.joinLanguageTeam(this.language, authenticatedAccount.getPerson().getId()); Events.instance().raiseEvent("personJoinedTribe"); log.info("{0} joined tribe {1}", authenticatedAccount.getUsername(), this.language); FacesMessages.instance().add("You are now a member of the {0} language team", this.locale.retrieveNativeName()); } catch (Exception e) { FacesMessages.instance().add(Severity.ERROR, e.getMessage()); } } @Transactional public void leaveTribe() { log.debug("starting leave tribe"); if (authenticatedAccount == null) { log.error("failed to load auth person"); return; } languageTeamServiceImpl.leaveLanguageTeam(this.language, authenticatedAccount.getPerson().getId()); Events.instance().raiseEvent("personLeftTribe"); log.info("{0} left tribe {1}", authenticatedAccount.getUsername(), this.language); FacesMessages.instance().add("You have left the {0} language team", this.locale.retrieveNativeName()); } }
Issue 9: "Leave this tribe" does not go away
flies-war/src/main/java/net/openl10n/flies/action/LanguageTeamAction.java
Issue 9: "Leave this tribe" does not go away
Java
apache-2.0
1d22657bb1279a42bbc18288503d9e21aa718c6b
0
BBreiden/finmath-lib,finmath/finmath-lib,finmath/finmath-lib,BBreiden/finmath-lib
/* * (c) Copyright Christian P. Fries, Germany. All rights reserved. Contact: [email protected]. * * Created on 12.07.2014 */ package net.finmath.optimizer; import java.util.ArrayList; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; /** * @author Christian Fries * */ public class LevenbergMarquardtTest { @Test public void testSmallLinearSystem() throws CloneNotSupportedException, SolverException { LevenbergMarquardt optimizer = new LevenbergMarquardt() { private static final long serialVersionUID = -6582160713209444489L; @Override public void setValues(double[] parameters, double[] values) { values[0] = parameters[0] * 0.0 + parameters[1]; values[1] = parameters[0] * 2.0 + parameters[1]; } }; // Set solver parameters optimizer.setInitialParameters(new double[] { 0, 0 }); optimizer.setWeights(new double[] { 1, 1 }); optimizer.setMaxIteration(100); optimizer.setTargetValues(new double[] { 5, 10 }); optimizer.run(); double[] bestParameters = optimizer.getBestFitParameters(); System.out.println("The solver for problem 1 required " + optimizer.getIterations() + " iterations. Accuracy is " + optimizer.getRootMeanSquaredError() + ". The best fit parameters are:"); for (int i = 0; i < bestParameters.length; i++) System.out.println("\tparameter[" + i + "]: " + bestParameters[i]); System.out.println(); Assert.assertTrue(Math.abs(bestParameters[0] - 2.5) < 1E-12); Assert.assertTrue(Math.abs(bestParameters[1] - 5.0) < 1E-12); /* * Creating a clone, continuing the search with new target values. * Note that we do not re-define the setValues method. */ OptimizerInterface optimizer2 = optimizer.getCloneWithModifiedTargetValues(new double[] { 5.1, 10.2 }, new double[] { 1, 1 }, true); optimizer2.run(); double[] bestParameters2 = optimizer2.getBestFitParameters(); System.out.println("The solver for problem 2 required " + optimizer2.getIterations() + " iterations. Accuracy is " + optimizer2.getRootMeanSquaredError() + ". The best fit parameters are:"); for (int i = 0; i < bestParameters2.length; i++) System.out.println("\tparameter[" + i + "]: " + bestParameters2[i]); System.out.println("________________________________________________________________________________"); System.out.println(); Assert.assertTrue(Math.abs(bestParameters2[0] - 2.55) < 1E-12); Assert.assertTrue(Math.abs(bestParameters2[1] - 5.10) < 1E-12); } @Test public void testMultiThreaddedOptimizer() throws SolverException { LevenbergMarquardt optimizer = new LevenbergMarquardt( new double[] { 0, 0, 0 }, // Initial parameters new double[] { 5, 10, 2 }, // Target values 100, // Max iterations 10 // Number of threads ) { private static final long serialVersionUID = -4656732051928259036L; // Override your objective function here @Override public void setValues(double[] parameters, double[] values) { values[0] = 1.0 * parameters[0] + 2.0 * parameters[1] + parameters[2] + parameters[0] * parameters[1]; values[1] = 2.0 * parameters[0] + 1.0 * parameters[1] + parameters[2] + parameters[1] * parameters[2]; values[2] = 3.0 * parameters[0] + 0.0 * parameters[1] + parameters[2]; } }; optimizer.run(); double[] bestParameters = optimizer.getBestFitParameters(); System.out.println("The solver for problem 3 required " + optimizer.getIterations() + " iterations. Accuracy is " + optimizer.getRootMeanSquaredError() + ". The best fit parameters are:"); for (int i = 0; i < bestParameters.length; i++) System.out.println("\tparameter[" + i + "]: " + bestParameters[i]); double[] values = new double[3]; optimizer.setValues(bestParameters, values); for (int i = 0; i < bestParameters.length; i++) System.out.println("\tvalue[" + i + "]: " + values[i]); System.out.println("________________________________________________________________________________"); System.out.println(); Assert.assertTrue(optimizer.getRootMeanSquaredError() < 1E-1); } @Test public void testRosenbrockFunction() throws SolverException { LevenbergMarquardt optimizer = new LevenbergMarquardt( new double[] { 0.5, 0.5 }, // Initial parameters new double[] { 0.0, 0.0 }, // Target values 100, // Max iterations 10 // Number of threads ) { private static final long serialVersionUID = 1636120150299382088L; // Override your objective function here @Override public void setValues(double[] parameters, double[] values) { values[0] = 10.0 * (parameters[1] - parameters[0]*parameters[0]); values[1] = 1.0 - parameters[0]; } }; optimizer.run(); double[] bestParameters = optimizer.getBestFitParameters(); System.out.println("The solver for problem 'Rosebrock' required " + optimizer.getIterations() + " iterations. Accuracy is " + optimizer.getRootMeanSquaredError() + ". The best fit parameters are:"); for (int i = 0; i < bestParameters.length; i++) System.out.println("\tparameter[" + i + "]: " + bestParameters[i]); double[] values = new double[2]; optimizer.setValues(bestParameters, values); for (int i = 0; i < values.length; i++) System.out.println("\tvalue[" + i + "]: " + values[i]); System.out.println("________________________________________________________________________________"); System.out.println(); Assert.assertTrue(Math.abs(bestParameters[0] - 1.0) < 1E-10); Assert.assertTrue(Math.abs(bestParameters[1] - 1.0) < 1E-10); } @Test public void testRosenbrockFunctionWithList() throws SolverException { ArrayList<Number> initialParams = new ArrayList<Number>(); initialParams.add(0.5); initialParams.add(0.5); ArrayList<Number> targetValues = new ArrayList<Number>(); targetValues.add(0.0); targetValues.add(0.0); LevenbergMarquardt optimizer = new LevenbergMarquardt( initialParams, // Initial parameters targetValues, // Target values 100, // Max iterations 10 // Number of threads ) { private static final long serialVersionUID = 5999706680609011046L; // Override your objective function here @Override public void setValues(double[] parameters, double[] values) { values[0] = 10.0 * (parameters[1] - parameters[0]*parameters[0]); values[1] = 1.0 - parameters[0]; } }; optimizer.run(); double[] bestParameters = optimizer.getBestFitParameters(); System.out.println("The solver for problem 'Rosebrock' required " + optimizer.getIterations() + " iterations. Accuracy is " + optimizer.getRootMeanSquaredError() + ". The best fit parameters are:"); for (int i = 0; i < bestParameters.length; i++) System.out.println("\tparameter[" + i + "]: " + bestParameters[i]); double[] values = new double[2]; optimizer.setValues(bestParameters, values); for (int i = 0; i < values.length; i++) System.out.println("\tvalue[" + i + "]: " + values[i]); System.out.println("________________________________________________________________________________"); System.out.println(); Assert.assertTrue(Math.abs(bestParameters[0] - 1.0) < 1E-10); Assert.assertTrue(Math.abs(bestParameters[1] - 1.0) < 1E-10); } /** * Optimization of booth function \( f(x,y) = \left(x+2y-7\right)^{2}+\left(2x+y-5\right)^{2} \). * The solution of \( f(x,y) = 0 \) is \( x=1 \), \( y=3 \). * * The test uses a finite difference approximation for the derivative. * * @throws SolverException */ @Test public void testBoothFunction() throws SolverException { final int numberOfParameters = 2; double[] initialParameters = new double[numberOfParameters]; double[] parameterSteps = new double[numberOfParameters]; Arrays.fill(initialParameters, 2.0); Arrays.fill(parameterSteps, 1E-8); double[] targetValues = new double[] { 0.0 }; int maxIteration = 1000; LevenbergMarquardt optimizer = new LevenbergMarquardt(initialParameters, targetValues, maxIteration, null) { private static final long serialVersionUID = -282626938650139518L; @Override public void setValues(double[] parameters, double[] values) { values[0] = Math.pow(parameters[0] + 2* parameters[1] - 7,2) + Math.pow(2 * parameters[0] + parameters[1] - 5,2); } }; optimizer.setParameterSteps(parameterSteps); // Set solver parameters optimizer.run(); double[] bestParameters = optimizer.getBestFitParameters(); System.out.println("The solver for Booth's function required " + optimizer.getIterations() + " iterations. The best fit parameters are:"); for (int i = 0; i < bestParameters.length; i++) System.out.println("\tparameter[" + i + "]: " + bestParameters[i]); System.out.println("The solver accuracy is " + optimizer.getRootMeanSquaredError()); System.out.println("________________________________________________________________________________"); System.out.println(); Assert.assertEquals(0.0, optimizer.getRootMeanSquaredError(), 2E-4); } /** * Optimization of booth function \( f(x,y) = \left(x+2y-7\right)^{2}+\left(2x+y-5\right)^{2} \). * The solution of \( f(x,y) = 0 \) is \( x=1 \), \( y=3 \). * * The test uses a a analytic calculation of derivative. * * @throws SolverException */ @Test public void testBoothFunctionWithAnalyticDerivative() throws SolverException { final int numberOfParameters = 2; double[] initialParameters = new double[numberOfParameters]; Arrays.fill(initialParameters, 2.0); double[] targetValues = new double[] { 0.0 }; int maxIteration = 1000; LevenbergMarquardt optimizer = new LevenbergMarquardt(initialParameters, targetValues, maxIteration, null) { private static final long serialVersionUID = -282626938650139518L; @Override public void setValues(double[] parameters, double[] values) { values[0] = Math.pow(parameters[0] + 2* parameters[1] - 7,2) + Math.pow(2 * parameters[0] + parameters[1] - 5,2); } @Override public void setDerivatives(double[] parameters, double[][] derivatives) { derivatives[0][0] = Math.pow(parameters[0] + 2 * parameters[1] - 7,1) * 2 + Math.pow(2 * parameters[0] + parameters[1] - 5,1) * 4; derivatives[1][0] = Math.pow(parameters[0] + 2 * parameters[1] - 7,1) * 4 + Math.pow(2 * parameters[0] + parameters[1] - 5,1) * 2; } }; // Set solver parameters optimizer.run(); double[] bestParameters = optimizer.getBestFitParameters(); System.out.println("The solver for Booth's function with analytic derivative required " + optimizer.getIterations() + " iterations. The best fit parameters are:"); for (int i = 0; i < bestParameters.length; i++) System.out.println("\tparameter[" + i + "]: " + bestParameters[i]); System.out.println("The solver accuracy is " + optimizer.getRootMeanSquaredError()); System.out.println("________________________________________________________________________________"); System.out.println(); Assert.assertEquals(0.0, optimizer.getRootMeanSquaredError(), 2E-4); } }
src/test/java6/net/finmath/optimizer/LevenbergMarquardtTest.java
/* * (c) Copyright Christian P. Fries, Germany. All rights reserved. Contact: [email protected]. * * Created on 12.07.2014 */ package net.finmath.optimizer; import java.util.ArrayList; import org.junit.Assert; import org.junit.Test; /** * @author Christian Fries * */ public class LevenbergMarquardtTest { @Test public void testSmallLinearSystem() throws CloneNotSupportedException, SolverException { LevenbergMarquardt optimizer = new LevenbergMarquardt() { private static final long serialVersionUID = -6582160713209444489L; @Override public void setValues(double[] parameters, double[] values) { values[0] = parameters[0] * 0.0 + parameters[1]; values[1] = parameters[0] * 2.0 + parameters[1]; } }; // Set solver parameters optimizer.setInitialParameters(new double[] { 0, 0 }); optimizer.setWeights(new double[] { 1, 1 }); optimizer.setMaxIteration(100); optimizer.setTargetValues(new double[] { 5, 10 }); optimizer.run(); double[] bestParameters = optimizer.getBestFitParameters(); System.out.println("The solver for problem 1 required " + optimizer.getIterations() + " iterations. Accuracy is " + optimizer.getRootMeanSquaredError() + ". The best fit parameters are:"); for (int i = 0; i < bestParameters.length; i++) System.out.println("\tparameter[" + i + "]: " + bestParameters[i]); System.out.println(); Assert.assertTrue(Math.abs(bestParameters[0] - 2.5) < 1E-12); Assert.assertTrue(Math.abs(bestParameters[1] - 5.0) < 1E-12); /* * Creating a clone, continuing the search with new target values. * Note that we do not re-define the setValues method. */ OptimizerInterface optimizer2 = optimizer.getCloneWithModifiedTargetValues(new double[] { 5.1, 10.2 }, new double[] { 1, 1 }, true); optimizer2.run(); double[] bestParameters2 = optimizer2.getBestFitParameters(); System.out.println("The solver for problem 2 required " + optimizer2.getIterations() + " iterations. Accuracy is " + optimizer2.getRootMeanSquaredError() + ". The best fit parameters are:"); for (int i = 0; i < bestParameters2.length; i++) System.out.println("\tparameter[" + i + "]: " + bestParameters2[i]); System.out.println("________________________________________________________________________________"); System.out.println(); Assert.assertTrue(Math.abs(bestParameters2[0] - 2.55) < 1E-12); Assert.assertTrue(Math.abs(bestParameters2[1] - 5.10) < 1E-12); } @Test public void testMultiThreaddedOptimizer() throws SolverException { LevenbergMarquardt optimizer = new LevenbergMarquardt( new double[] { 0, 0, 0 }, // Initial parameters new double[] { 5, 10, 2 }, // Target values 100, // Max iterations 10 // Number of threads ) { private static final long serialVersionUID = -4656732051928259036L; // Override your objective function here @Override public void setValues(double[] parameters, double[] values) { values[0] = 1.0 * parameters[0] + 2.0 * parameters[1] + parameters[2] + parameters[0] * parameters[1]; values[1] = 2.0 * parameters[0] + 1.0 * parameters[1] + parameters[2] + parameters[1] * parameters[2]; values[2] = 3.0 * parameters[0] + 0.0 * parameters[1] + parameters[2]; } }; optimizer.run(); double[] bestParameters = optimizer.getBestFitParameters(); System.out.println("The solver for problem 3 required " + optimizer.getIterations() + " iterations. Accuracy is " + optimizer.getRootMeanSquaredError() + ". The best fit parameters are:"); for (int i = 0; i < bestParameters.length; i++) System.out.println("\tparameter[" + i + "]: " + bestParameters[i]); double[] values = new double[3]; optimizer.setValues(bestParameters, values); for (int i = 0; i < bestParameters.length; i++) System.out.println("\tvalue[" + i + "]: " + values[i]); System.out.println("________________________________________________________________________________"); System.out.println(); Assert.assertTrue(optimizer.getRootMeanSquaredError() < 1E-1); } @Test public void testRosenbrockFunction() throws SolverException { LevenbergMarquardt optimizer = new LevenbergMarquardt( new double[] { 0.5, 0.5 }, // Initial parameters new double[] { 0.0, 0.0 }, // Target values 100, // Max iterations 10 // Number of threads ) { private static final long serialVersionUID = 1636120150299382088L; // Override your objective function here @Override public void setValues(double[] parameters, double[] values) { values[0] = 10.0 * (parameters[1] - parameters[0]*parameters[0]); values[1] = 1.0 - parameters[0]; } }; optimizer.run(); double[] bestParameters = optimizer.getBestFitParameters(); System.out.println("The solver for problem 'Rosebrock' required " + optimizer.getIterations() + " iterations. Accuracy is " + optimizer.getRootMeanSquaredError() + ". The best fit parameters are:"); for (int i = 0; i < bestParameters.length; i++) System.out.println("\tparameter[" + i + "]: " + bestParameters[i]); double[] values = new double[2]; optimizer.setValues(bestParameters, values); for (int i = 0; i < values.length; i++) System.out.println("\tvalue[" + i + "]: " + values[i]); System.out.println("________________________________________________________________________________"); System.out.println(); Assert.assertTrue(Math.abs(bestParameters[0] - 1.0) < 1E-10); Assert.assertTrue(Math.abs(bestParameters[1] - 1.0) < 1E-10); } @Test public void testRosenbrockFunctionWithList() throws SolverException { ArrayList<Number> initialParams = new ArrayList<Number>(); initialParams.add(0.5); initialParams.add(0.5); ArrayList<Number> targetValues = new ArrayList<Number>(); targetValues.add(0.0); targetValues.add(0.0); LevenbergMarquardt optimizer = new LevenbergMarquardt( initialParams, // Initial parameters targetValues, // Target values 100, // Max iterations 10 // Number of threads ) { private static final long serialVersionUID = 5999706680609011046L; // Override your objective function here @Override public void setValues(double[] parameters, double[] values) { values[0] = 10.0 * (parameters[1] - parameters[0]*parameters[0]); values[1] = 1.0 - parameters[0]; } }; optimizer.run(); double[] bestParameters = optimizer.getBestFitParameters(); System.out.println("The solver for problem 'Rosebrock' required " + optimizer.getIterations() + " iterations. Accuracy is " + optimizer.getRootMeanSquaredError() + ". The best fit parameters are:"); for (int i = 0; i < bestParameters.length; i++) System.out.println("\tparameter[" + i + "]: " + bestParameters[i]); double[] values = new double[2]; optimizer.setValues(bestParameters, values); for (int i = 0; i < values.length; i++) System.out.println("\tvalue[" + i + "]: " + values[i]); System.out.println("________________________________________________________________________________"); System.out.println(); Assert.assertTrue(Math.abs(bestParameters[0] - 1.0) < 1E-10); Assert.assertTrue(Math.abs(bestParameters[1] - 1.0) < 1E-10); } /** * Optimization of booth function \( f(x,y) = \left(x+2y-7\right)^{2}+\left(2x+y-5\right)^{2} \). * The solution of \( f(x,y) = 0 \) is \( x=1 \), \( y=3 \). * * The test uses a finite difference approximation for the derivative. * * @throws SolverException */ @Test public void testBoothFunction() throws SolverException { final int numberOfParameters = 2; double[] initialParameters = new double[numberOfParameters]; double[] parameterSteps = new double[numberOfParameters]; Arrays.fill(initialParameters, 2.0); Arrays.fill(parameterSteps, 1E-8); double[] targetValues = new double[] { 0.0 }; int maxIteration = 1000; LevenbergMarquardt optimizer = new LevenbergMarquardt(initialParameters, targetValues, maxIteration, null) { private static final long serialVersionUID = -282626938650139518L; @Override public void setValues(double[] parameters, double[] values) { values[0] = Math.pow(parameters[0] + 2* parameters[1] - 7,2) + Math.pow(2 * parameters[0] + parameters[1] - 5,2); } }; optimizer.setParameterSteps(parameterSteps); // Set solver parameters optimizer.run(); double[] bestParameters = optimizer.getBestFitParameters(); System.out.println("The solver for Booth's function required " + optimizer.getIterations() + " iterations. The best fit parameters are:"); for (int i = 0; i < bestParameters.length; i++) System.out.println("\tparameter[" + i + "]: " + bestParameters[i]); System.out.println("The solver accuracy is " + optimizer.getRootMeanSquaredError()); System.out.println("________________________________________________________________________________"); System.out.println(); Assert.assertEquals(0.0, optimizer.getRootMeanSquaredError(), 2E-4); } /** * Optimization of booth function \( f(x,y) = \left(x+2y-7\right)^{2}+\left(2x+y-5\right)^{2} \). * The solution of \( f(x,y) = 0 \) is \( x=1 \), \( y=3 \). * * The test uses a a analytic calculation of derivative. * * @throws SolverException */ @Test public void testBoothFunctionWithAnalyticDerivative() throws SolverException { final int numberOfParameters = 2; double[] initialParameters = new double[numberOfParameters]; Arrays.fill(initialParameters, 2.0); double[] targetValues = new double[] { 0.0 }; int maxIteration = 1000; LevenbergMarquardt optimizer = new LevenbergMarquardt(initialParameters, targetValues, maxIteration, null) { private static final long serialVersionUID = -282626938650139518L; @Override public void setValues(double[] parameters, double[] values) { values[0] = Math.pow(parameters[0] + 2* parameters[1] - 7,2) + Math.pow(2 * parameters[0] + parameters[1] - 5,2); } @Override public void setDerivatives(double[] parameters, double[][] derivatives) { derivatives[0][0] = Math.pow(parameters[0] + 2 * parameters[1] - 7,1) * 2 + Math.pow(2 * parameters[0] + parameters[1] - 5,1) * 4; derivatives[1][0] = Math.pow(parameters[0] + 2 * parameters[1] - 7,1) * 4 + Math.pow(2 * parameters[0] + parameters[1] - 5,1) * 2; } }; // Set solver parameters optimizer.run(); double[] bestParameters = optimizer.getBestFitParameters(); System.out.println("The solver for Booth's function with analytic derivative required " + optimizer.getIterations() + " iterations. The best fit parameters are:"); for (int i = 0; i < bestParameters.length; i++) System.out.println("\tparameter[" + i + "]: " + bestParameters[i]); System.out.println("The solver accuracy is " + optimizer.getRootMeanSquaredError()); System.out.println("________________________________________________________________________________"); System.out.println(); Assert.assertEquals(0.0, optimizer.getRootMeanSquaredError(), 2E-4); } }
Fixed imports.
src/test/java6/net/finmath/optimizer/LevenbergMarquardtTest.java
Fixed imports.
Java
apache-2.0
a88c20a1c5aaa56e5c51401c1d63f185b9ef06f4
0
Netflix/hollow,Netflix/hollow,Netflix/hollow
/* * * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.producer; import static com.netflix.hollow.api.consumer.HollowConsumer.AnnouncementWatcher.NO_ANNOUNCEMENT_AVAILABLE; import static java.lang.System.currentTimeMillis; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.metrics.HollowMetricsCollector; import com.netflix.hollow.api.metrics.HollowProducerMetrics; import com.netflix.hollow.api.producer.HollowProducer.Validator.ValidationException; import com.netflix.hollow.api.producer.HollowProducerListener.ProducerStatus; import com.netflix.hollow.api.producer.HollowProducerListener.PublishStatus; import com.netflix.hollow.api.producer.HollowProducerListener.RestoreStatus; import com.netflix.hollow.api.producer.enforcer.BasicSingleProducerEnforcer; import com.netflix.hollow.api.producer.enforcer.SingleProducerEnforcer; import com.netflix.hollow.api.producer.fs.HollowFilesystemBlobStager; import com.netflix.hollow.core.read.engine.HollowBlobHeaderReader; import com.netflix.hollow.core.read.engine.HollowBlobReader; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.core.util.HollowWriteStateCreator; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import com.netflix.hollow.tools.checksum.HollowChecksum; import com.netflix.hollow.tools.compact.HollowCompactor; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.Executor; import java.util.logging.Level; import java.util.logging.Logger; /** * * A HollowProducer is the top-level class used by producers of Hollow data to populate, publish, and announce data states. * The interactions between the "blob" store and announcement mechanism are defined by this class, and the implementations * of the data publishing and announcing are abstracted in interfaces which are provided to this class. * * To obtain a HollowProducer, you should use a builder pattern, for example: * * <pre> * {@code * * HollowProducer producer = HollowProducer.withPublisher(publisher) * .withAnnouncer(announcer) * .build(); * } * </pre> * * The following components are injectable, but only an implementation of the HollowProducer.Publisher is * required to be injected, all other components are optional. : * * <dl> * <dt>{@link HollowProducer.Publisher}</dt> * <dd>Implementations of this class define how to publish blob data to the blob store.</dd> * * <dt>{@link HollowProducer.Announcer}</dt> * <dd>Implementations of this class define the announcement mechanism, which is used to track the version of the * currently announced state.</dd> * * <dt>One or more {@link HollowProducer.Validator}</dt> * <dd>Implementations of this class allow for semantic validation of the data contained in a state prior to announcement. * If an Exception is thrown during validation, the state will not be announced, and the producer will be automatically * rolled back to the prior state.</dd> * * <dt>One or more {@link HollowProducerListener}</dt> * <dd>Listeners are notified about the progress and status of producer cycles throughout the various cycle stages.</dd> * * <dt>A Blob staging directory</dt> * <dd>Before blobs are published, they must be written and inspected/validated. A directory may be specified as a File to which * these "staged" blobs will be written prior to publish. Staged blobs will be cleaned up automatically after publish.</dd> * * <dt>{@link HollowProducer.BlobCompressor}</dt> * <dd>Implementations of this class intercept blob input/output streams to allow for compression in the blob store.</dd> * * <dt>{@link HollowProducer.BlobStager}</dt> * <dd>Implementations will define how to stage blobs, if the default behavior of staging blobs on local disk is not desirable. * If a {@link BlobStager} is provided, then neither a blob staging directory or {@link BlobCompressor} should be provided.</dd> * * <dt>An Executor for publishing snapshots</dt> * <dd>When consumers start up, if the latest announced version does not have a snapshot, they can load an earlier snapshot * and follow deltas to get up-to-date. A state can therefore be available and announced prior to the availability of * the snapshot. If an Executor is supplied here, then it will be used to publish snapshots. This can be useful if * snapshot publishing takes a long time -- subsequent cycles may proceed while snapshot uploads are still in progress.</dd> * * <dt>Number of cycles between snapshots</dt> * <dd>Because snapshots are not necessary for a data state to be announced, they need not be published every cycle. * If this parameter is specified, then a snapshot will be produced only every (n+1)th cycle.</dd> * * <dt>{@link HollowProducer.VersionMinter}</dt> * <dd>Allows for a custom version identifier minting strategy.</dd> * * <dt>Target max type shard size</dt> * <dd>Specify a target max type shard size. Defaults to 16MB. See http://hollow.how/advanced-topics/#type-sharding</dd> *</dl> * * @author Tim Taylor {@literal<[email protected]>} */ public class HollowProducer { private static final long DEFAULT_TARGET_MAX_TYPE_SHARD_SIZE = 16L * 1024L * 1024L; private final Logger log = Logger.getLogger(HollowProducer.class.getName()); private final BlobStager blobStager; private final Publisher publisher; private final List<Validator> validators; private final Announcer announcer; private final BlobStorageCleaner blobStorageCleaner; private HollowObjectMapper objectMapper; private final VersionMinter versionMinter; private final ListenerSupport listeners; private ReadStateHelper readStates; private final Executor snapshotPublishExecutor; private final int numStatesBetweenSnapshots; private int numStatesUntilNextSnapshot; private HollowProducerMetrics metrics; private HollowMetricsCollector<HollowProducerMetrics> metricsCollector; private final SingleProducerEnforcer singleProducerEnforcer; private long lastSucessfulCycle=0; private boolean isInitialized; public HollowProducer(Publisher publisher, Announcer announcer) { this(new HollowFilesystemBlobStager(), publisher, announcer, Collections.<Validator>emptyList(), Collections.<HollowProducerListener>emptyList(), new VersionMinterWithCounter(), null, 0, DEFAULT_TARGET_MAX_TYPE_SHARD_SIZE, null, new DummyBlobStorageCleaner(), new BasicSingleProducerEnforcer()); } public HollowProducer(Publisher publisher, Validator validator, Announcer announcer) { this(new HollowFilesystemBlobStager(), publisher, announcer, Collections.singletonList(validator), Collections.<HollowProducerListener>emptyList(), new VersionMinterWithCounter(), null, 0, DEFAULT_TARGET_MAX_TYPE_SHARD_SIZE, null, new DummyBlobStorageCleaner(), new BasicSingleProducerEnforcer()); } @Deprecated // TOBE cleaned up on Hollow 3 protected HollowProducer(BlobStager blobStager, Publisher publisher, Announcer announcer, List<Validator> validators, List<HollowProducerListener> listeners, VersionMinter versionMinter, Executor snapshotPublishExecutor, int numStatesBetweenSnapshots, long targetMaxTypeShardSize) { this(blobStager, publisher, announcer, validators, listeners, versionMinter, snapshotPublishExecutor, numStatesBetweenSnapshots, targetMaxTypeShardSize, null, new DummyBlobStorageCleaner(), new BasicSingleProducerEnforcer()); } @Deprecated // TOBE cleaned up on Hollow 3 protected HollowProducer(BlobStager blobStager, Publisher publisher, Announcer announcer, List<Validator> validators, List<HollowProducerListener> listeners, VersionMinter versionMinter, Executor snapshotPublishExecutor, int numStatesBetweenSnapshots, long targetMaxTypeShardSize, HollowMetricsCollector<HollowProducerMetrics> metricsCollector) { this(blobStager, publisher, announcer, validators, listeners, versionMinter, snapshotPublishExecutor, numStatesBetweenSnapshots, targetMaxTypeShardSize, metricsCollector, new DummyBlobStorageCleaner(), new BasicSingleProducerEnforcer()); } protected HollowProducer(BlobStager blobStager, Publisher publisher, Announcer announcer, List<Validator> validators, List<HollowProducerListener> listeners, VersionMinter versionMinter, Executor snapshotPublishExecutor, int numStatesBetweenSnapshots, long targetMaxTypeShardSize, HollowMetricsCollector<HollowProducerMetrics> metricsCollector, BlobStorageCleaner blobStorageCleaner, SingleProducerEnforcer singleProducerEnforcer) { this.publisher = publisher; this.validators = validators; this.announcer = announcer; this.versionMinter = versionMinter; this.blobStager = blobStager; this.singleProducerEnforcer = singleProducerEnforcer; this.snapshotPublishExecutor = snapshotPublishExecutor == null ? new Executor() { @Override public void execute(Runnable command) { command.run(); } } : snapshotPublishExecutor; this.numStatesBetweenSnapshots = numStatesBetweenSnapshots; HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); writeEngine.setTargetMaxTypeShardSize(targetMaxTypeShardSize); this.objectMapper = new HollowObjectMapper(writeEngine); this.listeners = new ListenerSupport(); this.readStates = ReadStateHelper.newDeltaChain(); this.blobStorageCleaner = blobStorageCleaner; for(HollowProducerListener listener : listeners) this.listeners.add(listener); this.metrics = new HollowProducerMetrics(); this.metricsCollector = metricsCollector; } /** * Returns the metrics for this producer */ public HollowProducerMetrics getMetrics() { return this.metrics; } public void initializeDataModel(Class<?>...classes) { long start = currentTimeMillis(); for(Class<?> c : classes) objectMapper.initializeTypeState(c); listeners.fireProducerInit(currentTimeMillis() - start); isInitialized = true; } public void initializeDataModel(HollowSchema... schemas) { long start = currentTimeMillis(); HollowWriteStateCreator.populateStateEngineWithTypeWriteStates(getWriteEngine(), Arrays.asList(schemas)); listeners.fireProducerInit(currentTimeMillis() - start); isInitialized = true; } public HollowProducer.ReadState restore(long versionDesired, HollowConsumer.BlobRetriever blobRetriever) { return restore(versionDesired, blobRetriever, new RestoreAction() { @Override public void restore(HollowReadStateEngine restoreFrom, HollowWriteStateEngine restoreTo) { restoreTo.restoreFrom(restoreFrom); } }); } HollowProducer.ReadState hardRestore(long versionDesired, HollowConsumer.BlobRetriever blobRetriever) { return restore(versionDesired, blobRetriever, new RestoreAction() { @Override public void restore(HollowReadStateEngine restoreFrom, HollowWriteStateEngine restoreTo) { HollowWriteStateCreator.populateUsingReadEngine(restoreTo, restoreFrom); } }); } private static interface RestoreAction { void restore(HollowReadStateEngine restoreFrom, HollowWriteStateEngine restoreTo); } private HollowProducer.ReadState restore(long versionDesired, HollowConsumer.BlobRetriever blobRetriever, RestoreAction restoreAction) { if(!isInitialized) throw new IllegalStateException("You must initialize the data model of a HollowProducer with producer.initializeDataModel(...) prior to restoring"); long start = currentTimeMillis(); RestoreStatus status = RestoreStatus.unknownFailure(); ReadState readState = null; try { listeners.fireProducerRestoreStart(versionDesired); if(versionDesired != Long.MIN_VALUE) { HollowConsumer client = HollowConsumer.withBlobRetriever(blobRetriever).build(); client.triggerRefreshTo(versionDesired); if(client.getCurrentVersionId() == versionDesired) { readState = ReadStateHelper.newReadState(client.getCurrentVersionId(), client.getStateEngine()); readStates = ReadStateHelper.restored(readState); // Need to restore data to new ObjectMapper since can't restore to non empty Write State Engine HollowObjectMapper newObjectMapper = createNewHollowObjectMapperFromExisting(objectMapper); restoreAction.restore(readStates.current().getStateEngine(), newObjectMapper.getStateEngine()); status = RestoreStatus.success(versionDesired, readState.getVersion()); objectMapper = newObjectMapper; // Restore completed successfully so swap } else { status = RestoreStatus.fail(versionDesired, client.getCurrentVersionId(), null); throw new IllegalStateException("Unable to reach requested version to restore from: " + versionDesired); } } } catch(Throwable th) { status = RestoreStatus.fail(versionDesired, readState != null ? readState.getVersion() : Long.MIN_VALUE, th); throw th; } finally { listeners.fireProducerRestoreComplete(status, currentTimeMillis() - start); } return readState; } private static HollowObjectMapper createNewHollowObjectMapperFromExisting(HollowObjectMapper objectMapper) { Collection<HollowSchema> schemas = objectMapper.getStateEngine().getSchemas(); HollowWriteStateEngine writeEngine = HollowWriteStateCreator.createWithSchemas(schemas); return new HollowObjectMapper(writeEngine); } protected HollowWriteStateEngine getWriteEngine() { return objectMapper.getStateEngine(); } protected HollowObjectMapper getObjectMapper() { return objectMapper; } /** * Each cycle produces a single data state. * * @return the version identifier of the produced state. */ public long runCycle(Populator task) { if(!singleProducerEnforcer.isPrimary()) { // TODO: minimum time spacing between cycles log.log(Level.INFO, "cycle not executed -- not primary"); return lastSucessfulCycle; } long toVersion = versionMinter.mint(); if(!readStates.hasCurrent()) listeners.fireNewDeltaChain(toVersion); ProducerStatus.Builder cycleStatus = listeners.fireCycleStart(toVersion); try { runCycle(task, cycleStatus, toVersion); } finally { listeners.fireCycleComplete(cycleStatus); metrics.updateCycleMetrics(cycleStatus.build()); if(metricsCollector !=null) metricsCollector.collect(metrics); } lastSucessfulCycle = toVersion; return toVersion; } /** * Run a compaction cycle, will produce a data state with exactly the same data as currently, but * reorganized so that ordinal holes are filled. This may need to be run multiple times to arrive * at an optimal state. * * @param config specifies what criteria to use to determine whether a compaction is necessary * @return the version identifier of the produced state, or AnnouncementWatcher.NO_ANNOUNCEMENT_AVAILABLE if compaction was unnecessary. */ public long runCompactionCycle(HollowCompactor.CompactionConfig config) { if(config != null && readStates.hasCurrent()) { final HollowCompactor compactor = new HollowCompactor(getWriteEngine(), readStates.current().getStateEngine(), config); if(compactor.needsCompaction()) { return runCycle(new Populator() { @Override public void populate(WriteState newState) throws Exception { compactor.compact(); } }); } } return NO_ANNOUNCEMENT_AVAILABLE; } protected void runCycle(Populator task, ProducerStatus.Builder cycleStatus, long toVersion) { // 1. Begin a new cycle Artifacts artifacts = new Artifacts(); HollowWriteStateEngine writeEngine = getWriteEngine(); try { // 1a. Prepare the write state writeEngine.prepareForNextCycle(); WriteState writeState = new WriteStateImpl(toVersion, objectMapper, readStates.current()); // 2. Populate the state ProducerStatus.Builder populateStatus = listeners.firePopulateStart(toVersion); try { task.populate(writeState); populateStatus.success(); } catch (Throwable th) { populateStatus.fail(th); throw th; } finally { listeners.firePopulateComplete(populateStatus); } // 3. Produce a new state if there's work to do if(writeEngine.hasChangedSinceLastCycle()) { // 3a. Publish, run checks & validation, then announce new state consumers publish(writeState, artifacts); ReadStateHelper candidate = readStates.roundtrip(writeState); cycleStatus.version(candidate.pending()); candidate = checkIntegrity(candidate, artifacts); try { validate(candidate.pending()); announce(candidate.pending()); readStates = candidate.commit(); cycleStatus.version(readStates.current()).success(); } catch(Throwable th) { if(artifacts.hasReverseDelta()) { applyDelta(artifacts.reverseDelta, candidate.pending().getStateEngine()); readStates = candidate.rollback(); } throw th; } } else { // 3b. Nothing to do; reset the effects of Step 2 writeEngine.resetToLastPrepareForNextCycle(); listeners.fireNoDelta(cycleStatus.success()); } } catch(Throwable th) { writeEngine.resetToLastPrepareForNextCycle(); cycleStatus.fail(th); if(th instanceof RuntimeException) throw (RuntimeException)th; throw new RuntimeException(th); } finally { artifacts.cleanup(); } } public void addListener(HollowProducerListener listener) { listeners.add(listener); } public void removeListener(HollowProducerListener listener) { listeners.remove(listener); } private void publish(final WriteState writeState, final Artifacts artifacts) throws IOException { ProducerStatus.Builder psb = listeners.firePublishStart(writeState.getVersion()); try { stageBlob(writeState, artifacts, Blob.Type.SNAPSHOT); if (readStates.hasCurrent()) { stageBlob(writeState, artifacts, Blob.Type.DELTA); stageBlob(writeState, artifacts, Blob.Type.REVERSE_DELTA); publishBlob(writeState, artifacts, Blob.Type.DELTA); publishBlob(writeState, artifacts, Blob.Type.REVERSE_DELTA); if(--numStatesUntilNextSnapshot < 0) { snapshotPublishExecutor.execute(new Runnable() { @Override public void run() { try { publishBlob(writeState, artifacts, Blob.Type.SNAPSHOT); artifacts.markSnapshotPublishComplete(); } catch(IOException e) { log.log(Level.WARNING, "Snapshot publish failed", e); } } }); numStatesUntilNextSnapshot = numStatesBetweenSnapshots; } else { artifacts.markSnapshotPublishComplete(); } } else { publishBlob(writeState, artifacts, Blob.Type.SNAPSHOT); artifacts.markSnapshotPublishComplete(); numStatesUntilNextSnapshot = numStatesBetweenSnapshots; } psb.success(); } catch (Throwable throwable) { psb.fail(throwable); throw throwable; } finally { listeners.firePublishComplete(psb); } } private void stageBlob(WriteState writeState, Artifacts artifacts, Blob.Type blobType) throws IOException { HollowBlobWriter writer = new HollowBlobWriter(getWriteEngine()); try { switch (blobType) { case SNAPSHOT: artifacts.snapshot = blobStager.openSnapshot(writeState.getVersion()); artifacts.snapshot.write(writer); break; case DELTA: artifacts.delta = blobStager.openDelta(readStates.current().getVersion(), writeState.getVersion()); artifacts.delta.write(writer); break; case REVERSE_DELTA: artifacts.reverseDelta = blobStager.openReverseDelta(writeState.getVersion(), readStates.current().getVersion()); artifacts.reverseDelta.write(writer); break; default: throw new IllegalStateException("unknown type, type=" + blobType); } } catch (Throwable th) { throw th; } } private void publishBlob(WriteState writeState, Artifacts artifacts, Blob.Type blobType) throws IOException { PublishStatus.Builder builder = (new PublishStatus.Builder()); try { switch (blobType) { case SNAPSHOT: builder.blob(artifacts.snapshot); publisher.publish(artifacts.snapshot); break; case DELTA: builder.blob(artifacts.delta); publisher.publish(artifacts.delta); break; case REVERSE_DELTA: builder.blob(artifacts.reverseDelta); publisher.publish(artifacts.reverseDelta); break; default: throw new IllegalStateException("unknown type, type=" + blobType); } builder.success(); } catch (Throwable th) { builder.fail(th); throw th; } finally { listeners.fireArtifactPublish(builder); metrics.updateBlobTypeMetrics(builder.build()); if(metricsCollector !=null) metricsCollector.collect(metrics); blobStorageCleaner.clean(blobType); } } /** * Given these read states * * * S(cur) at the currently announced version * * S(pnd) at the pending version * * Ensure that: * * S(cur).apply(forwardDelta).checksum == S(pnd).checksum * S(pnd).apply(reverseDelta).checksum == S(cur).checksum * * @param readStates * @return updated read states */ private ReadStateHelper checkIntegrity(ReadStateHelper readStates, Artifacts artifacts) throws Exception { ProducerStatus.Builder status = listeners.fireIntegrityCheckStart(readStates.pending()); try { ReadStateHelper result = readStates; HollowReadStateEngine current = readStates.hasCurrent() ? readStates.current().getStateEngine() : null; HollowReadStateEngine pending = readStates.pending().getStateEngine(); readSnapshot(artifacts.snapshot, pending); if(readStates.hasCurrent()) { log.info("CHECKSUMS"); HollowChecksum currentChecksum = HollowChecksum.forStateEngineWithCommonSchemas(current, pending); log.info(" CUR " + currentChecksum); HollowChecksum pendingChecksum = HollowChecksum.forStateEngineWithCommonSchemas(pending, current); log.info(" PND " + pendingChecksum); if(artifacts.hasDelta()) { if(!artifacts.hasReverseDelta()) throw new IllegalStateException("Both a delta and reverse delta are required"); // FIXME: timt: future cycles will fail unless both deltas validate applyDelta(artifacts.delta, current); HollowChecksum forwardChecksum = HollowChecksum.forStateEngineWithCommonSchemas(current, pending); //out.format(" CUR => PND %s\n", forwardChecksum); if(!forwardChecksum.equals(pendingChecksum)) throw new ChecksumValidationException(Blob.Type.DELTA); applyDelta(artifacts.reverseDelta, pending); HollowChecksum reverseChecksum = HollowChecksum.forStateEngineWithCommonSchemas(pending, current); //out.format(" CUR <= PND %s\n", reverseChecksum); if(!reverseChecksum.equals(currentChecksum)) throw new ChecksumValidationException(Blob.Type.REVERSE_DELTA); result = readStates.swap(); } } status.success(); return result; } catch(Throwable th) { status.fail(th); throw th; } finally { listeners.fireIntegrityCheckComplete(status); } } public static final class ChecksumValidationException extends IllegalStateException { private static final long serialVersionUID = -4399719849669674206L; ChecksumValidationException(Blob.Type type) { super(type.name() + " checksum invalid"); } } private void readSnapshot(Blob blob, HollowReadStateEngine stateEngine) throws IOException { InputStream is = blob.newInputStream(); try { new HollowBlobReader(stateEngine, new HollowBlobHeaderReader()).readSnapshot(is); } finally { is.close(); } } private void applyDelta(Blob blob, HollowReadStateEngine stateEngine) throws IOException { InputStream is = blob.newInputStream(); try { new HollowBlobReader(stateEngine, new HollowBlobHeaderReader()).applyDelta(is); } finally { is.close(); } } private void validate(HollowProducer.ReadState readState) { ProducerStatus.Builder status = listeners.fireValidationStart(readState); try { List<Throwable> validationFailures = new ArrayList<Throwable>(); for(Validator validator : validators) { try { validator.validate(readState); } catch(Throwable th) { validationFailures.add(th); } } if(!validationFailures.isEmpty()) { ValidationException ex = new ValidationException("Validation Failed", validationFailures.get(0)); ex.setIndividualFailures(validationFailures); throw ex; } status.success(); } catch (Throwable th) { status.fail(th); throw th; } finally { listeners.fireValidationComplete(status); } } private void announce(HollowProducer.ReadState readState) { if(announcer != null) { ProducerStatus.Builder status = listeners.fireAnnouncementStart(readState); try { announcer.announce(readState.getVersion()); status.success(); } catch(Throwable th) { status.fail(th); throw th; } finally { listeners.fireAnnouncementComplete(status); } } } public static interface VersionMinter { /** * Create a new state version.<p> * * State versions should be ascending -- later states have greater versions.<p> * * @return a new state version */ long mint(); } public static interface Populator { void populate(HollowProducer.WriteState newState) throws Exception; } public static interface WriteState { int add(Object o); HollowObjectMapper getObjectMapper(); HollowWriteStateEngine getStateEngine(); ReadState getPriorState(); long getVersion(); } public static interface ReadState { public long getVersion(); public HollowReadStateEngine getStateEngine(); } public static interface BlobStager { /** * Returns a blob with which a {@code HollowProducer} will write a snapshot for the version specified.<p> * * The producer will pass the returned blob back to this publisher when calling {@link Publisher#publish(Blob)}. * * @param version the blob version * * @return a {@link HollowProducer.Blob} representing a snapshot for the {@code version} */ public HollowProducer.Blob openSnapshot(long version); /** * Returns a blob with which a {@code HollowProducer} will write a forward delta from the version specified to * the version specified, i.e. {@code fromVersion => toVersion}.<p> * * The producer will pass the returned blob back to this publisher when calling {@link Publisher#publish(Blob)}. * * In the delta chain {@code fromVersion} is the older version such that {@code fromVersion < toVersion}. * * @param fromVersion the data state this delta will transition from * @param toVersion the data state this delta will transition to * * @return a {@link HollowProducer.Blob} representing a snapshot for the {@code version} */ public HollowProducer.Blob openDelta(long fromVersion, long toVersion); /** * Returns a blob with which a {@code HollowProducer} will write a reverse delta from the version specified to * the version specified, i.e. {@code fromVersion <= toVersion}.<p> * * The producer will pass the returned blob back to this publisher when calling {@link Publisher#publish(Blob)}. * * In the delta chain {@code fromVersion} is the older version such that {@code fromVersion < toVersion}. * * @param fromVersion version in the delta chain immediately after {@code toVersion} * @param toVersion version in the delta chain immediately before {@code fromVersion} * * @return a {@link HollowProducer.Blob} representing a snapshot for the {@code version} */ public HollowProducer.Blob openReverseDelta(long fromVersion, long toVersion); } public static interface BlobCompressor { public static final BlobCompressor NO_COMPRESSION = new BlobCompressor() { @Override public OutputStream compress(OutputStream os) { return os; } @Override public InputStream decompress(InputStream is) { return is; } }; /** * This method provides an opportunity to wrap the OutputStream used to write the blob (e.g. with a GZIPOutputStream). */ public OutputStream compress(OutputStream is); /** * This method provides an opportunity to wrap the InputStream used to write the blob (e.g. with a GZIPInputStream). */ public InputStream decompress(InputStream is); } public static interface Publisher { /** * Publish the blob specified to this publisher's blobstore.<p> * * It is guaranteed that {@code blob} was created by calling one of * {@link BlobStager#openSnapshot(long)}, {@link BlobStager#openDelta(long,long)}, or * {@link BlobStager#openReverseDelta(long,long)} on this publisher. * * @param blob the blob to publish */ public abstract void publish(HollowProducer.Blob blob); } public static abstract class Blob { protected final long fromVersion; protected final long toVersion; protected final Blob.Type type; protected Blob(long fromVersion, long toVersion, Blob.Type type) { this.fromVersion = fromVersion; this.toVersion = toVersion; this.type = type; } protected abstract void write(HollowBlobWriter writer) throws IOException; public abstract InputStream newInputStream() throws IOException; public abstract void cleanup(); public File getFile() { throw new UnsupportedOperationException("File is not available"); } public Type getType() { return this.type; } public long getFromVersion() { return this.fromVersion; } public long getToVersion() { return this.toVersion; } /** * Hollow blob types are {@code SNAPSHOT}, {@code DELTA} and {@code REVERSE_DELTA}. */ public static enum Type { SNAPSHOT("snapshot"), DELTA("delta"), REVERSE_DELTA("reversedelta"); public final String prefix; Type(String prefix) { this.prefix = prefix; } } } public static interface Validator { void validate(HollowProducer.ReadState readState); @SuppressWarnings("serial") public static class ValidationException extends RuntimeException { private List<Throwable> individualFailures; public ValidationException() { super(); } public ValidationException(String msg) { super(msg); } public ValidationException(String msg, Throwable cause) { super(msg, cause); } public void setIndividualFailures(List<Throwable> individualFailures) { this.individualFailures = individualFailures; } public List<Throwable> getIndividualFailures() { return individualFailures; } } } public static interface Announcer { public void announce(long stateVersion); } private static final class Artifacts { Blob snapshot = null; Blob delta = null; Blob reverseDelta = null; boolean cleanupCalled; boolean snapshotPublishComplete; synchronized void cleanup() { cleanupCalled = true; cleanupSnapshot(); if(delta != null) { delta.cleanup(); delta = null; } if(reverseDelta != null) { reverseDelta.cleanup(); reverseDelta = null; } } synchronized void markSnapshotPublishComplete() { snapshotPublishComplete = true; cleanupSnapshot(); } private void cleanupSnapshot() { if(cleanupCalled && snapshotPublishComplete && snapshot != null) { snapshot.cleanup(); snapshot = null; } } boolean hasDelta() { return delta != null; } public boolean hasReverseDelta() { return reverseDelta != null; } } public static HollowProducer.Builder withPublisher(HollowProducer.Publisher publisher) { Builder builder = new Builder(); return builder.withPublisher(publisher); } public static class Builder { protected BlobStager stager; protected BlobCompressor compressor; protected File stagingDir; protected Publisher publisher; protected Announcer announcer; protected List<Validator> validators = new ArrayList<Validator>(); protected List<HollowProducerListener> listeners = new ArrayList<HollowProducerListener>(); protected VersionMinter versionMinter = new VersionMinterWithCounter(); protected Executor snapshotPublishExecutor = null; protected int numStatesBetweenSnapshots = 0; protected long targetMaxTypeShardSize = DEFAULT_TARGET_MAX_TYPE_SHARD_SIZE; protected HollowMetricsCollector<HollowProducerMetrics> metricsCollector; protected BlobStorageCleaner blobStorageCleaner = new DummyBlobStorageCleaner(); protected SingleProducerEnforcer singleProducerEnforcer = new BasicSingleProducerEnforcer(); public Builder withBlobStager(HollowProducer.BlobStager stager) { this.stager = stager; return this; } public Builder withBlobCompressor(HollowProducer.BlobCompressor compressor) { this.compressor = compressor; return this; } public Builder withBlobStagingDir(File stagingDir) { this.stagingDir = stagingDir; return this; } public Builder withPublisher(HollowProducer.Publisher publisher) { this.publisher = publisher; return this; } public Builder withAnnouncer(HollowProducer.Announcer announcer) { this.announcer = announcer; return this; } public Builder withValidator(HollowProducer.Validator validator) { this.validators.add(validator); return this; } public Builder withValidators(HollowProducer.Validator... validators) { for(Validator validator : validators) this.validators.add(validator); return this; } public Builder withListener(HollowProducerListener listener) { this.listeners.add(listener); return this; } public Builder withListeners(HollowProducerListener... listeners) { for(HollowProducerListener listener : listeners) this.listeners.add(listener); return this; } public Builder withVersionMinter(HollowProducer.VersionMinter versionMinter) { this.versionMinter = versionMinter; return this; } public Builder withSnapshotPublishExecutor(Executor executor) { this.snapshotPublishExecutor = executor; return this; } public Builder withNumStatesBetweenSnapshots(int numStatesBetweenSnapshots) { this.numStatesBetweenSnapshots = numStatesBetweenSnapshots; return this; } public Builder withTargetMaxTypeShardSize(long targetMaxTypeShardSize) { this.targetMaxTypeShardSize = targetMaxTypeShardSize; return this; } public Builder withMetricsCollector(HollowMetricsCollector<HollowProducerMetrics> metricsCollector) { this.metricsCollector = metricsCollector; return this; } public Builder withBlobStorageCleaner(BlobStorageCleaner blobStorageCleaner) { this.blobStorageCleaner = blobStorageCleaner; return this; } public Builder withSingleProducerEnforcer(SingleProducerEnforcer singleProducerEnforcer) { this.singleProducerEnforcer = singleProducerEnforcer; return this; } protected void checkArguments() { if(stager != null && compressor != null) throw new IllegalArgumentException("Both a custom BlobStager and BlobCompressor were specified -- please specify only one of these."); if(stager != null && stagingDir != null) throw new IllegalArgumentException("Both a custom BlobStager and a staging directory were specified -- please specify only one of these."); if(this.stager == null) { BlobCompressor compressor = this.compressor != null ? this.compressor : BlobCompressor.NO_COMPRESSION; File stagingDir = this.stagingDir != null ? this.stagingDir : new File(System.getProperty("java.io.tmpdir")); this.stager = new HollowFilesystemBlobStager(stagingDir, compressor); } } public HollowProducer build() { checkArguments(); return new HollowProducer(stager, publisher, announcer, validators, listeners, versionMinter, snapshotPublishExecutor, numStatesBetweenSnapshots, targetMaxTypeShardSize, metricsCollector, blobStorageCleaner, singleProducerEnforcer); } } /** * Provides the opportunity to clean the blob storage. * It allows users to implement logic base on Blob Type. */ public static abstract class BlobStorageCleaner { public void clean(Blob.Type blobType) { switch(blobType) { case SNAPSHOT: cleanSnapshots(); break; case DELTA: cleanDeltas(); break; case REVERSE_DELTA: cleanReverseDeltas(); break; } } /** * This method provides an opportunity to remove old snapshots. */ public abstract void cleanSnapshots(); /** * This method provides an opportunity to remove old deltas. */ public abstract void cleanDeltas(); /** * This method provides an opportunity to remove old reverse deltas. */ public abstract void cleanReverseDeltas(); } /** * This Dummy blob storage cleaner does nothing */ private static class DummyBlobStorageCleaner extends HollowProducer.BlobStorageCleaner { @Override public void cleanSnapshots() { } @Override public void cleanDeltas() { } @Override public void cleanReverseDeltas() { } } }
hollow/src/main/java/com/netflix/hollow/api/producer/HollowProducer.java
/* * * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.producer; import static com.netflix.hollow.api.consumer.HollowConsumer.AnnouncementWatcher.NO_ANNOUNCEMENT_AVAILABLE; import static java.lang.System.currentTimeMillis; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.metrics.HollowMetricsCollector; import com.netflix.hollow.api.metrics.HollowProducerMetrics; import com.netflix.hollow.api.producer.HollowProducer.Validator.ValidationException; import com.netflix.hollow.api.producer.HollowProducerListener.ProducerStatus; import com.netflix.hollow.api.producer.HollowProducerListener.PublishStatus; import com.netflix.hollow.api.producer.HollowProducerListener.RestoreStatus; import com.netflix.hollow.api.producer.enforcer.BasicSingleProducerEnforcer; import com.netflix.hollow.api.producer.enforcer.SingleProducerEnforcer; import com.netflix.hollow.api.producer.fs.HollowFilesystemBlobStager; import com.netflix.hollow.core.read.engine.HollowBlobHeaderReader; import com.netflix.hollow.core.read.engine.HollowBlobReader; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.core.util.HollowWriteStateCreator; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import com.netflix.hollow.tools.checksum.HollowChecksum; import com.netflix.hollow.tools.compact.HollowCompactor; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.Executor; import java.util.logging.Level; import java.util.logging.Logger; /** * * A HollowProducer is the top-level class used by producers of Hollow data to populate, publish, and announce data states. * The interactions between the "blob" store and announcement mechanism are defined by this class, and the implementations * of the data publishing and announcing are abstracted in interfaces which are provided to this class. * * To obtain a HollowProducer, you should use a builder pattern, for example: * * <pre> * {@code * * HollowProducer producer = HollowProducer.withPublisher(publisher) * .withAnnouncer(announcer) * .build(); * } * </pre> * * The following components are injectable, but only an implementation of the HollowProducer.Publisher is * required to be injected, all other components are optional. : * * <dl> * <dt>{@link HollowProducer.Publisher}</dt> * <dd>Implementations of this class define how to publish blob data to the blob store.</dd> * * <dt>{@link HollowProducer.Announcer}</dt> * <dd>Implementations of this class define the announcement mechanism, which is used to track the version of the * currently announced state.</dd> * * <dt>One or more {@link HollowProducer.Validator}</dt> * <dd>Implementations of this class allow for semantic validation of the data contained in a state prior to announcement. * If an Exception is thrown during validation, the state will not be announced, and the producer will be automatically * rolled back to the prior state.</dd> * * <dt>One or more {@link HollowProducerListener}</dt> * <dd>Listeners are notified about the progress and status of producer cycles throughout the various cycle stages.</dd> * * <dt>A Blob staging directory</dt> * <dd>Before blobs are published, they must be written and inspected/validated. A directory may be specified as a File to which * these "staged" blobs will be written prior to publish. Staged blobs will be cleaned up automatically after publish.</dd> * * <dt>{@link HollowProducer.BlobCompressor}</dt> * <dd>Implementations of this class intercept blob input/output streams to allow for compression in the blob store.</dd> * * <dt>{@link HollowProducer.BlobStager}</dt> * <dd>Implementations will define how to stage blobs, if the default behavior of staging blobs on local disk is not desirable. * If a {@link BlobStager} is provided, then neither a blob staging directory or {@link BlobCompressor} should be provided.</dd> * * <dt>An Executor for publishing snapshots</dt> * <dd>When consumers start up, if the latest announced version does not have a snapshot, they can load an earlier snapshot * and follow deltas to get up-to-date. A state can therefore be available and announced prior to the availability of * the snapshot. If an Executor is supplied here, then it will be used to publish snapshots. This can be useful if * snapshot publishing takes a long time -- subsequent cycles may proceed while snapshot uploads are still in progress.</dd> * * <dt>Number of cycles between snapshots</dt> * <dd>Because snapshots are not necessary for a data state to be announced, they need not be published every cycle. * If this parameter is specified, then a snapshot will be produced only every (n+1)th cycle.</dd> * * <dt>{@link HollowProducer.VersionMinter}</dt> * <dd>Allows for a custom version identifier minting strategy.</dd> * * <dt>Target max type shard size</dt> * <dd>Specify a target max type shard size. Defaults to 16MB. See http://hollow.how/advanced-topics/#type-sharding</dd> *</dl> * * @author Tim Taylor {@literal<[email protected]>} */ public class HollowProducer { private static final long DEFAULT_TARGET_MAX_TYPE_SHARD_SIZE = 16L * 1024L * 1024L; private final Logger log = Logger.getLogger(HollowProducer.class.getName()); private final BlobStager blobStager; private final Publisher publisher; private final List<Validator> validators; private final Announcer announcer; private final BlobStorageCleaner blobStorageCleaner; private HollowObjectMapper objectMapper; private final VersionMinter versionMinter; private final ListenerSupport listeners; private ReadStateHelper readStates; private final Executor snapshotPublishExecutor; private final int numStatesBetweenSnapshots; private int numStatesUntilNextSnapshot; private HollowProducerMetrics metrics; private HollowMetricsCollector<HollowProducerMetrics> metricsCollector; private final SingleProducerEnforcer singleProducerEnforcer; private long lastSucessfulCycle=0; private boolean isInitialized; public HollowProducer(Publisher publisher, Announcer announcer) { this(new HollowFilesystemBlobStager(), publisher, announcer, Collections.<Validator>emptyList(), Collections.<HollowProducerListener>emptyList(), new VersionMinterWithCounter(), null, 0, DEFAULT_TARGET_MAX_TYPE_SHARD_SIZE, null, new DummyBlobStorageCleaner(), new BasicSingleProducerEnforcer()); } public HollowProducer(Publisher publisher, Validator validator, Announcer announcer) { this(new HollowFilesystemBlobStager(), publisher, announcer, Collections.singletonList(validator), Collections.<HollowProducerListener>emptyList(), new VersionMinterWithCounter(), null, 0, DEFAULT_TARGET_MAX_TYPE_SHARD_SIZE, null, new DummyBlobStorageCleaner(), new BasicSingleProducerEnforcer()); } protected HollowProducer(BlobStager blobStager, Publisher publisher, Announcer announcer, List<Validator> validators, List<HollowProducerListener> listeners, VersionMinter versionMinter, Executor snapshotPublishExecutor, int numStatesBetweenSnapshots, long targetMaxTypeShardSize, HollowMetricsCollector<HollowProducerMetrics> metricsCollector) { this(blobStager, publisher, announcer, validators, listeners, versionMinter, snapshotPublishExecutor, numStatesBetweenSnapshots, targetMaxTypeShardSize, metricsCollector, new DummyBlobStorageCleaner(), new BasicSingleProducerEnforcer()); } protected HollowProducer(BlobStager blobStager, Publisher publisher, Announcer announcer, List<Validator> validators, List<HollowProducerListener> listeners, VersionMinter versionMinter, Executor snapshotPublishExecutor, int numStatesBetweenSnapshots, long targetMaxTypeShardSize, HollowMetricsCollector<HollowProducerMetrics> metricsCollector, BlobStorageCleaner blobStorageCleaner, SingleProducerEnforcer singleProducerEnforcer) { this.publisher = publisher; this.validators = validators; this.announcer = announcer; this.versionMinter = versionMinter; this.blobStager = blobStager; this.singleProducerEnforcer = singleProducerEnforcer; this.snapshotPublishExecutor = snapshotPublishExecutor == null ? new Executor() { @Override public void execute(Runnable command) { command.run(); } } : snapshotPublishExecutor; this.numStatesBetweenSnapshots = numStatesBetweenSnapshots; HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); writeEngine.setTargetMaxTypeShardSize(targetMaxTypeShardSize); this.objectMapper = new HollowObjectMapper(writeEngine); this.listeners = new ListenerSupport(); this.readStates = ReadStateHelper.newDeltaChain(); this.blobStorageCleaner = blobStorageCleaner; for(HollowProducerListener listener : listeners) this.listeners.add(listener); this.metrics = new HollowProducerMetrics(); this.metricsCollector = metricsCollector; } /** * Returns the metrics for this producer */ public HollowProducerMetrics getMetrics() { return this.metrics; } public void initializeDataModel(Class<?>...classes) { long start = currentTimeMillis(); for(Class<?> c : classes) objectMapper.initializeTypeState(c); listeners.fireProducerInit(currentTimeMillis() - start); isInitialized = true; } public void initializeDataModel(HollowSchema... schemas) { long start = currentTimeMillis(); HollowWriteStateCreator.populateStateEngineWithTypeWriteStates(getWriteEngine(), Arrays.asList(schemas)); listeners.fireProducerInit(currentTimeMillis() - start); isInitialized = true; } public HollowProducer.ReadState restore(long versionDesired, HollowConsumer.BlobRetriever blobRetriever) { return restore(versionDesired, blobRetriever, new RestoreAction() { @Override public void restore(HollowReadStateEngine restoreFrom, HollowWriteStateEngine restoreTo) { restoreTo.restoreFrom(restoreFrom); } }); } HollowProducer.ReadState hardRestore(long versionDesired, HollowConsumer.BlobRetriever blobRetriever) { return restore(versionDesired, blobRetriever, new RestoreAction() { @Override public void restore(HollowReadStateEngine restoreFrom, HollowWriteStateEngine restoreTo) { HollowWriteStateCreator.populateUsingReadEngine(restoreTo, restoreFrom); } }); } private static interface RestoreAction { void restore(HollowReadStateEngine restoreFrom, HollowWriteStateEngine restoreTo); } private HollowProducer.ReadState restore(long versionDesired, HollowConsumer.BlobRetriever blobRetriever, RestoreAction restoreAction) { if(!isInitialized) throw new IllegalStateException("You must initialize the data model of a HollowProducer with producer.initializeDataModel(...) prior to restoring"); long start = currentTimeMillis(); RestoreStatus status = RestoreStatus.unknownFailure(); ReadState readState = null; try { listeners.fireProducerRestoreStart(versionDesired); if(versionDesired != Long.MIN_VALUE) { HollowConsumer client = HollowConsumer.withBlobRetriever(blobRetriever).build(); client.triggerRefreshTo(versionDesired); if(client.getCurrentVersionId() == versionDesired) { readState = ReadStateHelper.newReadState(client.getCurrentVersionId(), client.getStateEngine()); readStates = ReadStateHelper.restored(readState); // Need to restore data to new ObjectMapper since can't restore to non empty Write State Engine HollowObjectMapper newObjectMapper = createNewHollowObjectMapperFromExisting(objectMapper); restoreAction.restore(readStates.current().getStateEngine(), newObjectMapper.getStateEngine()); status = RestoreStatus.success(versionDesired, readState.getVersion()); objectMapper = newObjectMapper; // Restore completed successfully so swap } else { status = RestoreStatus.fail(versionDesired, client.getCurrentVersionId(), null); throw new IllegalStateException("Unable to reach requested version to restore from: " + versionDesired); } } } catch(Throwable th) { status = RestoreStatus.fail(versionDesired, readState != null ? readState.getVersion() : Long.MIN_VALUE, th); throw th; } finally { listeners.fireProducerRestoreComplete(status, currentTimeMillis() - start); } return readState; } private static HollowObjectMapper createNewHollowObjectMapperFromExisting(HollowObjectMapper objectMapper) { Collection<HollowSchema> schemas = objectMapper.getStateEngine().getSchemas(); HollowWriteStateEngine writeEngine = HollowWriteStateCreator.createWithSchemas(schemas); return new HollowObjectMapper(writeEngine); } protected HollowWriteStateEngine getWriteEngine() { return objectMapper.getStateEngine(); } protected HollowObjectMapper getObjectMapper() { return objectMapper; } /** * Each cycle produces a single data state. * * @return the version identifier of the produced state. */ public long runCycle(Populator task) { if(!singleProducerEnforcer.isPrimary()) { // TODO: minimum time spacing between cycles log.log(Level.INFO, "cycle not executed -- not primary"); return lastSucessfulCycle; } long toVersion = versionMinter.mint(); if(!readStates.hasCurrent()) listeners.fireNewDeltaChain(toVersion); ProducerStatus.Builder cycleStatus = listeners.fireCycleStart(toVersion); try { runCycle(task, cycleStatus, toVersion); } finally { listeners.fireCycleComplete(cycleStatus); metrics.updateCycleMetrics(cycleStatus.build()); if(metricsCollector !=null) metricsCollector.collect(metrics); } lastSucessfulCycle = toVersion; return toVersion; } /** * Run a compaction cycle, will produce a data state with exactly the same data as currently, but * reorganized so that ordinal holes are filled. This may need to be run multiple times to arrive * at an optimal state. * * @param config specifies what criteria to use to determine whether a compaction is necessary * @return the version identifier of the produced state, or AnnouncementWatcher.NO_ANNOUNCEMENT_AVAILABLE if compaction was unnecessary. */ public long runCompactionCycle(HollowCompactor.CompactionConfig config) { if(config != null && readStates.hasCurrent()) { final HollowCompactor compactor = new HollowCompactor(getWriteEngine(), readStates.current().getStateEngine(), config); if(compactor.needsCompaction()) { return runCycle(new Populator() { @Override public void populate(WriteState newState) throws Exception { compactor.compact(); } }); } } return NO_ANNOUNCEMENT_AVAILABLE; } protected void runCycle(Populator task, ProducerStatus.Builder cycleStatus, long toVersion) { // 1. Begin a new cycle Artifacts artifacts = new Artifacts(); HollowWriteStateEngine writeEngine = getWriteEngine(); try { // 1a. Prepare the write state writeEngine.prepareForNextCycle(); WriteState writeState = new WriteStateImpl(toVersion, objectMapper, readStates.current()); // 2. Populate the state ProducerStatus.Builder populateStatus = listeners.firePopulateStart(toVersion); try { task.populate(writeState); populateStatus.success(); } catch (Throwable th) { populateStatus.fail(th); throw th; } finally { listeners.firePopulateComplete(populateStatus); } // 3. Produce a new state if there's work to do if(writeEngine.hasChangedSinceLastCycle()) { // 3a. Publish, run checks & validation, then announce new state consumers publish(writeState, artifacts); ReadStateHelper candidate = readStates.roundtrip(writeState); cycleStatus.version(candidate.pending()); candidate = checkIntegrity(candidate, artifacts); try { validate(candidate.pending()); announce(candidate.pending()); readStates = candidate.commit(); cycleStatus.version(readStates.current()).success(); } catch(Throwable th) { if(artifacts.hasReverseDelta()) { applyDelta(artifacts.reverseDelta, candidate.pending().getStateEngine()); readStates = candidate.rollback(); } throw th; } } else { // 3b. Nothing to do; reset the effects of Step 2 writeEngine.resetToLastPrepareForNextCycle(); listeners.fireNoDelta(cycleStatus.success()); } } catch(Throwable th) { writeEngine.resetToLastPrepareForNextCycle(); cycleStatus.fail(th); if(th instanceof RuntimeException) throw (RuntimeException)th; throw new RuntimeException(th); } finally { artifacts.cleanup(); } } public void addListener(HollowProducerListener listener) { listeners.add(listener); } public void removeListener(HollowProducerListener listener) { listeners.remove(listener); } private void publish(final WriteState writeState, final Artifacts artifacts) throws IOException { ProducerStatus.Builder psb = listeners.firePublishStart(writeState.getVersion()); try { stageBlob(writeState, artifacts, Blob.Type.SNAPSHOT); if (readStates.hasCurrent()) { stageBlob(writeState, artifacts, Blob.Type.DELTA); stageBlob(writeState, artifacts, Blob.Type.REVERSE_DELTA); publishBlob(writeState, artifacts, Blob.Type.DELTA); publishBlob(writeState, artifacts, Blob.Type.REVERSE_DELTA); if(--numStatesUntilNextSnapshot < 0) { snapshotPublishExecutor.execute(new Runnable() { @Override public void run() { try { publishBlob(writeState, artifacts, Blob.Type.SNAPSHOT); artifacts.markSnapshotPublishComplete(); } catch(IOException e) { log.log(Level.WARNING, "Snapshot publish failed", e); } } }); numStatesUntilNextSnapshot = numStatesBetweenSnapshots; } else { artifacts.markSnapshotPublishComplete(); } } else { publishBlob(writeState, artifacts, Blob.Type.SNAPSHOT); artifacts.markSnapshotPublishComplete(); numStatesUntilNextSnapshot = numStatesBetweenSnapshots; } psb.success(); } catch (Throwable throwable) { psb.fail(throwable); throw throwable; } finally { listeners.firePublishComplete(psb); } } private void stageBlob(WriteState writeState, Artifacts artifacts, Blob.Type blobType) throws IOException { HollowBlobWriter writer = new HollowBlobWriter(getWriteEngine()); try { switch (blobType) { case SNAPSHOT: artifacts.snapshot = blobStager.openSnapshot(writeState.getVersion()); artifacts.snapshot.write(writer); break; case DELTA: artifacts.delta = blobStager.openDelta(readStates.current().getVersion(), writeState.getVersion()); artifacts.delta.write(writer); break; case REVERSE_DELTA: artifacts.reverseDelta = blobStager.openReverseDelta(writeState.getVersion(), readStates.current().getVersion()); artifacts.reverseDelta.write(writer); break; default: throw new IllegalStateException("unknown type, type=" + blobType); } } catch (Throwable th) { throw th; } } private void publishBlob(WriteState writeState, Artifacts artifacts, Blob.Type blobType) throws IOException { PublishStatus.Builder builder = (new PublishStatus.Builder()); try { switch (blobType) { case SNAPSHOT: builder.blob(artifacts.snapshot); publisher.publish(artifacts.snapshot); break; case DELTA: builder.blob(artifacts.delta); publisher.publish(artifacts.delta); break; case REVERSE_DELTA: builder.blob(artifacts.reverseDelta); publisher.publish(artifacts.reverseDelta); break; default: throw new IllegalStateException("unknown type, type=" + blobType); } builder.success(); } catch (Throwable th) { builder.fail(th); throw th; } finally { listeners.fireArtifactPublish(builder); metrics.updateBlobTypeMetrics(builder.build()); if(metricsCollector !=null) metricsCollector.collect(metrics); blobStorageCleaner.clean(blobType); } } /** * Given these read states * * * S(cur) at the currently announced version * * S(pnd) at the pending version * * Ensure that: * * S(cur).apply(forwardDelta).checksum == S(pnd).checksum * S(pnd).apply(reverseDelta).checksum == S(cur).checksum * * @param readStates * @return updated read states */ private ReadStateHelper checkIntegrity(ReadStateHelper readStates, Artifacts artifacts) throws Exception { ProducerStatus.Builder status = listeners.fireIntegrityCheckStart(readStates.pending()); try { ReadStateHelper result = readStates; HollowReadStateEngine current = readStates.hasCurrent() ? readStates.current().getStateEngine() : null; HollowReadStateEngine pending = readStates.pending().getStateEngine(); readSnapshot(artifacts.snapshot, pending); if(readStates.hasCurrent()) { log.info("CHECKSUMS"); HollowChecksum currentChecksum = HollowChecksum.forStateEngineWithCommonSchemas(current, pending); log.info(" CUR " + currentChecksum); HollowChecksum pendingChecksum = HollowChecksum.forStateEngineWithCommonSchemas(pending, current); log.info(" PND " + pendingChecksum); if(artifacts.hasDelta()) { if(!artifacts.hasReverseDelta()) throw new IllegalStateException("Both a delta and reverse delta are required"); // FIXME: timt: future cycles will fail unless both deltas validate applyDelta(artifacts.delta, current); HollowChecksum forwardChecksum = HollowChecksum.forStateEngineWithCommonSchemas(current, pending); //out.format(" CUR => PND %s\n", forwardChecksum); if(!forwardChecksum.equals(pendingChecksum)) throw new ChecksumValidationException(Blob.Type.DELTA); applyDelta(artifacts.reverseDelta, pending); HollowChecksum reverseChecksum = HollowChecksum.forStateEngineWithCommonSchemas(pending, current); //out.format(" CUR <= PND %s\n", reverseChecksum); if(!reverseChecksum.equals(currentChecksum)) throw new ChecksumValidationException(Blob.Type.REVERSE_DELTA); result = readStates.swap(); } } status.success(); return result; } catch(Throwable th) { status.fail(th); throw th; } finally { listeners.fireIntegrityCheckComplete(status); } } public static final class ChecksumValidationException extends IllegalStateException { private static final long serialVersionUID = -4399719849669674206L; ChecksumValidationException(Blob.Type type) { super(type.name() + " checksum invalid"); } } private void readSnapshot(Blob blob, HollowReadStateEngine stateEngine) throws IOException { InputStream is = blob.newInputStream(); try { new HollowBlobReader(stateEngine, new HollowBlobHeaderReader()).readSnapshot(is); } finally { is.close(); } } private void applyDelta(Blob blob, HollowReadStateEngine stateEngine) throws IOException { InputStream is = blob.newInputStream(); try { new HollowBlobReader(stateEngine, new HollowBlobHeaderReader()).applyDelta(is); } finally { is.close(); } } private void validate(HollowProducer.ReadState readState) { ProducerStatus.Builder status = listeners.fireValidationStart(readState); try { List<Throwable> validationFailures = new ArrayList<Throwable>(); for(Validator validator : validators) { try { validator.validate(readState); } catch(Throwable th) { validationFailures.add(th); } } if(!validationFailures.isEmpty()) { ValidationException ex = new ValidationException("Validation Failed", validationFailures.get(0)); ex.setIndividualFailures(validationFailures); throw ex; } status.success(); } catch (Throwable th) { status.fail(th); throw th; } finally { listeners.fireValidationComplete(status); } } private void announce(HollowProducer.ReadState readState) { if(announcer != null) { ProducerStatus.Builder status = listeners.fireAnnouncementStart(readState); try { announcer.announce(readState.getVersion()); status.success(); } catch(Throwable th) { status.fail(th); throw th; } finally { listeners.fireAnnouncementComplete(status); } } } public static interface VersionMinter { /** * Create a new state version.<p> * * State versions should be ascending -- later states have greater versions.<p> * * @return a new state version */ long mint(); } public static interface Populator { void populate(HollowProducer.WriteState newState) throws Exception; } public static interface WriteState { int add(Object o); HollowObjectMapper getObjectMapper(); HollowWriteStateEngine getStateEngine(); ReadState getPriorState(); long getVersion(); } public static interface ReadState { public long getVersion(); public HollowReadStateEngine getStateEngine(); } public static interface BlobStager { /** * Returns a blob with which a {@code HollowProducer} will write a snapshot for the version specified.<p> * * The producer will pass the returned blob back to this publisher when calling {@link Publisher#publish(Blob)}. * * @param version the blob version * * @return a {@link HollowProducer.Blob} representing a snapshot for the {@code version} */ public HollowProducer.Blob openSnapshot(long version); /** * Returns a blob with which a {@code HollowProducer} will write a forward delta from the version specified to * the version specified, i.e. {@code fromVersion => toVersion}.<p> * * The producer will pass the returned blob back to this publisher when calling {@link Publisher#publish(Blob)}. * * In the delta chain {@code fromVersion} is the older version such that {@code fromVersion < toVersion}. * * @param fromVersion the data state this delta will transition from * @param toVersion the data state this delta will transition to * * @return a {@link HollowProducer.Blob} representing a snapshot for the {@code version} */ public HollowProducer.Blob openDelta(long fromVersion, long toVersion); /** * Returns a blob with which a {@code HollowProducer} will write a reverse delta from the version specified to * the version specified, i.e. {@code fromVersion <= toVersion}.<p> * * The producer will pass the returned blob back to this publisher when calling {@link Publisher#publish(Blob)}. * * In the delta chain {@code fromVersion} is the older version such that {@code fromVersion < toVersion}. * * @param fromVersion version in the delta chain immediately after {@code toVersion} * @param toVersion version in the delta chain immediately before {@code fromVersion} * * @return a {@link HollowProducer.Blob} representing a snapshot for the {@code version} */ public HollowProducer.Blob openReverseDelta(long fromVersion, long toVersion); } public static interface BlobCompressor { public static final BlobCompressor NO_COMPRESSION = new BlobCompressor() { @Override public OutputStream compress(OutputStream os) { return os; } @Override public InputStream decompress(InputStream is) { return is; } }; /** * This method provides an opportunity to wrap the OutputStream used to write the blob (e.g. with a GZIPOutputStream). */ public OutputStream compress(OutputStream is); /** * This method provides an opportunity to wrap the InputStream used to write the blob (e.g. with a GZIPInputStream). */ public InputStream decompress(InputStream is); } public static interface Publisher { /** * Publish the blob specified to this publisher's blobstore.<p> * * It is guaranteed that {@code blob} was created by calling one of * {@link BlobStager#openSnapshot(long)}, {@link BlobStager#openDelta(long,long)}, or * {@link BlobStager#openReverseDelta(long,long)} on this publisher. * * @param blob the blob to publish */ public abstract void publish(HollowProducer.Blob blob); } public static abstract class Blob { protected final long fromVersion; protected final long toVersion; protected final Blob.Type type; protected Blob(long fromVersion, long toVersion, Blob.Type type) { this.fromVersion = fromVersion; this.toVersion = toVersion; this.type = type; } protected abstract void write(HollowBlobWriter writer) throws IOException; public abstract InputStream newInputStream() throws IOException; public abstract void cleanup(); public File getFile() { throw new UnsupportedOperationException("File is not available"); } public Type getType() { return this.type; } public long getFromVersion() { return this.fromVersion; } public long getToVersion() { return this.toVersion; } /** * Hollow blob types are {@code SNAPSHOT}, {@code DELTA} and {@code REVERSE_DELTA}. */ public static enum Type { SNAPSHOT("snapshot"), DELTA("delta"), REVERSE_DELTA("reversedelta"); public final String prefix; Type(String prefix) { this.prefix = prefix; } } } public static interface Validator { void validate(HollowProducer.ReadState readState); @SuppressWarnings("serial") public static class ValidationException extends RuntimeException { private List<Throwable> individualFailures; public ValidationException() { super(); } public ValidationException(String msg) { super(msg); } public ValidationException(String msg, Throwable cause) { super(msg, cause); } public void setIndividualFailures(List<Throwable> individualFailures) { this.individualFailures = individualFailures; } public List<Throwable> getIndividualFailures() { return individualFailures; } } } public static interface Announcer { public void announce(long stateVersion); } private static final class Artifacts { Blob snapshot = null; Blob delta = null; Blob reverseDelta = null; boolean cleanupCalled; boolean snapshotPublishComplete; synchronized void cleanup() { cleanupCalled = true; cleanupSnapshot(); if(delta != null) { delta.cleanup(); delta = null; } if(reverseDelta != null) { reverseDelta.cleanup(); reverseDelta = null; } } synchronized void markSnapshotPublishComplete() { snapshotPublishComplete = true; cleanupSnapshot(); } private void cleanupSnapshot() { if(cleanupCalled && snapshotPublishComplete && snapshot != null) { snapshot.cleanup(); snapshot = null; } } boolean hasDelta() { return delta != null; } public boolean hasReverseDelta() { return reverseDelta != null; } } public static HollowProducer.Builder withPublisher(HollowProducer.Publisher publisher) { Builder builder = new Builder(); return builder.withPublisher(publisher); } public static class Builder { protected BlobStager stager; protected BlobCompressor compressor; protected File stagingDir; protected Publisher publisher; protected Announcer announcer; protected List<Validator> validators = new ArrayList<Validator>(); protected List<HollowProducerListener> listeners = new ArrayList<HollowProducerListener>(); protected VersionMinter versionMinter = new VersionMinterWithCounter(); protected Executor snapshotPublishExecutor = null; protected int numStatesBetweenSnapshots = 0; protected long targetMaxTypeShardSize = DEFAULT_TARGET_MAX_TYPE_SHARD_SIZE; protected HollowMetricsCollector<HollowProducerMetrics> metricsCollector; protected BlobStorageCleaner blobStorageCleaner = new DummyBlobStorageCleaner(); protected SingleProducerEnforcer singleProducerEnforcer = new BasicSingleProducerEnforcer(); public Builder withBlobStager(HollowProducer.BlobStager stager) { this.stager = stager; return this; } public Builder withBlobCompressor(HollowProducer.BlobCompressor compressor) { this.compressor = compressor; return this; } public Builder withBlobStagingDir(File stagingDir) { this.stagingDir = stagingDir; return this; } public Builder withPublisher(HollowProducer.Publisher publisher) { this.publisher = publisher; return this; } public Builder withAnnouncer(HollowProducer.Announcer announcer) { this.announcer = announcer; return this; } public Builder withValidator(HollowProducer.Validator validator) { this.validators.add(validator); return this; } public Builder withValidators(HollowProducer.Validator... validators) { for(Validator validator : validators) this.validators.add(validator); return this; } public Builder withListener(HollowProducerListener listener) { this.listeners.add(listener); return this; } public Builder withListeners(HollowProducerListener... listeners) { for(HollowProducerListener listener : listeners) this.listeners.add(listener); return this; } public Builder withVersionMinter(HollowProducer.VersionMinter versionMinter) { this.versionMinter = versionMinter; return this; } public Builder withSnapshotPublishExecutor(Executor executor) { this.snapshotPublishExecutor = executor; return this; } public Builder withNumStatesBetweenSnapshots(int numStatesBetweenSnapshots) { this.numStatesBetweenSnapshots = numStatesBetweenSnapshots; return this; } public Builder withTargetMaxTypeShardSize(long targetMaxTypeShardSize) { this.targetMaxTypeShardSize = targetMaxTypeShardSize; return this; } public Builder withMetricsCollector(HollowMetricsCollector<HollowProducerMetrics> metricsCollector) { this.metricsCollector = metricsCollector; return this; } public Builder withBlobStorageCleaner(BlobStorageCleaner blobStorageCleaner) { this.blobStorageCleaner = blobStorageCleaner; return this; } public Builder withSingleProducerEnforcer(SingleProducerEnforcer singleProducerEnforcer) { this.singleProducerEnforcer = singleProducerEnforcer; return this; } protected void checkArguments() { if(stager != null && compressor != null) throw new IllegalArgumentException("Both a custom BlobStager and BlobCompressor were specified -- please specify only one of these."); if(stager != null && stagingDir != null) throw new IllegalArgumentException("Both a custom BlobStager and a staging directory were specified -- please specify only one of these."); if(this.stager == null) { BlobCompressor compressor = this.compressor != null ? this.compressor : BlobCompressor.NO_COMPRESSION; File stagingDir = this.stagingDir != null ? this.stagingDir : new File(System.getProperty("java.io.tmpdir")); this.stager = new HollowFilesystemBlobStager(stagingDir, compressor); } } public HollowProducer build() { checkArguments(); return new HollowProducer(stager, publisher, announcer, validators, listeners, versionMinter, snapshotPublishExecutor, numStatesBetweenSnapshots, targetMaxTypeShardSize, metricsCollector, blobStorageCleaner, singleProducerEnforcer); } } /** * Provides the opportunity to clean the blob storage. * It allows users to implement logic base on Blob Type. */ public static abstract class BlobStorageCleaner { public void clean(Blob.Type blobType) { switch(blobType) { case SNAPSHOT: cleanSnapshots(); break; case DELTA: cleanDeltas(); break; case REVERSE_DELTA: cleanReverseDeltas(); break; } } /** * This method provides an opportunity to remove old snapshots. */ public abstract void cleanSnapshots(); /** * This method provides an opportunity to remove old deltas. */ public abstract void cleanDeltas(); /** * This method provides an opportunity to remove old reverse deltas. */ public abstract void cleanReverseDeltas(); } /** * This Dummy blob storage cleaner does nothing */ private static class DummyBlobStorageCleaner extends HollowProducer.BlobStorageCleaner { @Override public void cleanSnapshots() { } @Override public void cleanDeltas() { } @Override public void cleanReverseDeltas() { } } }
Fix Producer Backwards incompatible take 2
hollow/src/main/java/com/netflix/hollow/api/producer/HollowProducer.java
Fix Producer Backwards incompatible take 2
Java
apache-2.0
46760478f67465d0c902142b4d54fd2c0af4b33c
0
xsobolx/robospice,hgl888/robospice,rabyunghwa/robospice,git4slash/robospice,git4slash/robospice,johnjohndoe/robospice,arunlodhi/robospice,rabyunghwa/robospice,Proper-Job/robospice,JunyiZhou/robospice,hejunbinlan/robospice,johnjohndoe/robospice,xsobolx/robospice,rav3n/robospice,jxauchengchao/robospice,fahmihidayah/robospice,hgl888/robospice,Proper-Job/robospice,JunyiZhou/robospice,arunlodhi/robospice,fahmihidayah/robospice,stephanenicolas/robospice,ldw85/robospice,dgyuri/robospice-minimal,dgyuri/robospice-minimal,rav3n/robospice,stephanenicolas/robospice,jxauchengchao/robospice,ldw85/robospice,hejunbinlan/robospice
package com.octo.android.robospice.persistence.file; import java.io.File; import java.io.FileFilter; import java.util.List; import roboguice.util.temp.Ln; import android.app.Application; import com.octo.android.robospice.persistence.CacheCleaner; import com.octo.android.robospice.persistence.ObjectPersister; import com.octo.android.robospice.persistence.ObjectPersisterFactory; import com.octo.android.robospice.persistence.exception.CacheCreationException; import com.octo.android.robospice.persistence.keysanitation.KeySanitizer; /** * A factory that will create {@link ObjectPersister} instances that save/load * data in a file. * @author sni */ public abstract class InFileObjectPersisterFactory extends ObjectPersisterFactory implements CacheCleaner { // ---------------------------------- // ATTRIBUTES // ---------------------------------- private File cacheFolder; private String cachePrefix; private KeySanitizer keySanitizer; // ---------------------------------- // CONSTRUCTORS // ---------------------------------- public InFileObjectPersisterFactory(Application application) throws CacheCreationException { this(application, null, null); } public InFileObjectPersisterFactory(Application application, File cacheFolder) throws CacheCreationException { this(application, null, cacheFolder); } public InFileObjectPersisterFactory(Application application, List<Class<?>> listHandledClasses) throws CacheCreationException { this(application, listHandledClasses, null); } public InFileObjectPersisterFactory(Application application, List<Class<?>> listHandledClasses, File cacheFolder) throws CacheCreationException { super(application, listHandledClasses); setCacheFolder(cacheFolder); setCachePrefix(getClass().getSimpleName() + InFileObjectPersister.CACHE_PREFIX_END); } // ---------------------------------- // API // ---------------------------------- /** * Sets the folder used by object persisters of this factory. * @param cacheFolder * the new cache folder of this factory (and persisters it will * create). Ca be null, it will then default to the sub folder * {@link InFileObjectPersister#DEFAULT_ROOT_CACHE_DIR} in side * the application cache folder. Will be created if doesn't exist * yet. * @throws CacheCreationException */ public void setCacheFolder(File cacheFolder) throws CacheCreationException { if (cacheFolder == null) { cacheFolder = new File(getApplication().getCacheDir(), InFileObjectPersister.DEFAULT_ROOT_CACHE_DIR); } this.cacheFolder = cacheFolder; if (!cacheFolder.exists() && !cacheFolder.mkdirs()) { throw new CacheCreationException("The cache folder " + cacheFolder.getAbsolutePath() + " could not be created."); } } /** * Sets the cachePrefix used by object persisters of this factory. * @param cachePrefix * the new cache cachePrefix of this factory (and persisters it * will create). Defaults to "className". */ public void setCachePrefix(String cachePrefix) { this.cachePrefix = cachePrefix; } public File getCacheFolder() { return cacheFolder; } public String getCachePrefix() { return cachePrefix; } public KeySanitizer getKeySanitizer() { return keySanitizer; } /** * @param keySanitizer * the new key sanitizer to be used by this * {@link InFileObjectPersisterFactory} and persisters. May be * null, in that case no key sanitation will be used. This is the * default. */ public void setKeySanitizer(KeySanitizer keySanitizer) { this.keySanitizer = keySanitizer; } @Override public final <T> InFileObjectPersister<T> createObjectPersister(Class<T> clazz) { InFileObjectPersister<T> inFileObjectPersister; try { inFileObjectPersister = createInFileObjectPersister(clazz, cacheFolder); inFileObjectPersister.setFactoryCachePrefix(cachePrefix); inFileObjectPersister.setKeySanitizer(keySanitizer); return inFileObjectPersister; } catch (CacheCreationException e) { throw new RuntimeException("Could not create cache folder of factory.", e); } } public abstract <T> InFileObjectPersister<T> createInFileObjectPersister(Class<T> clazz, File cacheFolder) throws CacheCreationException; @Override public void removeAllDataFromCache() { File cacheFolder = getCacheFolder(); File[] cacheFileList = cacheFolder.listFiles(new FileFilter() { @Override public boolean accept(File file) { return file.getName().startsWith(getCachePrefix()); } }); boolean allDeleted = true; if (cacheFileList == null || cacheFileList.length == 0) { return; } for (File cacheFile : cacheFileList) { allDeleted = cacheFile.delete() && allDeleted; } if (allDeleted || cacheFileList.length == 0) { Ln.d("Some file could not be deleted from cache."); } } }
robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/file/InFileObjectPersisterFactory.java
package com.octo.android.robospice.persistence.file; import java.io.File; import java.io.FileFilter; import java.util.List; import roboguice.util.temp.Ln; import android.app.Application; import com.octo.android.robospice.persistence.CacheCleaner; import com.octo.android.robospice.persistence.ObjectPersister; import com.octo.android.robospice.persistence.ObjectPersisterFactory; import com.octo.android.robospice.persistence.exception.CacheCreationException; import com.octo.android.robospice.persistence.keysanitation.KeySanitizer; /** * A factory that will create {@link ObjectPersister} instances that save/load * data in a file. * @author sni */ public abstract class InFileObjectPersisterFactory extends ObjectPersisterFactory implements CacheCleaner { // ---------------------------------- // ATTRIBUTES // ---------------------------------- private File cacheFolder; private String cachePrefix; private KeySanitizer keySanitizer; // ---------------------------------- // CONSTRUCTORS // ---------------------------------- public InFileObjectPersisterFactory(Application application) throws CacheCreationException { this(application, null, null); } public InFileObjectPersisterFactory(Application application, File cacheFolder) throws CacheCreationException { this(application, null, cacheFolder); } public InFileObjectPersisterFactory(Application application, List<Class<?>> listHandledClasses) throws CacheCreationException { this(application, listHandledClasses, null); } public InFileObjectPersisterFactory(Application application, List<Class<?>> listHandledClasses, File cacheFolder) throws CacheCreationException { super(application, listHandledClasses); setCacheFolder(cacheFolder); setCachePrefix(getClass().getSimpleName() + InFileObjectPersister.CACHE_PREFIX_END); } // ---------------------------------- // API // ---------------------------------- /** * Sets the folder used by object persisters of this factory. * @param cacheFolder * the new cache folder of this factory (and persisters it will * create). Ca be null, it will then default to the sub folder * {@link InFileObjectPersister#DEFAULT_ROOT_CACHE_DIR} in side * the application cache folder. Will be created if doesn't exist * yet. * @throws CacheCreationException */ public void setCacheFolder(File cacheFolder) throws CacheCreationException { if (cacheFolder == null) { cacheFolder = new File(getApplication().getCacheDir(), InFileObjectPersister.DEFAULT_ROOT_CACHE_DIR); } this.cacheFolder = cacheFolder; if (!cacheFolder.exists() && !cacheFolder.mkdirs()) { throw new CacheCreationException("The cache folder " + cacheFolder.getAbsolutePath() + " could not be created."); } } /** * Sets the cachePrefix used by object persisters of this factory. * @param cachePrefix * the new cache cachePrefix of this factory (and persisters it * will create). Defaults to "className". */ public void setCachePrefix(String cachePrefix) { this.cachePrefix = cachePrefix; } public File getCacheFolder() { return cacheFolder; } public String getCachePrefix() { return cachePrefix; } public KeySanitizer getKeySanitizer() { return keySanitizer; } /** * @param keySanitizer * the new key sanitizer to be used by this * {@link InFileObjectPersisterFactory} and persisters. May be * null, in that case no key sanitation will be used. This is the * default. */ public void setKeySanitizer(KeySanitizer keySanitizer) { this.keySanitizer = keySanitizer; } @Override public final <T> InFileObjectPersister<T> createObjectPersister(Class<T> clazz) { InFileObjectPersister<T> inFileObjectPersister; try { inFileObjectPersister = createInFileObjectPersister(clazz, cacheFolder); inFileObjectPersister.setFactoryCachePrefix(cachePrefix); inFileObjectPersister.setKeySanitizer(keySanitizer); return inFileObjectPersister; } catch (CacheCreationException e) { throw new RuntimeException("Could not create cache folder of factory.", e); } } public abstract <T> InFileObjectPersister<T> createInFileObjectPersister(Class<T> clazz, File cacheFolder) throws CacheCreationException; @Override public void removeAllDataFromCache() { File cacheFolder = getCacheFolder(); File[] cacheFileList = cacheFolder.listFiles(new FileFilter() { @Override public boolean accept(File file) { return file.getName().startsWith(getCachePrefix()); } }); boolean allDeleted = true; for (File cacheFile : cacheFileList) { allDeleted = cacheFile.delete() && allDeleted; } if (allDeleted || cacheFileList.length == 0) { Ln.d("Some file could not be deleted from cache."); } } }
Correct bug in cache removal when the cache folder doesn't exist.
robospice-cache-parent/robospice-cache/src/main/java/com/octo/android/robospice/persistence/file/InFileObjectPersisterFactory.java
Correct bug in cache removal when the cache folder doesn't exist.
Java
apache-2.0
35cf11dc82645afff3d76003a6ef70ec742d3a50
0
google/robotstxt-java
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.search.robotstxt; /** * Provides methods to calculate match priority for given directives against given URL. It is * required to compute match verdict in {@link RobotsMatcher}. */ public interface MatchingStrategy { /** * Calculates priority of ALLOW verdict based on given directive. * * @param targetUrl URL to calculate ALLOW match priority against * @param directiveValue ALLOW directive value * @return match priority (higher value means higher chance of ALLOW verdict) */ int matchAllowPriority(final String targetUrl, final String directiveValue); /** * Calculates priority of DISALLOW verdict based on given directive. * * @param targetUrl URL to calculate DISALLOW match priority against * @param directiveValue DISALLOW directive value * @return match priority (higher value means higher chance of DISALLOW verdict) */ int matchDisallowPriority(final String targetUrl, final String directiveValue); }
src/main/java/com/google/search/robotstxt/MatchingStrategy.java
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.search.robotstxt; /** * Provides methods to calculate match priority for given directives against given URL. It is * required to compute match verdict in {@link RobotsMatcher}. */ public interface MatchingStrategy { /** * Calculates priority of ALLOW verdict based on given directive. * * @param targetUrl URL to calculate ALLOW match priority against * @param directiveValue ALLOW directive value * @return match priority (higher value means higher chance of ALLOW verdict) */ int matchAllowPriority(final String targetUrl, final String directiveValue); /** * Calculates priority of DISALLOW verdict based on given directive. * * @param targetUrl URL to calculate DISALLOW match priority against * @param directiveValue DISALLOW directive value * @return match priority (higher value means higher chance of ALLOW verdict) */ int matchDisallowPriority(final String targetUrl, final String directiveValue); }
Fixed Javadoc.
src/main/java/com/google/search/robotstxt/MatchingStrategy.java
Fixed Javadoc.
Java
apache-2.0
3b5fc5e9cc7b436e85a7d8992b61b4c6d9f30189
0
vpavic/spring-session,vpavic/spring-session,vpavic/spring-session
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.session.hazelcast.config.annotation.web.http; import static org.assertj.core.api.Assertions.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.session.ExpiringSession; import org.springframework.session.FindByIndexNameSessionRepository; import org.springframework.session.Session; import org.springframework.session.SessionRepository; import org.springframework.session.data.SessionEventRegistry; import org.springframework.session.events.SessionCreatedEvent; import org.springframework.session.events.SessionDeletedEvent; import org.springframework.session.events.SessionExpiredEvent; import org.springframework.session.hazelcast.HazelcastITestUtils; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.hazelcast.core.HazelcastInstance; /** * Ensure that the appropriate SessionEvents are fired at the expected times. * Additionally ensure that the interactions with the {@link SessionRepository} * abstraction behave as expected after each SessionEvent. * * @author Tommy Ludwig */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @WebAppConfiguration public class EnableHazelcastHttpSessionEventsTests<S extends ExpiringSession> { private final static int MAX_INACTIVE_INTERVAL_IN_SECONDS = 1; @Autowired private SessionRepository<S> repository; @Autowired private SessionEventRegistry registry; private final Object lock = new Object(); @Before public void setup() { registry.clear(); registry.setLock(lock); } @Test public void saveSessionTest() throws InterruptedException { String username = "saves-"+System.currentTimeMillis(); S sessionToSave = repository.createSession(); String expectedAttributeName = "a"; String expectedAttributeValue = "b"; sessionToSave.setAttribute(expectedAttributeName, expectedAttributeValue); Authentication toSaveToken = new UsernamePasswordAuthenticationToken(username,"password", AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContext toSaveContext = SecurityContextHolder.createEmptyContext(); toSaveContext.setAuthentication(toSaveToken); sessionToSave.setAttribute("SPRING_SECURITY_CONTEXT", toSaveContext); sessionToSave.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username); repository.save(sessionToSave); assertThat(registry.receivedEvent()).isTrue(); assertThat(registry.getEvent()).isInstanceOf(SessionCreatedEvent.class); Session session = repository.getSession(sessionToSave.getId()); assertThat(session.getId()).isEqualTo(sessionToSave.getId()); assertThat(session.getAttributeNames()).isEqualTo(sessionToSave.getAttributeNames()); assertThat(session.getAttribute(expectedAttributeName)).isEqualTo(sessionToSave.getAttribute(expectedAttributeName)); } @Test public void expiredSessionTest() throws InterruptedException { S sessionToSave = repository.createSession(); repository.save(sessionToSave); assertThat(registry.receivedEvent()).isTrue(); assertThat(registry.getEvent()).isInstanceOf(SessionCreatedEvent.class); registry.clear(); assertThat(sessionToSave.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); synchronized (lock) { lock.wait((sessionToSave.getMaxInactiveIntervalInSeconds() * 1000) + 1); } assertThat(registry.receivedEvent()).isTrue(); assertThat(registry.getEvent()).isInstanceOf(SessionExpiredEvent.class); assertThat(repository.getSession(sessionToSave.getId())).isNull(); } @Test public void deletedSessionTest() throws InterruptedException { S sessionToSave = repository.createSession(); repository.save(sessionToSave); assertThat(registry.receivedEvent()).isTrue(); assertThat(registry.getEvent()).isInstanceOf(SessionCreatedEvent.class); registry.clear(); repository.delete(sessionToSave.getId()); assertThat(registry.receivedEvent()).isTrue(); assertThat(registry.getEvent()).isInstanceOf(SessionDeletedEvent.class); assertThat(repository.getSession(sessionToSave.getId())).isNull(); } @Test public void saveUpdatesTimeToLiveTest() throws InterruptedException { S sessionToSave = repository.createSession(); repository.save(sessionToSave); synchronized (lock) { lock.wait((sessionToSave.getMaxInactiveIntervalInSeconds() * 1000) - 500); } // Get and save the session like SessionRepositoryFilter would. S sessionToUpdate = repository.getSession(sessionToSave.getId()); sessionToUpdate.setLastAccessedTime(System.currentTimeMillis()); repository.save(sessionToUpdate); synchronized (lock) { lock.wait((sessionToUpdate.getMaxInactiveIntervalInSeconds() * 1000) - 100); } assertThat(repository.getSession(sessionToUpdate.getId())).isNotNull(); } @Configuration @EnableHazelcastHttpSession(maxInactiveIntervalInSeconds = MAX_INACTIVE_INTERVAL_IN_SECONDS) static class HazelcastSessionConfig { @Bean public HazelcastInstance embeddedHazelcast() { return HazelcastITestUtils.embeddedHazelcastServer(); } @Bean public SessionEventRegistry sessionEventRegistry() { return new SessionEventRegistry(); } } }
spring-session/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSessionEventsTests.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.session.hazelcast.config.annotation.web.http; import static org.assertj.core.api.Assertions.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.session.ExpiringSession; import org.springframework.session.FindByIndexNameSessionRepository; import org.springframework.session.Session; import org.springframework.session.SessionRepository; import org.springframework.session.data.SessionEventRegistry; import org.springframework.session.events.SessionCreatedEvent; import org.springframework.session.events.SessionDeletedEvent; import org.springframework.session.events.SessionExpiredEvent; import org.springframework.session.hazelcast.HazelcastITestUtils; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.hazelcast.core.HazelcastInstance; /** * Ensure that the appropriate SessionEvents are fired at the expected times. * Additionally ensure that the interactions with the {@link SessionRepository} * abstraction behave as expected after each SessionEvent. * * @author Tommy Ludwig */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @WebAppConfiguration public class EnableHazelcastHttpSessionEventsTests<S extends ExpiringSession> { private final static int MAX_INACTIVE_INTERVAL_IN_SECONDS = 1; @Autowired private SessionRepository<S> repository; @Autowired private SessionEventRegistry registry; private final Object lock = new Object(); @Before public void setup() { registry.clear(); registry.setLock(lock); } @Test public void saveSessionTest() throws InterruptedException { String username = "saves-"+System.currentTimeMillis(); S sessionToSave = repository.createSession(); String expectedAttributeName = "a"; String expectedAttributeValue = "b"; sessionToSave.setAttribute(expectedAttributeName, expectedAttributeValue); Authentication toSaveToken = new UsernamePasswordAuthenticationToken(username,"password", AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContext toSaveContext = SecurityContextHolder.createEmptyContext(); toSaveContext.setAuthentication(toSaveToken); sessionToSave.setAttribute("SPRING_SECURITY_CONTEXT", toSaveContext); sessionToSave.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username); repository.save(sessionToSave); assertThat(registry.receivedEvent()).isTrue(); assertThat(registry.getEvent()).isInstanceOf(SessionCreatedEvent.class); Session session = repository.getSession(sessionToSave.getId()); assertThat(session.getId()).isEqualTo(sessionToSave.getId()); assertThat(session.getAttributeNames()).isEqualTo(sessionToSave.getAttributeNames()); assertThat(session.getAttribute(expectedAttributeName)).isEqualTo(sessionToSave.getAttribute(expectedAttributeName)); } @Test public void expiredSessionTest() throws InterruptedException { S sessionToSave = repository.createSession(); repository.save(sessionToSave); assertThat(registry.receivedEvent()).isTrue(); assertThat(registry.getEvent()).isInstanceOf(SessionCreatedEvent.class); registry.clear(); assertThat(sessionToSave.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); synchronized (lock) { lock.wait((sessionToSave.getMaxInactiveIntervalInSeconds() * 1000) + 1); } assertThat(registry.receivedEvent()).isTrue(); assertThat(registry.getEvent()).isInstanceOf(SessionExpiredEvent.class); assertThat(repository.getSession(sessionToSave.getId())).isNull(); } @Test public void deletedSessionTest() throws InterruptedException { S sessionToSave = repository.createSession(); repository.save(sessionToSave); assertThat(registry.receivedEvent()).isTrue(); assertThat(registry.getEvent()).isInstanceOf(SessionCreatedEvent.class); registry.clear(); repository.delete(sessionToSave.getId()); assertThat(registry.receivedEvent()).isTrue(); assertThat(registry.getEvent()).isInstanceOf(SessionDeletedEvent.class); assertThat(repository.getSession(sessionToSave.getId())).isNull(); } @Test public void saveUpdatesTimeToLiveTest() throws InterruptedException { S sessionToSave = repository.createSession(); repository.save(sessionToSave); synchronized (lock) { lock.wait((sessionToSave.getMaxInactiveIntervalInSeconds() * 1000) - 500); } // Get and save the session like SessionRepositoryFilter would. S sessionToUpdate = repository.getSession(sessionToSave.getId()); repository.save(sessionToUpdate); synchronized (lock) { lock.wait((sessionToUpdate.getMaxInactiveIntervalInSeconds() * 1000) - 100); } assertThat(repository.getSession(sessionToUpdate.getId())).isNotNull(); } @Configuration @EnableHazelcastHttpSession(maxInactiveIntervalInSeconds = MAX_INACTIVE_INTERVAL_IN_SECONDS) static class HazelcastSessionConfig { @Bean public HazelcastInstance embeddedHazelcast() { return HazelcastITestUtils.embeddedHazelcastServer(); } @Bean public SessionEventRegistry sessionEventRegistry() { return new SessionEventRegistry(); } } }
Fix Hazelcast saveUpdatesTimeToLiveTest
spring-session/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSessionEventsTests.java
Fix Hazelcast saveUpdatesTimeToLiveTest
Java
apache-2.0
ee59f1044b3af1f96d4008508cce6e605fb1185e
0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.example.sharding.raw.jdbc; import org.apache.shardingsphere.example.core.api.ExampleExecuteTemplate; import org.apache.shardingsphere.example.core.api.service.ExampleService; import org.apache.shardingsphere.example.core.jdbc.service.OrderServiceImpl; import org.apache.shardingsphere.example.sharding.raw.jdbc.factory.YamlDataSourceFactory; import org.apache.shardingsphere.example.type.ShardingType; import javax.sql.DataSource; import java.io.IOException; import java.sql.SQLException; /* * Please make sure primary replica data replication sync on MySQL is running correctly. Otherwise this example will query empty data from replica. */ public final class YamlConfigurationExampleMain { private static ShardingType shardingType = ShardingType.SHARDING_DATABASES; // private static ShardingType shardingType = ShardingType.SHARDING_TABLES; // private static ShardingType shardingType = ShardingType.SHARDING_DATABASES_AND_TABLES; // private static ShardingType shardingType = ShardingType.READWRITE_SPLITTING; // private static ShardingType shardingType = ShardingType.SHARDING_READWRITE_SPLITTING; public static void main(final String[] args) throws SQLException, IOException { DataSource dataSource = YamlDataSourceFactory.newInstance(shardingType); ExampleExecuteTemplate.run(getExampleService(dataSource)); } private static ExampleService getExampleService(final DataSource dataSource) { return new OrderServiceImpl(dataSource); } }
examples/shardingsphere-jdbc-example/sharding-example/sharding-raw-jdbc-example/src/main/java/org/apache/shardingsphere/example/sharding/raw/jdbc/YamlConfigurationExampleMain.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.example.sharding.raw.jdbc; import org.apache.shardingsphere.example.core.api.ExampleExecuteTemplate; import org.apache.shardingsphere.example.core.api.service.ExampleService; import org.apache.shardingsphere.example.core.jdbc.service.OrderServiceImpl; import org.apache.shardingsphere.example.sharding.raw.jdbc.factory.YamlDataSourceFactory; import org.apache.shardingsphere.example.type.ShardingType; import javax.sql.DataSource; import java.io.IOException; import java.sql.SQLException; /* * Please make sure primary replica data replication sync on MySQL is running correctly. Otherwise this example will query empty data from replica. */ public final class YamlConfigurationExampleMain { private static ShardingType shardingType = ShardingType.SHARDING_READWRITE_SPLITTING; // private static ShardingType shardingType = ShardingType.SHARDING_TABLES; // private static ShardingType shardingType = ShardingType.SHARDING_DATABASES_AND_TABLES; // private static ShardingType shardingType = ShardingType.READWRITE_SPLITTING; // private static ShardingType shardingType = ShardingType.SHARDING_READWRITE_SPLITTING; public static void main(final String[] args) throws SQLException, IOException { DataSource dataSource = YamlDataSourceFactory.newInstance(shardingType); ExampleExecuteTemplate.run(getExampleService(dataSource)); } private static ExampleService getExampleService(final DataSource dataSource) { return new OrderServiceImpl(dataSource); } }
fix sharding-raw-jdbc-example (#10573)
examples/shardingsphere-jdbc-example/sharding-example/sharding-raw-jdbc-example/src/main/java/org/apache/shardingsphere/example/sharding/raw/jdbc/YamlConfigurationExampleMain.java
fix sharding-raw-jdbc-example (#10573)
Java
apache-2.0
4a8d110e681076159b0e223a3d03e8900f511839
0
googleinterns/step128-2020,googleinterns/step128-2020,googleinterns/step128-2020
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps; import static com.google.appengine.api.datastore.FetchOptions.Builder.withLimit; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.*; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Query; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.google.sps.servlets.EventServlet; import com.google.sps.servlets.KeywordSearchServlet; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; @PowerMockIgnore("okhttp3.*") @RunWith(PowerMockRunner.class) @SuppressStaticInitializationFor({"com.google.sps.Firebase"}) @PrepareForTest({Firebase.class}) public final class EventServletTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()); private EventServlet testEventServlet; @Before public void setUp() throws IOException { helper.setUp(); testEventServlet = new EventServlet(); } @After public void tearDown() { helper.tearDown(); } @Test public void postOneEventToDatastore() throws IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); TestingUtil.mockFirebase(request, "[email protected]"); // Add a mock request to pass as a parameter to doPost. when(request.getParameter("event-name")).thenReturn("Lake Clean Up"); when(request.getParameter("event-description")).thenReturn("We're cleaning up the lake"); when(request.getParameter("street-address")).thenReturn("678 Lakeview Way"); when(request.getParameter("city")).thenReturn("Lakeside"); when(request.getParameter("state")).thenReturn("Michigan"); when(request.getParameter("date")).thenReturn("2020-05-17"); when(request.getParameter("start-time")).thenReturn("14:00"); when(request.getParameter("end-time")).thenReturn("15:00"); when(request.getParameter("cover-photo")).thenReturn("/img-2030121"); String[] tags = {"environment"}; when(request.getParameter("all-tags")).thenReturn(Utils.convertToJson(tags)); // Post event to Datastore. testEventServlet.doPost(request, response); // Assert only one Entity was posted to Datastore. DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); assertEquals(1, ds.prepare(new Query("Event")).countEntities(withLimit(10))); assertEquals(1, ds.prepare(new Query("Interaction")).countEntities(withLimit(10))); } @Test public void postMultipleEventsToDatastore() throws IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); TestingUtil.mockFirebase(request, "[email protected]"); // Add a mock request to pass as a parameter to doPost. when(request.getParameter("event-name")).thenReturn("Lake Clean Up"); when(request.getParameter("event-description")).thenReturn("We're cleaning up the lake"); when(request.getParameter("street-address")).thenReturn("678 Lakeview Way"); when(request.getParameter("city")).thenReturn("Lakeside"); when(request.getParameter("state")).thenReturn("Michigan"); when(request.getParameter("date")).thenReturn("2020-05-17"); when(request.getParameter("start-time")).thenReturn("14:00"); when(request.getParameter("end-time")).thenReturn("15:00"); when(request.getParameter("cover-photo")).thenReturn("/img-2030121"); String[] tags = {"environment"}; when(request.getParameter("all-tags")).thenReturn(Utils.convertToJson(tags)); // Post three events to Datastore. testEventServlet.doPost(request, response); testEventServlet.doPost(request, response); testEventServlet.doPost(request, response); // Assert all three Entities were posted to Datastore. DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); assertEquals(3, ds.prepare(new Query("Event")).countEntities(withLimit(10))); Iterable<Entity> interactions = ds.prepare(new Query("Interaction")).asIterable(); int size = 0; for (Entity e : interactions) { size++; assertEquals(Interactions.CREATE_SCORE, Integer.parseInt(e.getProperty("rating").toString())); assertEquals("[email protected]", e.getProperty("user").toString()); } assertEquals(3, size); } @Test public void postEventWithAllFields() throws IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); String creatorEmail = "[email protected]"; TestingUtil.mockFirebase(request, creatorEmail); // Add a mock request to pass as a parameter to doPost. when(request.getParameter("event-name")).thenReturn("Lake Clean Up"); when(request.getParameter("event-description")).thenReturn("We're cleaning up the lake"); when(request.getParameter("street-address")).thenReturn("678 Lakeview Way"); when(request.getParameter("city")).thenReturn("Lakeside"); when(request.getParameter("state")).thenReturn("Michigan"); when(request.getParameter("date")).thenReturn("2020-05-17"); when(request.getParameter("start-time")).thenReturn("14:00"); when(request.getParameter("end-time")).thenReturn("15:00"); when(request.getParameter("cover-photo")).thenReturn("/img-2030121"); String[] tagsArr = {"environment"}; String tagsStr = Utils.convertToJson(tagsArr); when(request.getParameter("all-tags")).thenReturn(tagsStr); // Post event to Datastore. testEventServlet.doPost(request, response); // Retrieve the Entity posted to Datastore. DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Entity postedEntity = ds.prepare(new Query("Event")).asSingleEntity(); Entity goalEntity = createEntity(); // Assert the Entity posted to Datastore has the same properties as the // the goalEntity. assertEntitiesEqual(goalEntity, postedEntity); } @Test public void postEventWithEmptyOptionalFields() throws IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); TestingUtil.mockFirebase(request, "[email protected]"); // This mock request does not include optional fields end-time and cover-photo. when(request.getParameter("event-name")).thenReturn("Lake Clean Up"); when(request.getParameter("event-description")).thenReturn("We're cleaning up the lake"); when(request.getParameter("street-address")).thenReturn("678 Lakeview Way"); when(request.getParameter("city")).thenReturn("Lakeside"); when(request.getParameter("state")).thenReturn("Michigan"); when(request.getParameter("date")).thenReturn("2020-05-17"); when(request.getParameter("start-time")).thenReturn("14:00"); String[] tags = {"environment"}; when(request.getParameter("all-tags")).thenReturn(Utils.convertToJson(tags)); // Post event to Datastore. testEventServlet.doPost(request, response); // Retrieve the Entity posted to Datastore. DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Entity postedEntity = ds.prepare(new Query("Event")).asSingleEntity(); // Assert the Entity posted to Datastore has empty properties for the // parameters that were not in the request. assertEquals("", postedEntity.getProperty("endTime")); assertEquals("", postedEntity.getProperty("coverPhoto")); } @Test public void postEventWithoutLoggingIn() throws IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); TestingUtil.mockFirebase(request, ""); when(request.getParameter("event-name")).thenReturn("Lake Clean Up"); when(request.getParameter("event-description")).thenReturn("We're cleaning up the lake"); when(request.getParameter("street-address")).thenReturn("678 Lakeview Way"); when(request.getParameter("city")).thenReturn("Lakeside"); when(request.getParameter("state")).thenReturn("Michigan"); when(request.getParameter("date")).thenReturn("2020-05-17"); when(request.getParameter("start-time")).thenReturn("14:00"); String[] tags = {"environment"}; when(request.getParameter("all-tags")).thenReturn(Utils.convertToJson(tags)); try { testEventServlet.doPost(request, response); // doPost should throw an error because it is not logged in fail(); } catch (IOException e) { // no entities should have been posted DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); assertEquals(0, ds.prepare(new Query("Event")).countEntities()); } } private Entity createEntity() { // Create what the event Entity should look like, but do not post to // it to Datastore. Entity entity = new Entity("Event"); entity.setProperty("eventName", "Lake Clean Up"); entity.setProperty("eventDescription", "We're cleaning up the lake"); entity.setProperty("address", "678 Lakeview Way, Lakeside, Michigan"); entity.setProperty("date", "Sunday, May 17, 2020"); entity.setProperty("startTime", "2:00 PM"); entity.setProperty("endTime", "3:00 PM"); entity.setProperty("coverPhoto", "/img-2030121"); entity.setProperty("creator", "[email protected]"); entity.setProperty("attendeeCount", 0L); entity.setProperty("eventKey", "agR0ZXN0cgsLEgVFdmVudBgBDA"); entity.setProperty("unformattedStart", "14:00"); entity.setProperty("unformattedEnd", "15:00"); entity.setProperty("unformattedDate", "2020-05-17"); // Convert tags and set tag property. String[] tagsArr = {"environment"}; String tagsStr = Utils.convertToJson(tagsArr); Gson gson = new Gson(); List<String> tags = gson.fromJson(tagsStr, new TypeToken<ArrayList<String>>() {}.getType()); entity.setIndexedProperty("tags", tags); // Retrieve keywords and set keyword properties. Map<String, Integer> keywords = KeywordSearchServlet.getKeywords("Lake Clean Up", "We're cleaning up the lake"); entity.setProperty("keywords", KeywordSearchServlet.getKeywordMapKeys(keywords)); entity.setProperty("keywordsValues", KeywordSearchServlet.getKeywordMapValues(keywords)); return entity; } private void assertEntitiesEqual(Entity goal, Entity resultEntity) { Set<String> goalProperties = goal.getProperties().keySet(); Set<String> resultProperties = resultEntity.getProperties().keySet(); assertEquals(goalProperties.size(), resultProperties.size()); for (String s : goalProperties) { if (s.equals("keywordsValues")) { assertTrue( ((goal.getProperty(s)).toString()).equals((resultEntity.getProperty(s)).toString())); } else { assertEquals(goal.getProperty(s), resultEntity.getProperty(s)); } } } }
src/test/java/com/google/sps/EventServletTest.java
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps; import static com.google.appengine.api.datastore.FetchOptions.Builder.withLimit; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.*; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Query; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.google.sps.servlets.EventServlet; import com.google.sps.servlets.KeywordSearchServlet; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; @PowerMockIgnore("okhttp3.*") @RunWith(PowerMockRunner.class) @SuppressStaticInitializationFor({"com.google.sps.Firebase"}) @PrepareForTest({Firebase.class}) public final class EventServletTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()); private EventServlet testEventServlet; @Before public void setUp() throws IOException { helper.setUp(); testEventServlet = new EventServlet(); } @After public void tearDown() { helper.tearDown(); } @Test public void postOneEventToDatastore() throws IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); TestingUtil.mockFirebase(request, "[email protected]"); // Add a mock request to pass as a parameter to doPost. when(request.getParameter("event-name")).thenReturn("Lake Clean Up"); when(request.getParameter("event-description")).thenReturn("We're cleaning up the lake"); when(request.getParameter("street-address")).thenReturn("678 Lakeview Way"); when(request.getParameter("city")).thenReturn("Lakeside"); when(request.getParameter("state")).thenReturn("Michigan"); when(request.getParameter("date")).thenReturn("2020-05-17"); when(request.getParameter("start-time")).thenReturn("14:00"); when(request.getParameter("end-time")).thenReturn("15:00"); when(request.getParameter("cover-photo")).thenReturn("/img-2030121"); String[] tags = {"environment"}; when(request.getParameter("all-tags")).thenReturn(Utils.convertToJson(tags)); // Post event to Datastore. testEventServlet.doPost(request, response); // Assert only one Entity was posted to Datastore. DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); assertEquals(1, ds.prepare(new Query("Event")).countEntities(withLimit(10))); assertEquals(1, ds.prepare(new Query("Interaction")).countEntities(withLimit(10))); } @Test public void postMultipleEventsToDatastore() throws IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); TestingUtil.mockFirebase(request, "[email protected]"); // Add a mock request to pass as a parameter to doPost. when(request.getParameter("event-name")).thenReturn("Lake Clean Up"); when(request.getParameter("event-description")).thenReturn("We're cleaning up the lake"); when(request.getParameter("street-address")).thenReturn("678 Lakeview Way"); when(request.getParameter("city")).thenReturn("Lakeside"); when(request.getParameter("state")).thenReturn("Michigan"); when(request.getParameter("date")).thenReturn("2020-05-17"); when(request.getParameter("start-time")).thenReturn("14:00"); when(request.getParameter("end-time")).thenReturn("15:00"); when(request.getParameter("cover-photo")).thenReturn("/img-2030121"); String[] tags = {"environment"}; when(request.getParameter("all-tags")).thenReturn(Utils.convertToJson(tags)); // Post three events to Datastore. testEventServlet.doPost(request, response); testEventServlet.doPost(request, response); testEventServlet.doPost(request, response); // Assert all three Entities were posted to Datastore. DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); assertEquals(3, ds.prepare(new Query("Event")).countEntities(withLimit(10))); Iterable<Entity> interactions = ds.prepare(new Query("Interaction")).asIterable(); int size = 0; for (Entity e : interactions) { size++; assertEquals(Interactions.CREATE_SCORE, Integer.parseInt(e.getProperty("rating").toString())); assertEquals("[email protected]", e.getProperty("user").toString()); } assertEquals(3, size); } @Test public void postEventWithAllFields() throws IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); String creatorEmail = "[email protected]"; TestingUtil.mockFirebase(request, creatorEmail); // Add a mock request to pass as a parameter to doPost. when(request.getParameter("event-name")).thenReturn("Lake Clean Up"); when(request.getParameter("event-description")).thenReturn("We're cleaning up the lake"); when(request.getParameter("street-address")).thenReturn("678 Lakeview Way"); when(request.getParameter("city")).thenReturn("Lakeside"); when(request.getParameter("state")).thenReturn("Michigan"); when(request.getParameter("date")).thenReturn("2020-05-17"); when(request.getParameter("start-time")).thenReturn("14:00"); when(request.getParameter("end-time")).thenReturn("15:00"); when(request.getParameter("cover-photo")).thenReturn("/img-2030121"); String[] tagsArr = {"environment"}; String tagsStr = Utils.convertToJson(tagsArr); when(request.getParameter("all-tags")).thenReturn(tagsStr); // Post event to Datastore. testEventServlet.doPost(request, response); // Create what the event Entity should look like, but do not post to // it to Datastore. Entity goalEntity = new Entity("Event"); goalEntity.setProperty("eventName", "Lake Clean Up"); goalEntity.setProperty("eventDescription", "We're cleaning up the lake"); goalEntity.setProperty("address", "678 Lakeview Way, Lakeside, Michigan"); goalEntity.setProperty("date", "Sunday, May 17, 2020"); goalEntity.setProperty("startTime", "2:00 PM"); goalEntity.setProperty("endTime", "3:00 PM"); goalEntity.setProperty("coverPhoto", "/img-2030121"); goalEntity.setProperty("creator", creatorEmail); goalEntity.setProperty("attendeeCount", 0L); goalEntity.setProperty("eventKey", "agR0ZXN0cgsLEgVFdmVudBgBDA"); goalEntity.setProperty("unformattedStart", "14:00"); goalEntity.setProperty("unformattedEnd", "15:00"); goalEntity.setProperty("unformattedDate", "2020-05-17"); Gson gson = new Gson(); List<String> tagsList = gson.fromJson(tagsStr, new TypeToken<ArrayList<String>>() {}.getType()); goalEntity.setIndexedProperty("tags", tagsList); Map<String, Integer> keywords = KeywordSearchServlet.getKeywords("Lake Clean Up", "We're cleaning up the lake"); goalEntity.setProperty("keywords", KeywordSearchServlet.getKeywordMapKeys(keywords)); goalEntity.setProperty("keywordsValues", KeywordSearchServlet.getKeywordMapValues(keywords)); // Retrieve the Entity posted to Datastore. DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Entity postedEntity = ds.prepare(new Query("Event")).asSingleEntity(); // Assert the Entity posted to Datastore has the same properties as the // the goalEntity. assertEntitiesEqual(goalEntity, postedEntity); } @Test public void postEventWithEmptyOptionalFields() throws IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); TestingUtil.mockFirebase(request, "[email protected]"); // This mock request does not include optional fields end-time and cover-photo. when(request.getParameter("event-name")).thenReturn("Lake Clean Up"); when(request.getParameter("event-description")).thenReturn("We're cleaning up the lake"); when(request.getParameter("street-address")).thenReturn("678 Lakeview Way"); when(request.getParameter("city")).thenReturn("Lakeside"); when(request.getParameter("state")).thenReturn("Michigan"); when(request.getParameter("date")).thenReturn("2020-05-17"); when(request.getParameter("start-time")).thenReturn("14:00"); String[] tags = {"environment"}; when(request.getParameter("all-tags")).thenReturn(Utils.convertToJson(tags)); // Post event to Datastore. testEventServlet.doPost(request, response); // Retrieve the Entity posted to Datastore. DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Entity postedEntity = ds.prepare(new Query("Event")).asSingleEntity(); // Assert the Entity posted to Datastore has empty properties for the // parameters that were not in the request. assertEquals("", postedEntity.getProperty("endTime")); assertEquals("", postedEntity.getProperty("coverPhoto")); } @Test public void postEventWithoutLoggingIn() throws IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); TestingUtil.mockFirebase(request, ""); when(request.getParameter("event-name")).thenReturn("Lake Clean Up"); when(request.getParameter("event-description")).thenReturn("We're cleaning up the lake"); when(request.getParameter("street-address")).thenReturn("678 Lakeview Way"); when(request.getParameter("city")).thenReturn("Lakeside"); when(request.getParameter("state")).thenReturn("Michigan"); when(request.getParameter("date")).thenReturn("2020-05-17"); when(request.getParameter("start-time")).thenReturn("14:00"); String[] tags = {"environment"}; when(request.getParameter("all-tags")).thenReturn(Utils.convertToJson(tags)); try { testEventServlet.doPost(request, response); // doPost should throw an error because it is not logged in fail(); } catch (IOException e) { // no entities should have been posted DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); assertEquals(0, ds.prepare(new Query("Event")).countEntities()); } } private void assertEntitiesEqual(Entity goal, Entity resultEntity) { Set<String> goalProperties = goal.getProperties().keySet(); Set<String> resultProperties = resultEntity.getProperties().keySet(); assertEquals(goalProperties.size(), resultProperties.size()); for (String s : goalProperties) { if (s.equals("keywordsValues")) { assertTrue( ((goal.getProperty(s)).toString()).equals((resultEntity.getProperty(s)).toString())); } else { assertEquals(goal.getProperty(s), resultEntity.getProperty(s)); } } } }
Separate creation of entity into function
src/test/java/com/google/sps/EventServletTest.java
Separate creation of entity into function
Java
apache-2.0
12adb3848f24aa098564d8f95cf47d0835a7ce68
0
RWTH-i5-IDSG/jamocha,RWTH-i5-IDSG/jamocha
/* * Copyright 2002-2013 The Jamocha Team * * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.jamocha.org/ * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.jamocha.filter; import java.util.HashSet; import java.util.Optional; import java.util.Set; import lombok.Getter; import lombok.Setter; import lombok.Value; import org.jamocha.dn.memory.FactAddress; import org.jamocha.dn.memory.SlotAddress; import org.jamocha.dn.memory.SlotType; import org.jamocha.dn.memory.Template; import org.jamocha.dn.nodes.Node; import com.google.common.collect.Sets; /** * A Path describes an element of a condition part of a rule. It "traces" its position in the * network during construction time. * * @author Fabian Ohler <[email protected]> * @author Christoph Terwelp <[email protected]> */ public class Path { /** * {@link Template} of the path * * @return {@link Template template} of the path */ @Getter final Template template; /** * {@link Node}, the path is currently produced by * * @param currentlyLowestNode * {@link Node node}, the path is currently produced by * @return {@link Node node}, the path is currently produced by */ @Getter @Setter private Node currentlyLowestNode; /** * {@link FactAddress} identifying the fact in the current {@link Node node} * * @param factAddressInCurrentlyLowestNode * {@link FactAddress fact address} identifying the fact in the current {@link Node * node} * @return {@link FactAddress fact address} identifying the fact in the current {@link Node * node} */ @Getter @Setter private FactAddress factAddressInCurrentlyLowestNode; /** * Set of paths this path has been joined with (including itself) * * @param joinedWith * set of paths this path has been joined with (including itself) * @return set of paths this path has been joined with (including itself) */ @Getter @Setter private Set<Path> joinedWith; private Optional<Backup> backup = Optional.empty(); @Value private class Backup { Node currentlyLowestNode; FactAddress factAddressInCurrentlyLowestNode; Set<Path> joinedWith; Backup() { this.currentlyLowestNode = Path.this.currentlyLowestNode; this.factAddressInCurrentlyLowestNode = Path.this.factAddressInCurrentlyLowestNode; this.joinedWith = Path.this.joinedWith; } } /** * Extracts the {@link SlotType} of the Slot corresponding to {@link SlotAddress addr}. * * @param addr * {@link SlotAddress slot address} of the Slot one is interested in * @return the {@link SlotType} of the Slot corresponding to the parameter given */ public SlotType getTemplateSlotType(final SlotAddress addr) { return null == addr ? SlotType.FACTADDRESS : addr.getSlotType(this.template); } /** * For all {@link Path paths} passed, this method sets their sets of joined {@link Path paths} * to contain all {@link Path paths} passed. * * @param joined * list of {@link Path paths} to set their set of joined {@link Path paths} to * contain all {@link Path paths} passed */ public static void setJoinedWithForAll(final Path... joined) { final Set<Path> paths = new HashSet<>(); for (final Path path : joined) { paths.add(path); } for (final Path path : joined) { path.setJoinedWith(paths); } } public Path(final Template template, final Node currentlyLowestNode, final FactAddress factAddressInCurrentlyLowestNode, final Path... joinedWith) { super(); this.template = template; this.currentlyLowestNode = currentlyLowestNode; this.factAddressInCurrentlyLowestNode = factAddressInCurrentlyLowestNode; this.joinedWith = Sets.newHashSetWithExpectedSize(joinedWith.length); this.joinedWith.add(this); for (final Path path : joinedWith) { this.joinedWith.add(path); } } public Path(final Template template, final Path... joinedWith) { this(template, null, null, joinedWith); } @Override public String toString() { return getPathString() + " [" + template.getName() + "]"; } public String toString(final SlotAddress slot) { if (null == slot) return toString(); return getPathString() + " [" + template.getName() + "::" + template.getSlotName(slot) + "]"; } private String getPathString() { return "Path" + this.hashCode(); } public void cachedOverride(final Node currentlyLowestNode, final FactAddress factAddressInCurrentlyLowestNode, final Set<Path> joinedWith) { assert !this.backup.isPresent(); this.backup = Optional.of(new Backup()); this.currentlyLowestNode = currentlyLowestNode; this.factAddressInCurrentlyLowestNode = factAddressInCurrentlyLowestNode; this.joinedWith = joinedWith; } public void restoreCache() { assert this.backup.isPresent(); final Backup backupInstance = this.backup.get(); this.currentlyLowestNode = backupInstance.currentlyLowestNode; this.factAddressInCurrentlyLowestNode = backupInstance.factAddressInCurrentlyLowestNode; this.joinedWith = backupInstance.joinedWith; this.backup = Optional.empty(); } }
src/org/jamocha/filter/Path.java
/* * Copyright 2002-2013 The Jamocha Team * * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.jamocha.org/ * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.jamocha.filter; import java.util.HashSet; import java.util.Optional; import java.util.Set; import lombok.Getter; import lombok.Setter; import lombok.Value; import org.jamocha.dn.memory.FactAddress; import org.jamocha.dn.memory.SlotAddress; import org.jamocha.dn.memory.SlotType; import org.jamocha.dn.memory.Template; import org.jamocha.dn.nodes.Node; import com.google.common.collect.Sets; /** * A Path describes an element of a condition part of a rule. It "traces" its position in the * network during construction time. * * @author Fabian Ohler <[email protected]> * @author Christoph Terwelp <[email protected]> */ public class Path { /** * {@link Template} of the path * * @return {@link Template template} of the path */ @Getter final Template template; /** * {@link Node}, the path is currently produced by * * @param currentlyLowestNode * {@link Node node}, the path is currently produced by * @return {@link Node node}, the path is currently produced by */ @Getter @Setter private Node currentlyLowestNode; /** * {@link FactAddress} identifying the fact in the current {@link Node node} * * @param factAddressInCurrentlyLowestNode * {@link FactAddress fact address} identifying the fact in the current {@link Node * node} * @return {@link FactAddress fact address} identifying the fact in the current {@link Node * node} */ @Getter @Setter private FactAddress factAddressInCurrentlyLowestNode; /** * Set of paths this path has been joined with (including itself) * * @param joinedWith * set of paths this path has been joined with (including itself) * @return set of paths this path has been joined with (including itself) */ @Getter @Setter private Set<Path> joinedWith; private Optional<Backup> backup = Optional.empty(); @Value private class Backup { Node currentlyLowestNode; FactAddress factAddressInCurrentlyLowestNode; Set<Path> joinedWith; Backup() { this.currentlyLowestNode = Path.this.currentlyLowestNode; this.factAddressInCurrentlyLowestNode = Path.this.factAddressInCurrentlyLowestNode; this.joinedWith = Path.this.joinedWith; } } /** * Extracts the {@link SlotType} of the Slot corresponding to {@link SlotAddress addr}. * * @param addr * {@link SlotAddress slot address} of the Slot one is interested in * @return the {@link SlotType} of the Slot corresponding to the parameter given */ public SlotType getTemplateSlotType(final SlotAddress addr) { return addr.getSlotType(this.template); } /** * For all {@link Path paths} passed, this method sets their sets of joined {@link Path paths} * to contain all {@link Path paths} passed. * * @param joined * list of {@link Path paths} to set their set of joined {@link Path paths} to * contain all {@link Path paths} passed */ public static void setJoinedWithForAll(final Path... joined) { final Set<Path> paths = new HashSet<>(); for (final Path path : joined) { paths.add(path); } for (final Path path : joined) { path.setJoinedWith(paths); } } public Path(final Template template, final Node currentlyLowestNode, final FactAddress factAddressInCurrentlyLowestNode, final Path... joinedWith) { super(); this.template = template; this.currentlyLowestNode = currentlyLowestNode; this.factAddressInCurrentlyLowestNode = factAddressInCurrentlyLowestNode; this.joinedWith = Sets.newHashSetWithExpectedSize(joinedWith.length); this.joinedWith.add(this); for (final Path path : joinedWith) { this.joinedWith.add(path); } } public Path(final Template template, final Path... joinedWith) { this(template, null, null, joinedWith); } @Override public String toString() { return getPathString() + " [" + template.getName() + "]"; } public String toString(final SlotAddress slot) { if (null == slot) return toString(); return getPathString() + " [" + template.getName() + "::" + template.getSlotName(slot) + "]"; } private String getPathString() { return "Path" + this.hashCode(); } public void cachedOverride(final Node currentlyLowestNode, final FactAddress factAddressInCurrentlyLowestNode, final Set<Path> joinedWith) { assert !this.backup.isPresent(); this.backup = Optional.of(new Backup()); this.currentlyLowestNode = currentlyLowestNode; this.factAddressInCurrentlyLowestNode = factAddressInCurrentlyLowestNode; this.joinedWith = joinedWith; } public void restoreCache() { assert this.backup.isPresent(); final Backup backupInstance = this.backup.get(); this.currentlyLowestNode = backupInstance.currentlyLowestNode; this.factAddressInCurrentlyLowestNode = backupInstance.factAddressInCurrentlyLowestNode; this.joinedWith = backupInstance.joinedWith; this.backup = Optional.empty(); } }
Path::getTemplateSlotType null-safe
src/org/jamocha/filter/Path.java
Path::getTemplateSlotType null-safe
Java
apache-2.0
a63ad5364d5145fb62befda588a5f0c14caceac6
0
thinkhoon/tkhoon
package com.tkhoon.framework; public interface FrameworkConstant { String DEFAULT_CHARSET = "UTF-8"; String APP_HOME_PAGE = "app.home_page"; String APP_JSP_PATH = "app.jsp_path"; String APP_WWW_PATH = "app.www_path"; String DEFAULT_SERVLET_NAME = "default"; String JSP_SERVLET_NAME = "jsp"; String UPLOAD_SERVLET_NAME = "upload"; String FAVICON_ICO_URL = "/favicon.ico"; String UPLOAD_SERVLET_URL = "/upload.do"; String UPLOAD_BASE_PATH = "upload/"; String UPLOAD_PATH_NAME = "path"; String UPLOAD_INPUT_NAME = "file"; String UPLOAD_FILE_NAME = "file_name"; String UPLOAD_FILE_TYPE = "file_type"; String UPLOAD_FILE_SIZE = "file_size"; String PLUGIN_PACKAGE = "com.tkhoon.plugin"; }//
src/main/java/com/tkhoon/framework/FrameworkConstant.java
package com.tkhoon.framework; public interface FrameworkConstant { String DEFAULT_CHARSET = "UTF-8"; String APP_HOME_PAGE = "app.home_page"; String APP_JSP_PATH = "app.jsp_path"; String APP_WWW_PATH = "app.www_path"; String DEFAULT_SERVLET_NAME = "default"; String JSP_SERVLET_NAME = "jsp"; String UPLOAD_SERVLET_NAME = "upload"; String FAVICON_ICO_URL = "/favicon.ico"; String UPLOAD_SERVLET_URL = "/upload.do"; String UPLOAD_BASE_PATH = "upload/"; String UPLOAD_PATH_NAME = "path"; String UPLOAD_INPUT_NAME = "file"; String UPLOAD_FILE_NAME = "file_name"; String UPLOAD_FILE_TYPE = "file_type"; String UPLOAD_FILE_SIZE = "file_size"; String PLUGIN_PACKAGE = "com.tkhoon.plugin"; }//
fix bug
src/main/java/com/tkhoon/framework/FrameworkConstant.java
fix bug
Java
apache-2.0
a2c95e883b27dfe1e26945bd4643a18f6c46afdc
0
yetiz-org/hbase-utils
package org.yetiz.utils.hbase; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.commons.collections.map.UnmodifiableMap; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.reflections.Reflections; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yetiz.utils.hbase.exception.InvalidOperationException; import org.yetiz.utils.hbase.exception.TypeNotFoundException; import org.yetiz.utils.hbase.utils.ModelCallbackTask; import javax.xml.bind.DatatypeConverter; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.ByteBuffer; import java.util.*; import java.util.stream.Stream; /** * Created by yeti on 16/4/1. */ public abstract class HTableModel<T extends HTableModel> { protected static final ObjectMapper JSON_MAPPER = new ObjectMapper(new JsonFactory()); private static final HashMap<TableName, HashMap<String, Qualifier>> ModelQualifiers = new HashMap<>(); private static final HashMap<TableName, HashMap<String, Family>> ModelFamilies = new HashMap<>(); private static final HashMap<Class<? extends HTableModel>, TableName> ModelTableNameMaps = new HashMap<>(); private static final HashMap<TableName, Class<? extends HTableModel>> TableNameModelMaps = new HashMap<>(); private static final HashMap<TableName, HashMap<String, String>> ModelFQFields = new HashMap<>(); private static final Reflections REFLECTION = new Reflections(""); private static final ValueSetterPackage DEFAULT_VALUE_SETTER_PACKAGE = new ValueSetterPackage("", "", null); private static Field resultField; private static Field isResultField; private static Logger LOGGER = LoggerFactory.getLogger(HTableModel.class); static { initModelQualifier(); try { resultField = HTableModel.class.getDeclaredField("result"); isResultField = HTableModel.class.getDeclaredField("isResult"); } catch (Throwable throwable) { } } private final HashMap<String, ValueSetterPackage> setValues; private boolean isResult; private Result result = null; private boolean copy = false; public HTableModel() { isResult = false; setValues = new HashMap<>(); } /** * get <code>Qualifier</code> by method name, this is readonly map * * @param tableName * @return */ public static final Map<String, Qualifier> qualifiers(TableName tableName) { return UnmodifiableMap.decorate(ModelQualifiers.get(tableName)); } /** * get <code>Family</code> by method name, this is readonly map * * @param tableName * @return */ public static final Map<String, Family> families(TableName tableName) { return UnmodifiableMap.decorate(ModelFamilies.get(tableName)); } public static final TableName tableName(Class<? extends HTableModel> type) { return ModelTableNameMaps.get(type); } public static final Class<? extends HTableModel> modelType(TableName tableName) { return TableNameModelMaps.get(tableName); } public static final <R extends HTableModel> R newWrappedModel(TableName tableName, Result result) { try { R r = (R) TableNameModelMaps.get(tableName).newInstance(); resultField.set(r, result); isResultField.set(r, true); return r; } catch (Throwable throwable) { throw new TypeNotFoundException(throwable); } } public static final void DBDrop(HBaseClient client) { implementedModels() .parallel() .forEach(type -> { try { type.newInstance().drop(client); } catch (Throwable throwable) { } }); } private static final Stream<Class<? extends HTableModel>> implementedModels() { return REFLECTION .getSubTypesOf(HTableModel.class) .stream() .filter(type -> !Modifier.isAbstract(type.getModifiers())); } public void drop(HBaseClient client) { client.admin().deleteTable(tableName()); } public TableName tableName() { return ModelTableNameMaps.get(this.getClass()); } public static final void DBMigration(HBaseClient client) { LOGGER.info("Start migration."); implementedModels() .parallel() .forEach(type -> { try { type.newInstance().migrate(client); } catch (Throwable throwable) { } }); LOGGER.info("Migration done."); } public void migrate(HBaseClient client) { if (!client.admin().tableExists(tableName())) { client.admin().createTable(tableName()); } LOGGER.info(String.format("%s migrating...", tableName().get().getNameAsString())); ObjectNode root = JSON_MAPPER.createObjectNode(); root.put("object_name", this.getClass().getName()); HTableDescriptor descriptor = client.admin().tableDescriptor(tableName()); ArrayNode families = JSON_MAPPER.createArrayNode(); HTableDescriptor finalDescriptor = descriptor; HashMap<String, ArrayNode> familyMaps = new HashMap<>(); HashMap<String, String> familyComp = new HashMap<>(); ModelFamilies.get(tableName()).entrySet() .stream() .map(entry -> { familyMaps.put(entry.getValue().family(), familyMaps.getOrDefault(entry.getValue().family(), JSON_MAPPER.createArrayNode()) .add(JSON_MAPPER.createObjectNode() .put("field_name", entry.getKey()) .put("qualifier", ModelQualifiers.get(tableName()).get(entry.getKey()).qualifier()) .put("description", ModelQualifiers.get(tableName()).get(entry.getKey()).description())) ); familyComp.put(entry.getValue().family(), entry.getValue().compression().getName()); return entry; }) .collect(HashMap::new, (map, entry) -> { if (!map.containsKey(entry.getValue().family())) { map.put(entry.getValue().family(), entry.getValue()); } }, (map1, map2) -> map1.putAll(map2)) .entrySet() .stream() .forEach(entry -> { if (!finalDescriptor.hasFamily(HBaseClient.bytes((String) entry.getKey()))) { client .admin() .addColumnFamily(tableName(), ((Family) entry.getValue()).family(), ((Family) entry.getValue()).compression()); } }); familyMaps.entrySet() .stream() .forEach(entry -> families .add(JSON_MAPPER.createObjectNode() .put("family", entry.getKey()) .put("compression", familyComp.get(entry.getKey())) .set("qualifiers", entry.getValue())) ); root.set("families", families); descriptor = client.admin().tableDescriptor(tableName()); descriptor.setValue("description".getBytes(), root.toString().getBytes()); client.admin().updateTable(tableName(), descriptor); } private static void initModelQualifier() { implementedModels() .forEach(type -> { TableName tableName = TableName.valueOf(type.getSimpleName()); ModelTableNameMaps.put(type, tableName); TableNameModelMaps.put(tableName, type); }); implementedModels() .forEach(type -> { try { TableName tableName = type.newInstance().tableName(); List<Method> methods = methods(type, null); ModelFQFields.put(tableName, methods .stream() .collect(HashMap<String, String>::new, (map, method) -> { if (method.getAnnotation(Family.class) != null && method.getAnnotation(Qualifier.class) != null) { map.put(method.getAnnotation(Family.class).family() + "+-" + method.getAnnotation(Qualifier.class).qualifier(), method.getName()); } }, (map1, map2) -> map1.putAll(map2))); ModelQualifiers.put(tableName, methods .stream() .collect(HashMap<String, Qualifier>::new, (map, method) -> { if (method.getAnnotation(Qualifier.class) != null) { map.put(method.getName(), method.getAnnotation(Qualifier.class)); } }, (map1, map2) -> map1.putAll(map2))); ModelFamilies.put(tableName, methods .stream() .collect(HashMap<String, Family>::new, (map, method) -> { if (method.getAnnotation(Family.class) != null) { map.put(method.getName(), method.getAnnotation(Family.class)); } }, (map1, map2) -> map1.putAll(map2))); } catch (Throwable throwable) { } }); } private static final List<Field> fields(Class type, List<Field> fields) { if (fields == null) { fields = new ArrayList<>(); } fields.addAll(Arrays.asList(type.getDeclaredFields())); if (type.getSuperclass() != null) { fields = fields(type.getSuperclass(), fields); } return fields; } private static final List<Method> methods(Class type, List<Method> methods) { if (methods == null) { methods = new ArrayList<>(); } methods.addAll(Arrays.asList(type.getDeclaredMethods())); if (type.getSuperclass() != null) { methods = methods(type.getSuperclass(), methods); } return methods; } public static Get get(byte[] row) { Get get = new Get(row); return get; } public static Delete delete(byte[] row) { Delete delete = new Delete(row); return delete; } public static final byte[] byteValueFromHex(String hex) { return DatatypeConverter.parseHexBinary(hex); } public static final String hexValue(byte[] value) { return DatatypeConverter.printHexBinary(value); } public T put(HBaseClient client) { if (!isResult) { throw new InvalidOperationException("this is not result instance."); } Put put = put(result.getRow()); HBaseTable table = client.table(tableName()); table.put(put); table.close(); return (T) this; } public Put put(byte[] row) { Put put = new Put(row); if (!setValues.containsKey("row_updated_time")) { row_updated_time(System.currentTimeMillis()); } setValues.values() .stream() .forEach(pack -> put.addColumn(byteValue(pack.family), byteValue(pack.qualifier), pack.value)); return put; } @Family(family = "d") @Qualifier(qualifier = "rowudt", description = "row-updated-time") public T row_updated_time(long updated_time) { return setValue(updated_time); } protected final T setValue(long longValue) { copyResultToSetter(); String methodName = Thread.currentThread().getStackTrace()[2].getMethodName(); this.setValues.put(methodName, new ValueSetterPackage(family(methodName), qualifier(methodName), byteValue(longValue))); return (T) this; } private void copyResultToSetter() { if (!isResult) { return; } if (!copy) { copy = true; } else { return; } result.listCells() .stream() .forEach(cell -> { String family = stringValue(CellUtil.cloneFamily(cell)); String qualifier = stringValue(CellUtil.cloneQualifier(cell)); String methodName = ModelFQFields.get(tableName()) .get(family + "+-" + qualifier); if (methodName != null) { setValues.put(methodName, new ValueSetterPackage(family, qualifier, CellUtil.cloneValue(cell))); } }); } public static final String stringValue(byte[] bytes) { return new String(bytes, HBaseClient.DEFAULT_CHARSET); } private final String family(String methodName) { return ModelFamilies.get(tableName()).get(methodName).family(); } private final String qualifier(String methodName) { return ModelQualifiers.get(tableName()).get(methodName).qualifier(); } public static final byte[] byteValue(Object object) { if (object instanceof CharSequence) { return object.toString().getBytes(HBaseClient.DEFAULT_CHARSET); } if (object instanceof String) { return ((String) object).getBytes(HBaseClient.DEFAULT_CHARSET); } if (object instanceof Long) { return ByteBuffer.allocate(8).putLong((Long) object).array(); } if (object instanceof Integer) { return ByteBuffer.allocate(4).putInt((Integer) object).array(); } if (object instanceof Float) { return ByteBuffer.allocate(4).putFloat((Float) object).array(); } if (object instanceof Double) { return ByteBuffer.allocate(8).putDouble((Double) object).array(); } if (object == null) { return null; } return object.toString().getBytes(HBaseClient.DEFAULT_CHARSET); } /** * When this instance is Operation result and the result is Empty, then do * * @param task callback task * @return */ public T orThen(ModelCallbackTask<T> task) { if (isEmpty() && isResult) { task.callback((T) this); } return (T) this; } public boolean isEmpty() { return result == null || result.isEmpty(); } /** * do after previous operation * * @param task * @return */ public T then(ModelCallbackTask<T> task) { task.callback((T) this); return (T) this; } public T delete(HBaseClient client) { if (!isResult) { throw new InvalidOperationException("this is not result instance."); } HBaseTable table = client.table(tableName()); table.delete(new Delete(result.getRow())); table.close(); return (T) this; } public Delete delete() { if (!isResult) { throw new InvalidOperationException("this is not result instance."); } return new Delete(result.getRow()); } public final byte[] row() { return result.getRow(); } protected final T setValue(String string) { copyResultToSetter(); String methodName = Thread.currentThread().getStackTrace()[2].getMethodName(); this.setValues.put(methodName, new ValueSetterPackage(family(methodName), qualifier(methodName), byteValue(string))); return (T) this; } protected final T setValue(byte[] bytes) { copyResultToSetter(); String methodName = Thread.currentThread().getStackTrace()[2].getMethodName(); this.setValues.put(methodName, new ValueSetterPackage(family(methodName), qualifier(methodName), bytes)); return (T) this; } public Long row_updated_time() { return longValue(retrieveValue()); } public static final Long longValue(byte[] bytes) { return ByteBuffer.wrap(bytes).getLong(); } protected final byte[] retrieveValue() { String methodName = Thread.currentThread().getStackTrace()[2].getMethodName(); if (isResult && !copy) { return result.getValue(HBaseClient.bytes(family(methodName)), HBaseClient.bytes(qualifier(methodName))); } return setValues.getOrDefault(methodName, DEFAULT_VALUE_SETTER_PACKAGE).value; } private static class ValueSetterPackage { public String family; public String qualifier; public byte[] value; public ValueSetterPackage(String family, String qualifier, byte[] value) { this.family = family; this.qualifier = qualifier; this.value = value; } } }
src/main/java/org/yetiz/utils/hbase/HTableModel.java
package org.yetiz.utils.hbase; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.commons.collections.map.UnmodifiableMap; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.reflections.Reflections; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yetiz.utils.hbase.exception.InvalidOperationException; import org.yetiz.utils.hbase.exception.TypeNotFoundException; import org.yetiz.utils.hbase.utils.ModelCallbackTask; import javax.xml.bind.DatatypeConverter; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.ByteBuffer; import java.util.*; import java.util.stream.Stream; /** * Created by yeti on 16/4/1. */ public abstract class HTableModel<T extends HTableModel> { protected static final ObjectMapper JSON_MAPPER = new ObjectMapper(new JsonFactory()); private static final HashMap<TableName, HashMap<String, Qualifier>> ModelQualifiers = new HashMap<>(); private static final HashMap<TableName, HashMap<String, Family>> ModelFamilies = new HashMap<>(); private static final HashMap<Class<? extends HTableModel>, TableName> ModelTableNameMaps = new HashMap<>(); private static final HashMap<TableName, Class<? extends HTableModel>> TableNameModelMaps = new HashMap<>(); private static final HashMap<TableName, HashMap<String, String>> ModelFQFields = new HashMap<>(); private static final Reflections REFLECTION = new Reflections(""); private static final ValueSetterPackage DEFAULT_VALUE_SETTER_PACKAGE = new ValueSetterPackage("", "", null); private static Field resultField; private static Field isResultField; private static Logger LOGGER = LoggerFactory.getLogger(HTableModel.class); static { initModelQualifier(); try { resultField = HTableModel.class.getDeclaredField("result"); isResultField = HTableModel.class.getDeclaredField("isResult"); } catch (Throwable throwable) { } } private final HashMap<String, ValueSetterPackage> setValues; private boolean isResult; private Result result = null; private boolean copy = false; public HTableModel() { isResult = false; setValues = new HashMap<>(); } /** * get <code>Qualifier</code> by method name, this is readonly map * * @param tableName * @return */ public static final Map<String, Qualifier> qualifiers(TableName tableName) { return UnmodifiableMap.decorate(ModelQualifiers.get(tableName)); } /** * get <code>Family</code> by method name, this is readonly map * * @param tableName * @return */ public static final Map<String, Family> families(TableName tableName) { return UnmodifiableMap.decorate(ModelFamilies.get(tableName)); } public static final TableName tableName(Class<? extends HTableModel> type) { return ModelTableNameMaps.get(type); } public static final Class<? extends HTableModel> modelType(TableName tableName) { return TableNameModelMaps.get(tableName); } public static final <R extends HTableModel> R newWrappedModel(TableName tableName, Result result) { try { R r = (R) TableNameModelMaps.get(tableName).newInstance(); resultField.set(r, result); isResultField.set(r, true); return r; } catch (Throwable throwable) { throw new TypeNotFoundException(throwable); } } public static final void DBDrop(HBaseClient client) { implementedModels() .parallel() .forEach(type -> { try { type.newInstance().drop(client); } catch (Throwable throwable) { } }); } private static final Stream<Class<? extends HTableModel>> implementedModels() { return REFLECTION .getSubTypesOf(HTableModel.class) .stream() .filter(type -> !Modifier.isAbstract(type.getModifiers())); } public void drop(HBaseClient client) { client.admin().deleteTable(tableName()); } public TableName tableName() { return ModelTableNameMaps.get(this.getClass()); } public static final void DBMigration(HBaseClient client) { LOGGER.info("Start migration."); implementedModels() .parallel() .forEach(type -> { try { type.newInstance().migrate(client); } catch (Throwable throwable) { } }); LOGGER.info("Migration done."); } public void migrate(HBaseClient client) { if (!client.admin().tableExists(tableName())) { client.admin().createTable(tableName()); } LOGGER.info(String.format("%s migrating...", tableName().get().getNameAsString())); ObjectNode root = JSON_MAPPER.createObjectNode(); root.put("object_name", this.getClass().getName()); HTableDescriptor descriptor = client.admin().tableDescriptor(tableName()); ArrayNode families = JSON_MAPPER.createArrayNode(); HTableDescriptor finalDescriptor = descriptor; HashMap<String, ArrayNode> familyMaps = new HashMap<>(); HashMap<String, String> familyComp = new HashMap<>(); ModelFamilies.get(tableName()).entrySet() .stream() .map(entry -> { familyMaps.put(entry.getValue().family(), familyMaps.getOrDefault(entry.getValue().family(), JSON_MAPPER.createArrayNode()) .add(JSON_MAPPER.createObjectNode() .put("field_name", entry.getKey()) .put("qualifier", ModelQualifiers.get(tableName()).get(entry.getKey()).qualifier()) .put("description", ModelQualifiers.get(tableName()).get(entry.getKey()).description())) ); familyComp.put(entry.getValue().family(), entry.getValue().compression().getName()); return entry; }) .collect(HashMap::new, (map, entry) -> { if (!map.containsKey(entry.getValue().family())) { map.put(entry.getValue().family(), entry.getValue()); } }, (map1, map2) -> map1.putAll(map2)) .entrySet() .stream() .forEach(entry -> { if (!finalDescriptor.hasFamily(HBaseClient.bytes((String) entry.getKey()))) { client .admin() .addColumnFamily(tableName(), ((Family) entry.getValue()).family(), ((Family) entry.getValue()).compression()); } }); familyMaps.entrySet() .stream() .forEach(entry -> families .add(JSON_MAPPER.createObjectNode() .put("family", entry.getKey()) .put("compression", familyComp.get(entry.getKey())) .set("qualifiers", entry.getValue())) ); root.set("families", families); descriptor = client.admin().tableDescriptor(tableName()); descriptor.setValue("description".getBytes(), root.toString().getBytes()); client.admin().updateTable(tableName(), descriptor); } private static void initModelQualifier() { implementedModels() .forEach(type -> { TableName tableName = TableName.valueOf(type.getSimpleName()); ModelTableNameMaps.put(type, tableName); TableNameModelMaps.put(tableName, type); }); implementedModels() .forEach(type -> { try { TableName tableName = type.newInstance().tableName(); List<Method> methods = methods(type, null); ModelFQFields.put(tableName, methods .stream() .collect(HashMap<String, String>::new, (map, method) -> { if (method.getAnnotation(Family.class) != null && method.getAnnotation(Qualifier.class) != null) { map.put(method.getAnnotation(Family.class).family() + "+-" + method.getAnnotation(Qualifier.class).qualifier(), method.getName()); } }, (map1, map2) -> map1.putAll(map2))); ModelQualifiers.put(tableName, methods .stream() .collect(HashMap<String, Qualifier>::new, (map, method) -> { if (method.getAnnotation(Qualifier.class) != null) { map.put(method.getName(), method.getAnnotation(Qualifier.class)); } }, (map1, map2) -> map1.putAll(map2))); ModelFamilies.put(tableName, methods .stream() .collect(HashMap<String, Family>::new, (map, method) -> { if (method.getAnnotation(Family.class) != null) { map.put(method.getName(), method.getAnnotation(Family.class)); } }, (map1, map2) -> map1.putAll(map2))); } catch (Throwable throwable) { } }); } private static final List<Field> fields(Class type, List<Field> fields) { if (fields == null) { fields = new ArrayList<>(); } fields.addAll(Arrays.asList(type.getDeclaredFields())); if (type.getSuperclass() != null) { fields = fields(type.getSuperclass(), fields); } return fields; } private static final List<Method> methods(Class type, List<Method> methods) { if (methods == null) { methods = new ArrayList<>(); } methods.addAll(Arrays.asList(type.getDeclaredMethods())); if (type.getSuperclass() != null) { methods = methods(type.getSuperclass(), methods); } return methods; } public static Get get(byte[] row) { Get get = new Get(row); return get; } public static Delete delete(byte[] row) { Delete delete = new Delete(row); return delete; } public static final byte[] byteValueFromHex(String hex) { return DatatypeConverter.parseHexBinary(hex); } public static final String hexValue(byte[] value) { return DatatypeConverter.printHexBinary(value); } public T put(HBaseClient client) { if (!isResult) { throw new InvalidOperationException("this is not result instance."); } Put put = put(result.getRow()); HBaseTable table = client.table(tableName()); table.put(put); table.close(); return (T) this; } public Put put(byte[] row) { Put put = new Put(row); if (!setValues.containsKey("row_updated_time")) { row_updated_time(System.currentTimeMillis()); } setValues.values() .stream() .forEach(pack -> put.addColumn(byteValue(pack.family), byteValue(pack.qualifier), pack.value)); return put; } @Family(family = "d") @Qualifier(qualifier = "rowudt", description = "row-updated-time") public T row_updated_time(long updated_time) { return setValue(updated_time); } protected final T setValue(long longValue) { copyResultToSetter(); String methodName = Thread.currentThread().getStackTrace()[2].getMethodName(); this.setValues.put(methodName, new ValueSetterPackage(family(methodName), qualifier(methodName), byteValue(longValue))); return (T) this; } private void copyResultToSetter() { if (!isResult) { return; } if (!copy) { copy = true; } else { return; } result.listCells() .stream() .forEach(cell -> { String family = stringValue(CellUtil.cloneFamily(cell)); String qualifier = stringValue(CellUtil.cloneQualifier(cell)); String methodName = ModelFQFields.get(tableName()) .get(family + "+-" + qualifier); if (methodName != null) { setValues.put(methodName, new ValueSetterPackage(family, qualifier, CellUtil.cloneValue(cell))); } }); } public static final String stringValue(byte[] bytes) { return new String(bytes, HBaseClient.DEFAULT_CHARSET); } private final String family(String methodName) { return ModelFamilies.get(tableName()).get(methodName).family(); } private final String qualifier(String methodName) { return ModelQualifiers.get(tableName()).get(methodName).qualifier(); } public static final byte[] byteValue(Object object) { if (object instanceof CharSequence) { return object.toString().getBytes(HBaseClient.DEFAULT_CHARSET); } if (object instanceof String) { return ((String) object).getBytes(HBaseClient.DEFAULT_CHARSET); } if (object instanceof Long) { return ByteBuffer.allocate(8).putLong((Long) object).array(); } if (object instanceof Integer) { return ByteBuffer.allocate(4).putInt((Integer) object).array(); } if (object instanceof Float) { return ByteBuffer.allocate(4).putFloat((Float) object).array(); } if (object instanceof Double) { return ByteBuffer.allocate(8).putDouble((Double) object).array(); } if (object == null){ return null; } return object.toString().getBytes(HBaseClient.DEFAULT_CHARSET); } /** * When this instance is Operation result and the result is Empty, then do * * @param task callback task * @return */ public T orThen(ModelCallbackTask<T> task) { if (isEmpty() && isResult) { task.callback((T) this); } return (T) this; } public boolean isEmpty() { return result == null || result.isEmpty(); } /** * do after previous operation * * @param task * @return */ public T then(ModelCallbackTask<T> task) { task.callback((T) this); return (T) this; } public T delete(HBaseClient client) { if (!isResult) { throw new InvalidOperationException("this is not result instance."); } HBaseTable table = client.table(tableName()); table.delete(new Delete(result.getRow())); table.close(); return (T) this; } public Delete delete() { if (!isResult) { throw new InvalidOperationException("this is not result instance."); } return new Delete(result.getRow()); } public final byte[] row() { return result.getRow(); } protected final T setValue(String string) { copyResultToSetter(); String methodName = Thread.currentThread().getStackTrace()[2].getMethodName(); this.setValues.put(methodName, new ValueSetterPackage(family(methodName), qualifier(methodName), byteValue(string))); return (T) this; } public Long row_updated_time() { return longValue(retrieveValue()); } public static final Long longValue(byte[] bytes) { return ByteBuffer.wrap(bytes).getLong(); } protected final byte[] retrieveValue() { String methodName = Thread.currentThread().getStackTrace()[2].getMethodName(); if (isResult && !copy) { return result.getValue(HBaseClient.bytes(family(methodName)), HBaseClient.bytes(qualifier(methodName))); } return setValues.getOrDefault(methodName, DEFAULT_VALUE_SETTER_PACKAGE).value; } private static class ValueSetterPackage { public String family; public String qualifier; public byte[] value; public ValueSetterPackage(String family, String qualifier, byte[] value) { this.family = family; this.qualifier = qualifier; this.value = value; } } }
add setValue of byte[]
src/main/java/org/yetiz/utils/hbase/HTableModel.java
add setValue of byte[]
Java
apache-2.0
71ba60622338b6314d2628c45516c19c4ef208ca
0
gastaldi/AsciidocFX,LightGuard/AsciidocFX,asciidocfx/AsciidocFX,LightGuard/AsciidocFX,jaredmorgs/AsciidocFX,gastaldi/AsciidocFX,jaredmorgs/AsciidocFX,asciidocfx/AsciidocFX,gastaldi/AsciidocFX,jaredmorgs/AsciidocFX,asciidocfx/AsciidocFX,lefou/AsciidocFX,asciidocfx/AsciidocFX,LightGuard/AsciidocFX,lefou/AsciidocFX
package com.kodcu.service; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.concurrent.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.security.CodeSource; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; /** * Created by usta on 25.07.2014. */ public class DocoJarExtractorService { private static Logger logger = LoggerFactory.getLogger(DocoJarExtractorService.class); public static void extract() { Path userDir = Paths.get(System.getProperty("user.dir")); if (Files.exists(userDir.resolve("doco/.doco.cache"))) return; Task<Void> task = new Task<Void>() { @Override protected Void call() throws Exception { logger.debug("***Doco extraction started***"); // // CodeSource codeSource = DocoJarExtractorService.class.getProtectionDomain().getCodeSource(); // File jarFile = new File(codeSource.getLocation().toURI().getPath()); // String jarDir = jarFile.getPath(); String jarDir = getClass().getResource("").getPath().split("!")[0]; JarFile zipFile = new JarFile(new File(new URI(jarDir).getPath())); Enumeration<JarEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { JarEntry ze = entries.nextElement(); if (!ze.getName().contains("doco/")) continue; Path path = userDir.resolve(ze.getName()); if (ze.isDirectory()) { Files.createDirectories(path); continue; } InputStream zin = zipFile.getInputStream(ze); try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();) { for (int c = zin.read(); c != -1; c = zin.read()) { outputStream.write(c); } Files.write(path, outputStream.toByteArray(), StandardOpenOption.CREATE, TRUNCATE_EXISTING); } } Files.createFile(userDir.resolve("doco/.doco.cache")); logger.debug("***Doco extraction completed***"); return null; } }; task.exceptionProperty().addListener((observable, oldValue, newValue) -> { logger.debug(newValue.getMessage(),newValue); }); Thread thread = new Thread(task); thread.setDaemon(true); thread.start(); } }
src/main/java/com/kodcu/service/DocoJarExtractorService.java
package com.kodcu.service; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.concurrent.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.security.CodeSource; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; /** * Created by usta on 25.07.2014. */ public class DocoJarExtractorService { private static Logger logger = LoggerFactory.getLogger(DocoJarExtractorService.class); public static void extract() { Path userDir = Paths.get(System.getProperty("user.dir")); if (Files.exists(userDir.resolve("doco/.doco.cache"))) return; Task<Void> task = new Task<Void>() { @Override protected Void call() throws Exception { logger.debug("***Doco extraction started***"); // // CodeSource codeSource = DocoJarExtractorService.class.getProtectionDomain().getCodeSource(); // File jarFile = new File(codeSource.getLocation().toURI().getPath()); // String jarDir = jarFile.getPath(); String jarDir = getClass().getResource("").getPath().split("!")[0]; JarFile zipFile = new JarFile(new File(jarDir)); Enumeration<JarEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { JarEntry ze = entries.nextElement(); if (!ze.getName().contains("doco/")) continue; Path path = userDir.resolve(ze.getName()); if (ze.isDirectory()) { Files.createDirectories(path); continue; } InputStream zin = zipFile.getInputStream(ze); try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();) { for (int c = zin.read(); c != -1; c = zin.read()) { outputStream.write(c); } Files.write(path, outputStream.toByteArray(), StandardOpenOption.CREATE, TRUNCATE_EXISTING); } } Files.createFile(userDir.resolve("doco/.doco.cache")); logger.debug("***Doco extraction completed***"); return null; } }; task.exceptionProperty().addListener((observable, oldValue, newValue) -> { logger.debug(newValue.getMessage(),newValue); }); Thread thread = new Thread(task); thread.setDaemon(true); thread.start(); } }
Jar extractor update
src/main/java/com/kodcu/service/DocoJarExtractorService.java
Jar extractor update
Java
apache-2.0
f6c6a3015a163387e1f93a8c89be0cab5ea7d6f6
0
mengmoya/onos,osinstom/onos,LorenzReinhart/ONOSnew,sonu283304/onos,LorenzReinhart/ONOSnew,maheshraju-Huawei/actn,sdnwiselab/onos,opennetworkinglab/onos,gkatsikas/onos,osinstom/onos,LorenzReinhart/ONOSnew,sonu283304/onos,sdnwiselab/onos,oplinkoms/onos,kuujo/onos,mengmoya/onos,Shashikanth-Huawei/bmp,sdnwiselab/onos,donNewtonAlpha/onos,oplinkoms/onos,kuujo/onos,lsinfo3/onos,Shashikanth-Huawei/bmp,kuujo/onos,opennetworkinglab/onos,opennetworkinglab/onos,gkatsikas/onos,donNewtonAlpha/onos,donNewtonAlpha/onos,y-higuchi/onos,sonu283304/onos,VinodKumarS-Huawei/ietf96yang,Shashikanth-Huawei/bmp,opennetworkinglab/onos,VinodKumarS-Huawei/ietf96yang,sonu283304/onos,Shashikanth-Huawei/bmp,y-higuchi/onos,sdnwiselab/onos,mengmoya/onos,osinstom/onos,y-higuchi/onos,oplinkoms/onos,kuujo/onos,opennetworkinglab/onos,gkatsikas/onos,Shashikanth-Huawei/bmp,maheshraju-Huawei/actn,oplinkoms/onos,lsinfo3/onos,LorenzReinhart/ONOSnew,kuujo/onos,oplinkoms/onos,LorenzReinhart/ONOSnew,gkatsikas/onos,VinodKumarS-Huawei/ietf96yang,donNewtonAlpha/onos,donNewtonAlpha/onos,maheshraju-Huawei/actn,osinstom/onos,opennetworkinglab/onos,maheshraju-Huawei/actn,gkatsikas/onos,sdnwiselab/onos,y-higuchi/onos,VinodKumarS-Huawei/ietf96yang,y-higuchi/onos,maheshraju-Huawei/actn,VinodKumarS-Huawei/ietf96yang,sdnwiselab/onos,mengmoya/onos,lsinfo3/onos,gkatsikas/onos,osinstom/onos,lsinfo3/onos,kuujo/onos,oplinkoms/onos,mengmoya/onos,oplinkoms/onos,kuujo/onos
/* * Copyright 2015 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.cluster; import java.util.Arrays; import java.util.Collection; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Verify.verifyNotNull; import static com.google.common.base.Verify.verify; import com.google.common.base.MoreObjects; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; /** * Cluster metadata. * <p> * Metadata specifies how a ONOS cluster is constituted and is made up of the collection * of {@link org.onosproject.cluster.ControllerNode nodes} and the collection of data * {@link org.onosproject.cluster.Partition partitions}. */ public final class ClusterMetadata { // Name to use when the ClusterMetadataService is in transient state public static final String NO_NAME = ""; private String name; private Set<ControllerNode> nodes; private Set<Partition> partitions; /** * Returns a new cluster metadata builder. * @return The cluster metadata builder. */ public static Builder builder() { return new Builder(); } /** * Returns the name of the cluster. * * @return cluster name */ public String getName() { return this.name; } /** * Returns the collection of {@link org.onosproject.cluster.ControllerNode nodes} that make up the cluster. * @return cluster nodes */ public Collection<ControllerNode> getNodes() { return this.nodes; } /** * Returns the collection of {@link org.onosproject.cluster.Partition partitions} that make * up the cluster. * @return collection of partitions. */ public Collection<Partition> getPartitions() { return this.partitions; } @Override public String toString() { return MoreObjects.toStringHelper(ClusterMetadata.class) .add("name", name) .add("nodes", nodes) .add("partitions", partitions) .toString(); } @Override public int hashCode() { return Arrays.deepHashCode(new Object[] {name, nodes, partitions}); } /* * Provide a deep equality check of the cluster metadata (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object object) { if (!ClusterMetadata.class.isInstance(object)) { return false; } ClusterMetadata that = (ClusterMetadata) object; if (!this.name.equals(that.name) || this.nodes.size() != that.nodes.size() || this.partitions.size() != that.partitions.size()) { return false; } return Sets.symmetricDifference(this.nodes, that.nodes).isEmpty() && Sets.symmetricDifference(this.partitions, that.partitions).isEmpty(); } /** * Builder for a {@link ClusterMetadata} instance. */ public static class Builder { private final ClusterMetadata metadata; public Builder() { metadata = new ClusterMetadata(); } /** * Sets the cluster name, returning the cluster metadata builder for method chaining. * @param name cluster name * @return this cluster metadata builder */ public Builder withName(String name) { metadata.name = checkNotNull(name); return this; } /** * Sets the collection of cluster nodes, returning the cluster metadata builder for method chaining. * @param controllerNodes collection of cluster nodes * @return this cluster metadata builder */ public Builder withControllerNodes(Collection<ControllerNode> controllerNodes) { metadata.nodes = ImmutableSet.copyOf(checkNotNull(controllerNodes)); return this; } /** * Sets the partitions, returning the cluster metadata builder for method chaining. * @param partitions collection of partitions * @return this cluster metadata builder */ public Builder withPartitions(Collection<Partition> partitions) { metadata.partitions = ImmutableSet.copyOf(checkNotNull(partitions)); return this; } /** * Builds the cluster metadata. * @return cluster metadata * @throws com.google.common.base.VerifyException VerifyException if the metadata is misconfigured */ public ClusterMetadata build() { verifyMetadata(); return metadata; } /** * Validates the constructed metadata for semantic correctness. * @throws VerifyException if the metadata is misconfigured. */ private void verifyMetadata() { verifyNotNull(metadata.getName(), "Cluster name must be specified"); verify(CollectionUtils.isNotEmpty(metadata.getNodes()), "Cluster nodes must be specified"); verify(CollectionUtils.isNotEmpty(metadata.getPartitions()), "Cluster partitions must be specified"); // verify that partitions are constituted from valid cluster nodes. boolean validPartitions = Collections2.transform(metadata.getNodes(), ControllerNode::id) .containsAll(metadata.getPartitions() .stream() .flatMap(r -> r.getMembers().stream()) .collect(Collectors.toSet())); verify(validPartitions, "Partition locations must be valid cluster nodes"); } } }
core/api/src/main/java/org/onosproject/cluster/ClusterMetadata.java
/* * Copyright 2015 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.cluster; import java.util.Arrays; import java.util.Collection; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Verify.verifyNotNull; import static com.google.common.base.Verify.verify; import com.google.common.base.MoreObjects; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; /** * Cluster metadata. * <p> * Metadata specifies how a ONOS cluster is constituted and is made up of the collection * of {@link org.onosproject.cluster.ControllerNode nodes} and the collection of data * {@link org.onosproject.cluster.Partition partitions}. */ public final class ClusterMetadata { // Name to use when the ClusterMetadataService is in transient state public static final String NO_NAME = ""; private String name; private Set<ControllerNode> nodes; private Set<Partition> partitions; /** * Returns a new cluster metadata builder. * @return The cluster metadata builder. */ public static Builder builder() { return new Builder(); } /** * Returns the name of the cluster. * * @return cluster name */ public String getName() { return this.name; } /** * Returns the collection of {@link org.onosproject.cluster.ControllerNode nodes} that make up the cluster. * @return cluster nodes */ public Collection<ControllerNode> getNodes() { return this.nodes; } /** * Returns the collection of {@link org.onosproject.cluster.Partition partitions} that make * up the cluster. * @return collection of partitions. */ public Collection<Partition> getPartitions() { return this.partitions; } @Override public String toString() { return MoreObjects.toStringHelper(ClusterMetadata.class) .add("name", name) .add("nodes", nodes) .add("partitions", partitions) .toString(); } @Override public int hashCode() { return Arrays.deepHashCode(new Object[] {name, nodes, partitions}); } /* * Provide a deep equality check of the cluster metadata (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object object) { if (!ClusterMetadata.class.isInstance(object)) { return false; } ClusterMetadata that = (ClusterMetadata) object; if (!this.name.equals(that.name) || this.nodes.size() != that.nodes.size() || this.partitions.size() != that.partitions.size()) { return false; } return Sets.symmetricDifference(this.nodes, that.nodes).isEmpty() && Sets.symmetricDifference(this.partitions, that.partitions).isEmpty(); } /** * Builder for a {@link ClusterMetadata} instance. */ public static class Builder { private final ClusterMetadata metadata; public Builder() { metadata = new ClusterMetadata(); } /** * Sets the cluster name, returning the cluster metadata builder for method chaining. * @param name cluster name * @return this cluster metadata builder */ public Builder withName(String name) { metadata.name = checkNotNull(name); return this; } /** * Sets the collection of cluster nodes, returning the cluster metadata builder for method chaining. * @param controllerNodes collection of cluster nodes * @return this cluster metadata builder */ public Builder withControllerNodes(Collection<ControllerNode> controllerNodes) { metadata.nodes = ImmutableSet.copyOf(checkNotNull(controllerNodes)); return this; } /** * Sets the partitions, returning the cluster metadata builder for method chaining. * @param partitions collection of partitions * @return this cluster metadata builder */ public Builder withPartitions(Collection<Partition> partitions) { metadata.partitions = ImmutableSet.copyOf(checkNotNull(partitions)); return this; } /** * Builds the cluster metadata. * @return cluster metadata * @throws com.google.common.base.VerifyException VerifyException if the metadata is misconfigured */ public ClusterMetadata build() { verifyMetadata(); return metadata; } /** * Validates the constructed metadata for semantic correctness. * @throws VerifyException if the metadata is misconfigured. */ private void verifyMetadata() { verifyNotNull(metadata.getName(), "Cluster name must be specified"); verify(CollectionUtils.isEmpty(metadata.getNodes()), "Cluster nodes must be specified"); verify(CollectionUtils.isEmpty(metadata.getPartitions()), "Cluster partitions must be specified"); // verify that partitions are constituted from valid cluster nodes. boolean validPartitions = Collections2.transform(metadata.getNodes(), ControllerNode::id) .containsAll(metadata.getPartitions() .stream() .flatMap(r -> r.getMembers().stream()) .collect(Collectors.toSet())); verify(validPartitions, "Partition locations must be valid cluster nodes"); } } }
Fix incorrect input verification check in ClusterMetadata Change-Id: I921ae8a8ba8c35bd91f27d2d1d985096f023c211
core/api/src/main/java/org/onosproject/cluster/ClusterMetadata.java
Fix incorrect input verification check in ClusterMetadata
Java
apache-2.0
916c472e248a107eec051797dbbf375ef1340d11
0
imay/palo,imay/palo,imay/palo,imay/palo,imay/palo,imay/palo
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.apache.doris.common.util; import org.apache.doris.analysis.DateLiteral; import org.apache.doris.catalog.AggregateType; import org.apache.doris.catalog.Column; import org.apache.doris.catalog.DataProperty; import org.apache.doris.catalog.Partition; import org.apache.doris.catalog.PrimitiveType; import org.apache.doris.catalog.Type; import org.apache.doris.common.AnalysisException; import org.apache.doris.common.Config; import org.apache.doris.common.Pair; import org.apache.doris.system.SystemInfoService; import org.apache.doris.thrift.TStorageMedium; import org.apache.doris.thrift.TStorageType; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Sets; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.List; import java.util.Map; import java.util.Set; public class PropertyAnalyzer { private static final Logger LOG = LogManager.getLogger(PropertyAnalyzer.class); private static final String COMMA_SEPARATOR = ","; public static final String PROPERTIES_SHORT_KEY = "short_key"; public static final String PROPERTIES_REPLICATION_NUM = "replication_num"; public static final String PROPERTIES_STORAGE_TYPE = "storage_type"; public static final String PROPERTIES_STORAGE_MEDIUM = "storage_medium"; public static final String PROPERTIES_STORAGE_COLDOWN_TIME = "storage_cooldown_time"; // for 1.x -> 2.x migration public static final String PROPERTIES_VERSION_INFO = "version_info"; // for restore public static final String PROPERTIES_SCHEMA_VERSION = "schema_version"; public static final String PROPERTIES_BF_COLUMNS = "bloom_filter_columns"; public static final String PROPERTIES_BF_FPP = "bloom_filter_fpp"; private static final double MAX_FPP = 0.05; private static final double MIN_FPP = 0.0001; public static final String PROPERTIES_KUDU_MASTER_ADDRS = "kudu_master_addrs"; public static final String PROPERTIES_COLUMN_SEPARATOR = "column_separator"; public static final String PROPERTIES_LINE_DELIMITER = "line_delimiter"; public static final String PROPERTIES_COLOCATE_WITH = "colocate_with"; public static DataProperty analyzeDataProperty(Map<String, String> properties, DataProperty oldDataProperty) throws AnalysisException { DataProperty dataProperty = oldDataProperty; if (properties == null) { return dataProperty; } TStorageMedium storageMedium = null; long coolDownTimeStamp = DataProperty.MAX_COOLDOWN_TIME_MS; boolean hasMedium = false; boolean hasCooldown = false; for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (!hasMedium && key.equalsIgnoreCase(PROPERTIES_STORAGE_MEDIUM)) { hasMedium = true; if (value.equalsIgnoreCase(TStorageMedium.SSD.name())) { storageMedium = TStorageMedium.SSD; } else if (value.equalsIgnoreCase(TStorageMedium.HDD.name())) { storageMedium = TStorageMedium.HDD; } else { throw new AnalysisException("Invalid storage medium: " + value); } } else if (!hasCooldown && key.equalsIgnoreCase(PROPERTIES_STORAGE_COLDOWN_TIME)) { hasCooldown = true; DateLiteral dateLiteral = new DateLiteral(value, Type.DATETIME); coolDownTimeStamp = dateLiteral.getLongValue(); } } // end for properties if (!hasCooldown && !hasMedium) { return dataProperty; } properties.remove(PROPERTIES_STORAGE_MEDIUM); properties.remove(PROPERTIES_STORAGE_COLDOWN_TIME); if (hasCooldown && !hasMedium) { throw new AnalysisException("Invalid data property. storage medium property is not found"); } if (storageMedium == TStorageMedium.HDD && hasCooldown) { throw new AnalysisException("Can not assign cooldown timestamp to HDD storage medium"); } long currentTimeMs = System.currentTimeMillis(); if (storageMedium == TStorageMedium.SSD && hasCooldown) { if (coolDownTimeStamp <= currentTimeMs) { throw new AnalysisException("Cooldown time should later than now"); } } if (storageMedium == TStorageMedium.SSD && !hasCooldown) { // set default cooldown time coolDownTimeStamp = currentTimeMs + Config.storage_cooldown_second * 1000L; } Preconditions.checkNotNull(storageMedium); return new DataProperty(storageMedium, coolDownTimeStamp); } public static short analyzeShortKeyColumnCount(Map<String, String> properties) throws AnalysisException { short shortKeyColumnCount = (short) -1; if (properties != null && properties.containsKey(PROPERTIES_SHORT_KEY)) { // check and use speciefied short key try { shortKeyColumnCount = Short.valueOf(properties.get(PROPERTIES_SHORT_KEY)); } catch (NumberFormatException e) { throw new AnalysisException("Short key: " + e.getMessage()); } if (shortKeyColumnCount <= 0) { throw new AnalysisException("Short key column count should larger than 0."); } properties.remove(PROPERTIES_SHORT_KEY); } return shortKeyColumnCount; } public static Short analyzeReplicationNum(Map<String, String> properties, short oldReplicationNum) throws AnalysisException { Short replicationNum = oldReplicationNum; if (properties != null && properties.containsKey(PROPERTIES_REPLICATION_NUM)) { try { replicationNum = Short.valueOf(properties.get(PROPERTIES_REPLICATION_NUM)); } catch (Exception e) { throw new AnalysisException(e.getMessage()); } if (replicationNum <= 0) { throw new AnalysisException("Replication num should larger than 0. (suggested 3)"); } properties.remove(PROPERTIES_REPLICATION_NUM); } return replicationNum; } public static String analyzeColumnSeparator(Map<String, String> properties, String oldColumnSeparator) { String columnSeparator = oldColumnSeparator; if (properties != null && properties.containsKey(PROPERTIES_COLUMN_SEPARATOR)) { columnSeparator = properties.get(PROPERTIES_COLUMN_SEPARATOR); properties.remove(PROPERTIES_COLUMN_SEPARATOR); } return columnSeparator; } public static String analyzeLineDelimiter(Map<String, String> properties, String oldLineDelimiter) { String lineDelimiter = oldLineDelimiter; if (properties != null && properties.containsKey(PROPERTIES_LINE_DELIMITER)) { lineDelimiter = properties.get(PROPERTIES_LINE_DELIMITER); properties.remove(PROPERTIES_LINE_DELIMITER); } return lineDelimiter; } public static TStorageType analyzeStorageType(Map<String, String> properties) throws AnalysisException { // default is COLUMN TStorageType tStorageType = TStorageType.COLUMN; if (properties != null && properties.containsKey(PROPERTIES_STORAGE_TYPE)) { String storageType = properties.get(PROPERTIES_STORAGE_TYPE); if (storageType.equalsIgnoreCase(TStorageType.COLUMN.name())) { tStorageType = TStorageType.COLUMN; } else { throw new AnalysisException("Invalid storage type: " + storageType); } properties.remove(PROPERTIES_STORAGE_TYPE); } return tStorageType; } public static Pair<Long, Long> analyzeVersionInfo(Map<String, String> properties) throws AnalysisException { Pair<Long, Long> versionInfo = new Pair<>(Partition.PARTITION_INIT_VERSION, Partition.PARTITION_INIT_VERSION_HASH); if (properties != null && properties.containsKey(PROPERTIES_VERSION_INFO)) { String versionInfoStr = properties.get(PROPERTIES_VERSION_INFO); String[] versionInfoArr = versionInfoStr.split(COMMA_SEPARATOR); if (versionInfoArr.length == 2) { try { versionInfo.first = Long.parseLong(versionInfoArr[0]); versionInfo.second = Long.parseLong(versionInfoArr[1]); } catch (NumberFormatException e) { throw new AnalysisException("version info number format error"); } } else { throw new AnalysisException("version info format error. format: version,version_hash"); } properties.remove(PROPERTIES_VERSION_INFO); } return versionInfo; } public static int analyzeSchemaVersion(Map<String, String> properties) throws AnalysisException { int schemaVersion = 0; if (properties != null && properties.containsKey(PROPERTIES_SCHEMA_VERSION)) { String schemaVersionStr = properties.get(PROPERTIES_SCHEMA_VERSION); try { schemaVersion = Integer.valueOf(schemaVersionStr); } catch (Exception e) { throw new AnalysisException("schema version format error"); } properties.remove(PROPERTIES_SCHEMA_VERSION); } return schemaVersion; } public static Set<String> analyzeBloomFilterColumns(Map<String, String> properties, List<Column> columns) throws AnalysisException { Set<String> bfColumns = null; if (properties != null && properties.containsKey(PROPERTIES_BF_COLUMNS)) { bfColumns = Sets.newHashSet(); String bfColumnsStr = properties.get(PROPERTIES_BF_COLUMNS); if (Strings.isNullOrEmpty(bfColumnsStr)) { return bfColumns; } String[] bfColumnArr = bfColumnsStr.split(COMMA_SEPARATOR); Set<String> bfColumnSet = Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER); for (String bfColumn : bfColumnArr) { bfColumn = bfColumn.trim(); boolean found = false; for (Column column : columns) { if (column.getName().equalsIgnoreCase(bfColumn)) { PrimitiveType type = column.getDataType(); // tinyint/float/double columns don't support // key columns and none/replace aggregate non-key columns support if (type == PrimitiveType.TINYINT || type == PrimitiveType.FLOAT || type == PrimitiveType.DOUBLE) { throw new AnalysisException(type + " is not supported in bloom filter index. " + "invalid column: " + bfColumn); } else if (column.isKey() || column.getAggregationType() == AggregateType.NONE || column.getAggregationType() == AggregateType.REPLACE) { if (!bfColumnSet.add(bfColumn)) { throw new AnalysisException("Reduplicated bloom filter column: " + bfColumn); } bfColumns.add(column.getName()); found = true; break; } else { // althrough the implemention supports bf for replace non-key column, // for simplicity and unity, we don't expose that to user. throw new AnalysisException("Bloom filter index only used in columns of DUP_KEYS table or " + "key columns of UNIQUE_KEYS/AGG_KEYS table. invalid column: " + bfColumn); } } } if (!found) { throw new AnalysisException("Bloom filter column does not exist in table. invalid column: " + bfColumn); } } properties.remove(PROPERTIES_BF_COLUMNS); } return bfColumns; } public static double analyzeBloomFilterFpp(Map<String, String> properties) throws AnalysisException { double bfFpp = 0; if (properties != null && properties.containsKey(PROPERTIES_BF_FPP)) { String bfFppStr = properties.get(PROPERTIES_BF_FPP); try { bfFpp = Double.parseDouble(bfFppStr); } catch (NumberFormatException e) { throw new AnalysisException("Bloom filter fpp is not Double"); } // check range if (bfFpp < MIN_FPP || bfFpp > MAX_FPP) { throw new AnalysisException("Bloom filter fpp should in [" + MIN_FPP + ", " + MAX_FPP + "]"); } properties.remove(PROPERTIES_BF_FPP); } return bfFpp; } public static String analyzeKuduMasterAddr(Map<String, String> properties, String kuduMasterAddr) throws AnalysisException { String returnAddr = kuduMasterAddr; if (properties != null && properties.containsKey(PROPERTIES_KUDU_MASTER_ADDRS)) { String addrsStr = properties.get(PROPERTIES_KUDU_MASTER_ADDRS); String[] addrArr = addrsStr.split(","); if (addrArr.length == 0) { throw new AnalysisException("Kudu master address is set empty"); } returnAddr = ""; for (int i = 0; i < addrArr.length; i++) { Pair<String, Integer> hostPort = SystemInfoService.validateHostAndPort(addrArr[i]); returnAddr += hostPort.first + ":" + hostPort.second + ","; } // remove last comma returnAddr = returnAddr.substring(0, returnAddr.length() - 1); properties.remove(PROPERTIES_KUDU_MASTER_ADDRS); } return returnAddr; } public static String analyzeColocate(Map<String, String> properties) throws AnalysisException { String colocateTable = null; if (properties != null && properties.containsKey(PROPERTIES_COLOCATE_WITH)) { colocateTable = properties.get(PROPERTIES_COLOCATE_WITH); properties.remove(PROPERTIES_COLOCATE_WITH); } return colocateTable; } }
fe/src/main/java/org/apache/doris/common/util/PropertyAnalyzer.java
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.apache.doris.common.util; import org.apache.doris.analysis.DateLiteral; import org.apache.doris.catalog.AggregateType; import org.apache.doris.catalog.Column; import org.apache.doris.catalog.DataProperty; import org.apache.doris.catalog.Partition; import org.apache.doris.catalog.PrimitiveType; import org.apache.doris.catalog.Type; import org.apache.doris.common.AnalysisException; import org.apache.doris.common.Config; import org.apache.doris.common.Pair; import org.apache.doris.system.SystemInfoService; import org.apache.doris.thrift.TStorageMedium; import org.apache.doris.thrift.TStorageType; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Sets; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.List; import java.util.Map; import java.util.Set; public class PropertyAnalyzer { private static final Logger LOG = LogManager.getLogger(PropertyAnalyzer.class); private static final String COMMA_SEPARATOR = ","; public static final String PROPERTIES_SHORT_KEY = "short_key"; public static final String PROPERTIES_REPLICATION_NUM = "replication_num"; public static final String PROPERTIES_STORAGE_TYPE = "storage_type"; public static final String PROPERTIES_STORAGE_MEDIUM = "storage_medium"; public static final String PROPERTIES_STORAGE_COLDOWN_TIME = "storage_cooldown_time"; // for 1.x -> 2.x migration public static final String PROPERTIES_VERSION_INFO = "version_info"; // for restore public static final String PROPERTIES_SCHEMA_VERSION = "schema_version"; public static final String PROPERTIES_BF_COLUMNS = "bloom_filter_columns"; public static final String PROPERTIES_BF_FPP = "bloom_filter_fpp"; private static final double MAX_FPP = 0.05; private static final double MIN_FPP = 0.0001; public static final String PROPERTIES_KUDU_MASTER_ADDRS = "kudu_master_addrs"; public static final String PROPERTIES_COLUMN_SEPARATOR = "column_separator"; public static final String PROPERTIES_LINE_DELIMITER = "line_delimiter"; public static final String PROPERTIES_COLOCATE_WITH = "colocate_with"; public static DataProperty analyzeDataProperty(Map<String, String> properties, DataProperty oldDataProperty) throws AnalysisException { DataProperty dataProperty = oldDataProperty; if (properties == null) { return dataProperty; } TStorageMedium storageMedium = null; long coolDownTimeStamp = DataProperty.MAX_COOLDOWN_TIME_MS; boolean hasMedium = false; boolean hasCooldown = false; for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (!hasMedium && key.equalsIgnoreCase(PROPERTIES_STORAGE_MEDIUM)) { hasMedium = true; if (value.equalsIgnoreCase(TStorageMedium.SSD.name())) { storageMedium = TStorageMedium.SSD; } else if (value.equalsIgnoreCase(TStorageMedium.HDD.name())) { storageMedium = TStorageMedium.HDD; } else { throw new AnalysisException("Invalid storage medium: " + value); } } else if (!hasCooldown && key.equalsIgnoreCase(PROPERTIES_STORAGE_COLDOWN_TIME)) { hasCooldown = true; DateLiteral dateLiteral = new DateLiteral(value, Type.DATETIME); coolDownTimeStamp = dateLiteral.getLongValue(); } } // end for properties if (!hasCooldown && !hasMedium) { return dataProperty; } properties.remove(PROPERTIES_STORAGE_MEDIUM); properties.remove(PROPERTIES_STORAGE_COLDOWN_TIME); if (hasCooldown && !hasMedium) { throw new AnalysisException("Invalid data property. storage medium property is not found"); } if (storageMedium == TStorageMedium.HDD && hasCooldown) { throw new AnalysisException("Can not assign cooldown timestamp to HDD storage medium"); } long currentTimeMs = System.currentTimeMillis(); if (storageMedium == TStorageMedium.SSD && hasCooldown) { if (coolDownTimeStamp <= currentTimeMs) { throw new AnalysisException("Cooldown time should later than now"); } } if (storageMedium == TStorageMedium.SSD && !hasCooldown) { // set default cooldown time coolDownTimeStamp = currentTimeMs + Config.storage_cooldown_second * 1000L; } Preconditions.checkNotNull(storageMedium); return new DataProperty(storageMedium, coolDownTimeStamp); } public static short analyzeShortKeyColumnCount(Map<String, String> properties) throws AnalysisException { short shortKeyColumnCount = (short) -1; if (properties != null && properties.containsKey(PROPERTIES_SHORT_KEY)) { // check and use speciefied short key try { shortKeyColumnCount = Short.valueOf(properties.get(PROPERTIES_SHORT_KEY)); } catch (NumberFormatException e) { throw new AnalysisException("Short key: " + e.getMessage()); } if (shortKeyColumnCount <= 0) { throw new AnalysisException("Short key column count should larger than 0."); } properties.remove(PROPERTIES_SHORT_KEY); } return shortKeyColumnCount; } public static Short analyzeReplicationNum(Map<String, String> properties, short oldReplicationNum) throws AnalysisException { Short replicationNum = oldReplicationNum; if (properties != null && properties.containsKey(PROPERTIES_REPLICATION_NUM)) { try { replicationNum = Short.valueOf(properties.get(PROPERTIES_REPLICATION_NUM)); } catch (Exception e) { throw new AnalysisException(e.getMessage()); } if (replicationNum <= 0) { throw new AnalysisException("Replication num should larger than 0. (suggested 3)"); } properties.remove(PROPERTIES_REPLICATION_NUM); } return replicationNum; } public static String analyzeColumnSeparator(Map<String, String> properties, String oldColumnSeparator) { String columnSeparator = oldColumnSeparator; if (properties != null && properties.containsKey(PROPERTIES_COLUMN_SEPARATOR)) { columnSeparator = properties.get(PROPERTIES_COLUMN_SEPARATOR); properties.remove(PROPERTIES_COLUMN_SEPARATOR); } return columnSeparator; } public static String analyzeLineDelimiter(Map<String, String> properties, String oldLineDelimiter) { String lineDelimiter = oldLineDelimiter; if (properties != null && properties.containsKey(PROPERTIES_LINE_DELIMITER)) { lineDelimiter = properties.get(PROPERTIES_LINE_DELIMITER); properties.remove(PROPERTIES_LINE_DELIMITER); } return lineDelimiter; } public static TStorageType analyzeStorageType(Map<String, String> properties) throws AnalysisException { // default is COLUMN TStorageType tStorageType = TStorageType.COLUMN; if (properties != null && properties.containsKey(PROPERTIES_STORAGE_TYPE)) { String storageType = properties.get(PROPERTIES_STORAGE_TYPE); if (storageType.equalsIgnoreCase(TStorageType.COLUMN.name())) { tStorageType = TStorageType.COLUMN; } else { throw new AnalysisException("Invalid storage type: " + storageType); } properties.remove(PROPERTIES_STORAGE_TYPE); } return tStorageType; } public static Pair<Long, Long> analyzeVersionInfo(Map<String, String> properties) throws AnalysisException { Pair<Long, Long> versionInfo = new Pair<>(Partition.PARTITION_INIT_VERSION, Partition.PARTITION_INIT_VERSION_HASH); if (properties != null && properties.containsKey(PROPERTIES_VERSION_INFO)) { String versionInfoStr = properties.get(PROPERTIES_VERSION_INFO); String[] versionInfoArr = versionInfoStr.split(COMMA_SEPARATOR); if (versionInfoArr.length == 2) { try { versionInfo.first = Long.parseLong(versionInfoArr[0]); versionInfo.second = Long.parseLong(versionInfoArr[1]); } catch (NumberFormatException e) { throw new AnalysisException("version info number format error"); } } else { throw new AnalysisException("version info format error. format: version,version_hash"); } properties.remove(PROPERTIES_VERSION_INFO); } return versionInfo; } public static int analyzeSchemaVersion(Map<String, String> properties) throws AnalysisException { int schemaVersion = 0; if (properties != null && properties.containsKey(PROPERTIES_SCHEMA_VERSION)) { String schemaVersionStr = properties.get(PROPERTIES_SCHEMA_VERSION); try { schemaVersion = Integer.valueOf(schemaVersionStr); } catch (Exception e) { throw new AnalysisException("schema version format error"); } properties.remove(PROPERTIES_SCHEMA_VERSION); } return schemaVersion; } public static Set<String> analyzeBloomFilterColumns(Map<String, String> properties, List<Column> columns) throws AnalysisException { Set<String> bfColumns = null; if (properties != null && properties.containsKey(PROPERTIES_BF_COLUMNS)) { bfColumns = Sets.newHashSet(); String bfColumnsStr = properties.get(PROPERTIES_BF_COLUMNS); if (Strings.isNullOrEmpty(bfColumnsStr)) { return bfColumns; } String[] bfColumnArr = bfColumnsStr.split(COMMA_SEPARATOR); Set<String> bfColumnSet = Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER); for (String bfColumn : bfColumnArr) { boolean found = false; for (Column column : columns) { if (column.getName().equalsIgnoreCase(bfColumn)) { PrimitiveType type = column.getDataType(); // tinyint/float/double columns don't support // key columns and none/replace aggregate non-key columns support if (type == PrimitiveType.TINYINT || type == PrimitiveType.FLOAT || type == PrimitiveType.DOUBLE) { throw new AnalysisException(type + " is not supported in bloom filter index. " + "invalid column: " + bfColumn); } else if (column.isKey() || column.getAggregationType() == AggregateType.NONE || column.getAggregationType() == AggregateType.REPLACE) { if (!bfColumnSet.add(bfColumn)) { throw new AnalysisException("Reduplicated bloom filter column: " + bfColumn); } bfColumns.add(column.getName()); found = true; break; } else { // althrough the implemention supports bf for replace non-key column, // for simplicity and unity, we don't expose that to user. throw new AnalysisException("Bloom filter index only used in columns of DUP_KEYS table or " + "key columns of UNIQUE_KEYS/AGG_KEYS table. invalid column: " + bfColumn); } } } if (!found) { throw new AnalysisException("Bloom filter column does not exist in table. invalid column: " + bfColumn); } } properties.remove(PROPERTIES_BF_COLUMNS); } return bfColumns; } public static double analyzeBloomFilterFpp(Map<String, String> properties) throws AnalysisException { double bfFpp = 0; if (properties != null && properties.containsKey(PROPERTIES_BF_FPP)) { String bfFppStr = properties.get(PROPERTIES_BF_FPP); try { bfFpp = Double.parseDouble(bfFppStr); } catch (NumberFormatException e) { throw new AnalysisException("Bloom filter fpp is not Double"); } // check range if (bfFpp < MIN_FPP || bfFpp > MAX_FPP) { throw new AnalysisException("Bloom filter fpp should in [" + MIN_FPP + ", " + MAX_FPP + "]"); } properties.remove(PROPERTIES_BF_FPP); } return bfFpp; } public static String analyzeKuduMasterAddr(Map<String, String> properties, String kuduMasterAddr) throws AnalysisException { String returnAddr = kuduMasterAddr; if (properties != null && properties.containsKey(PROPERTIES_KUDU_MASTER_ADDRS)) { String addrsStr = properties.get(PROPERTIES_KUDU_MASTER_ADDRS); String[] addrArr = addrsStr.split(","); if (addrArr.length == 0) { throw new AnalysisException("Kudu master address is set empty"); } returnAddr = ""; for (int i = 0; i < addrArr.length; i++) { Pair<String, Integer> hostPort = SystemInfoService.validateHostAndPort(addrArr[i]); returnAddr += hostPort.first + ":" + hostPort.second + ","; } // remove last comma returnAddr = returnAddr.substring(0, returnAddr.length() - 1); properties.remove(PROPERTIES_KUDU_MASTER_ADDRS); } return returnAddr; } public static String analyzeColocate(Map<String, String> properties) throws AnalysisException { String colocateTable = null; if (properties != null && properties.containsKey(PROPERTIES_COLOCATE_WITH)) { colocateTable = properties.get(PROPERTIES_COLOCATE_WITH); properties.remove(PROPERTIES_COLOCATE_WITH); } return colocateTable; } }
Fix bug in create table with BF (#907) Fixed a bug in the Bloom filter where column names could not be found due to spaces
fe/src/main/java/org/apache/doris/common/util/PropertyAnalyzer.java
Fix bug in create table with BF (#907)
Java
apache-2.0
7fec10c7c8ffd1c655ba68a6d2cda898b068503a
0
bhecquet/seleniumRobot,bhecquet/seleniumRobot,bhecquet/seleniumRobot
/** * Orignal work: Copyright 2015 www.seleniumtests.com * Modified work: Copyright 2016 www.infotel.com * Copyright 2017-2019 B.Hecquet * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seleniumtests.util.osutility; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.time.Clock; import java.time.Instant; import org.apache.log4j.Logger; import com.seleniumtests.customexception.CustomSeleniumTestsException; import com.seleniumtests.util.logging.SeleniumRobotLogger; /** * Common methods for Windows and Unix systems. */ public class OSCommand { private static final Logger logger = SeleniumRobotLogger.getLogger(OSCommand.class); private OSCommand() { // class with static methods } public static Process executeCommand(final String cmd) { Process proc; try { proc = Runtime.getRuntime().exec(cmd); return proc; } catch (IOException e1) { throw new CustomSeleniumTestsException("cannot start process: " + cmd, e1); } } public static Process executeCommand(final String[] cmd) { Process proc; try { proc = Runtime.getRuntime().exec(cmd); return proc; } catch (IOException e1) { throw new CustomSeleniumTestsException("cannot start process: " + cmd, e1); } } /** * Execute a command in command line terminal * @param cmd * @param wait for the end of the command execution * @return */ public static String executeCommandAndWait(final String[] cmd) { return executeCommandAndWait(cmd, -1, null); } /** * Execute a command in command line terminal and wait at most 'timeout' seconds * @param cmd * @param timeout number of seconds to wait for end of execution. A negative value means it will wait 30 secs * @return */ public static String executeCommandAndWait(final String[] cmd, int timeout, Charset charset) { try { Process proc = Runtime.getRuntime().exec(cmd); return waitProcessTermination(proc, timeout, charset); } catch (IOException e) { logger.error(e); } return ""; } /** * Execute a command in command line terminal * @param cmd * @param wait for the end of the command execution * @return */ public static String executeCommandAndWait(final String cmd) { return executeCommandAndWait(cmd, -1, null); } /** * Execute a command in command line terminal and wait at most 'timeout' seconds * @param cmd * @param timeout number of seconds to wait for end of execution. A negative value means it will wait 30 secs * @param charset charset used to read program output. If set to null, default charset will be used * @return */ public static String executeCommandAndWait(final String cmd, int timeout, Charset charset) { try { Process proc = Runtime.getRuntime().exec(cmd); return waitProcessTermination(proc, timeout, charset); } catch (IOException e1) { logger.error(e1); } return ""; } private static String waitProcessTermination(Process proc, int timeout, Charset charset) { try { return readOutput(proc, timeout, charset); } catch (InterruptedException e) { logger.error("Interruption: " + e.getMessage()); } catch (IOException e1) { logger.error(e1); } return ""; } private static String readOutput(Process proc, int timeout, Charset charset) throws IOException, InterruptedException { if (charset == null) { charset = OSUtility.getCharset(); } StringBuilder output = new StringBuilder(); StringBuilder error = new StringBuilder(); InputStream is = proc.getInputStream(); InputStream es = proc.getErrorStream(); Clock clock = Clock.systemUTC(); Instant end = clock.instant().plusSeconds(timeout > 0 ? timeout: 30); boolean read = false; boolean terminated = false; while (end.isAfter(clock.instant()) && (!read || !terminated)) { // be sure we read all logs produced by process, event after termination if (!proc.isAlive()) { terminated = true; } read = true; int isAvailable = is.available(); if (isAvailable > 0) { byte[] b = new byte[isAvailable]; is.read(b); output.append(new String(b, charset)); } if (es.available() > 0) { byte[] b = new byte[isAvailable]; is.read(b); error.append(new String(b, charset)); } Thread.sleep(100); } return output.toString() + '\n' + error.toString(); } }
core/src/main/java/com/seleniumtests/util/osutility/OSCommand.java
/** * Orignal work: Copyright 2015 www.seleniumtests.com * Modified work: Copyright 2016 www.infotel.com * Copyright 2017-2019 B.Hecquet * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seleniumtests.util.osutility; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.time.Clock; import java.time.Instant; import org.apache.log4j.Logger; import com.seleniumtests.customexception.CustomSeleniumTestsException; import com.seleniumtests.util.logging.SeleniumRobotLogger; /** * Common methods for Windows and Unix systems. */ public class OSCommand { private static final Logger logger = SeleniumRobotLogger.getLogger(OSCommand.class); private OSCommand() { // class with static methods } public static Process executeCommand(final String cmd) { Process proc; try { proc = Runtime.getRuntime().exec(cmd); return proc; } catch (IOException e1) { throw new CustomSeleniumTestsException("cannot start process: " + cmd, e1); } } public static Process executeCommand(final String[] cmd) { Process proc; try { proc = Runtime.getRuntime().exec(cmd); return proc; } catch (IOException e1) { throw new CustomSeleniumTestsException("cannot start process: " + cmd, e1); } } /** * Execute a command in command line terminal * @param cmd * @param wait for the end of the command execution * @return */ public static String executeCommandAndWait(final String[] cmd) { return executeCommandAndWait(cmd, -1, null); } /** * Execute a command in command line terminal and wait at most 'timeout' seconds * @param cmd * @param timeout number of seconds to wait for end of execution. A negative value means it will wait 30 secs * @return */ public static String executeCommandAndWait(final String[] cmd, int timeout, Charset charset) { try { Process proc = Runtime.getRuntime().exec(cmd); return waitProcessTermination(proc, timeout, charset); } catch (IOException e) { logger.error(e); } return ""; } /** * Execute a command in command line terminal * @param cmd * @param wait for the end of the command execution * @return */ public static String executeCommandAndWait(final String cmd) { return executeCommandAndWait(cmd, -1, null); } /** * Execute a command in command line terminal and wait at most 'timeout' seconds * @param cmd * @param timeout number of seconds to wait for end of execution. A negative value means it will wait 30 secs * @param charset charset used to read program output. If set to null, default charset will be used * @return */ public static String executeCommandAndWait(final String cmd, int timeout, Charset charset) { try { Process proc = Runtime.getRuntime().exec(cmd); return waitProcessTermination(proc, timeout, charset); } catch (IOException e1) { logger.error(e1); } return ""; } private static String waitProcessTermination(Process proc, int timeout, Charset charset) { try { return readOutput(proc, timeout, charset); } catch (InterruptedException e) { logger.error("Interruption: " + e.getMessage()); } catch (IOException e1) { logger.error(e1); } return ""; } private static String readOutput(Process proc, int timeout, Charset charset) throws IOException, InterruptedException { if (charset == null) { charset = OSUtility.getCharset(); } StringBuilder output = new StringBuilder(); StringBuilder error = new StringBuilder(); InputStream is = proc.getInputStream(); InputStream es = proc.getErrorStream(); Clock clock = Clock.systemUTC(); Instant end = clock.instant().plusSeconds(timeout > 0 ? timeout: 30); boolean read = false; while (end.isAfter(clock.instant()) && (proc.isAlive() || !read)) { read = true; int isAvailable = is.available(); if (isAvailable > 0) { byte[] b = new byte[isAvailable]; is.read(b); output.append(new String(b, charset) + "\n"); } if (es.available() > 0) { byte[] b = new byte[isAvailable]; is.read(b); error.append(new String(b, charset) + "\n"); } Thread.sleep(1); } return output.toString() + '\n' + error.toString(); } }
issue #437: correct IT
core/src/main/java/com/seleniumtests/util/osutility/OSCommand.java
issue #437: correct IT
Java
mit
b68d50f8bab7e61c4fb779c7ed61769112ac1eac
0
InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service
package org.innovateuk.ifs.project.projectdetails.controller; import org.innovateuk.ifs.application.service.CompetitionService; import org.innovateuk.ifs.application.service.OrganisationService; import org.innovateuk.ifs.commons.security.SecuredBySpring; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.project.ProjectService; import org.innovateuk.ifs.project.projectdetails.ProjectDetailsService; import org.innovateuk.ifs.project.projectdetails.viewmodel.ProjectDetailsViewModel; import org.innovateuk.ifs.project.resource.ProjectResource; import org.innovateuk.ifs.project.resource.ProjectUserResource; import org.innovateuk.ifs.user.resource.OrganisationResource; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.util.PrioritySorting; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Supplier; import java.util.stream.Collectors; import static org.innovateuk.ifs.user.resource.UserRoleType.PARTNER; import static org.innovateuk.ifs.user.resource.UserRoleType.PROJECT_MANAGER; import static org.innovateuk.ifs.util.CollectionFunctions.simpleFilter; import static org.innovateuk.ifs.util.CollectionFunctions.simpleFindFirst; /** * This controller will handle all requests that are related to project details. */ @Controller @RequestMapping("/competition/{competitionId}/project") public class ProjectDetailsController { @Autowired private CompetitionService competitionService; @Autowired private ProjectService projectService; @Autowired private ProjectDetailsService projectDetailsService; @Autowired private OrganisationService organisationService; @PreAuthorize("hasAnyAuthority('project_finance', 'comp_admin', 'support', 'innovation_lead')") @GetMapping("/{projectId}/details") public String viewProjectDetails(@PathVariable("competitionId") final Long competitionId, @PathVariable("projectId") final Long projectId, Model model, UserResource loggedInUser) { ProjectResource projectResource = projectService.getById(projectId); List<ProjectUserResource> projectUsers = projectService.getProjectUsersForProject(projectResource.getId()); OrganisationResource leadOrganisationResource = projectService.getLeadOrganisation(projectId); List<OrganisationResource> partnerOrganisations = sortedOrganisations(getPartnerOrganisations(projectUsers), leadOrganisationResource); model.addAttribute("model", new ProjectDetailsViewModel(projectResource, competitionId, null, leadOrganisationResource.getName(), getProjectManager(projectUsers).orElse(null), getFinanceContactForPartnerOrganisation(projectUsers, partnerOrganisations))); return "project/detail"; } @PreAuthorize("hasAnyAuthority('project_finance', 'ifs_administrator')") @GetMapping("/{projectId}/edit-duration") public String editProjectDuration(@PathVariable("competitionId") final Long competitionId, @PathVariable("projectId") final Long projectId, Model model, UserResource loggedInUser) { ProjectResource project = projectService.getById(projectId); CompetitionResource competition = competitionService.getById(competitionId); model.addAttribute("model", new ProjectDetailsViewModel(project, competitionId, competition.getName(), null, null, null)); return "project/edit-duration"; } @PreAuthorize("hasAnyAuthority('project_finance', 'ifs_administrator')") @PostMapping("/{projectId}/update-duration") public String updateProjectDuration(@PathVariable("competitionId") final Long competitionId, @PathVariable("projectId") final Long projectId, @RequestParam(value = "durationInMonths") final Long durationInMonths, Model model, UserResource loggedInUser) { Supplier<String> failureView = () -> "redirect:/competition/" + competitionId + "/project/" + projectId + "/edit-duration"; Supplier<String> successView = () -> "redirect:/project/" + projectId + "/finance-check"; return projectDetailsService.updateProjectDuration(projectId, durationInMonths) .handleSuccessOrFailure(failure -> failureView.get(), success -> successView.get()); } private List<OrganisationResource> getPartnerOrganisations(final List<ProjectUserResource> projectRoles) { return projectRoles.stream() .filter(uar -> uar.getRoleName().equals(PARTNER.getName())) .map(uar -> organisationService.getOrganisationById(uar.getOrganisation())) .collect(Collectors.toList()); } private List<OrganisationResource> sortedOrganisations(List<OrganisationResource> organisations, OrganisationResource lead) { return new PrioritySorting<>(organisations, lead, OrganisationResource::getName).unwrap(); } private Optional<ProjectUserResource> getProjectManager(List<ProjectUserResource> projectUsers) { return simpleFindFirst(projectUsers, pu -> PROJECT_MANAGER.getName().equals(pu.getRoleName())); } private Map<OrganisationResource, ProjectUserResource> getFinanceContactForPartnerOrganisation(List<ProjectUserResource> projectUsers, List<OrganisationResource> partnerOrganisations) { List<ProjectUserResource> financeRoles = simpleFilter(projectUsers, ProjectUserResource::isFinanceContact); Map<OrganisationResource, ProjectUserResource> organisationFinanceContactMap = new LinkedHashMap<>(); partnerOrganisations.stream().forEach(organisation -> organisationFinanceContactMap.put(organisation, simpleFindFirst(financeRoles, financeUserResource -> financeUserResource.getOrganisation().equals(organisation.getId())).orElse(null)) ); return organisationFinanceContactMap; } }
ifs-web-service/ifs-project-setup-mgt-service/src/main/java/org/innovateuk/ifs/project/projectdetails/controller/ProjectDetailsController.java
package org.innovateuk.ifs.project.projectdetails.controller; import org.innovateuk.ifs.application.service.CompetitionService; import org.innovateuk.ifs.application.service.OrganisationService; import org.innovateuk.ifs.commons.security.SecuredBySpring; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.project.ProjectService; import org.innovateuk.ifs.project.projectdetails.ProjectDetailsService; import org.innovateuk.ifs.project.projectdetails.viewmodel.ProjectDetailsViewModel; import org.innovateuk.ifs.project.resource.ProjectResource; import org.innovateuk.ifs.project.resource.ProjectUserResource; import org.innovateuk.ifs.user.resource.OrganisationResource; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.util.PrioritySorting; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Supplier; import java.util.stream.Collectors; import static org.innovateuk.ifs.user.resource.UserRoleType.PARTNER; import static org.innovateuk.ifs.user.resource.UserRoleType.PROJECT_MANAGER; import static org.innovateuk.ifs.util.CollectionFunctions.simpleFilter; import static org.innovateuk.ifs.util.CollectionFunctions.simpleFindFirst; /** * This controller will handle all requests that are related to project details. */ @Controller @RequestMapping("/competition/{competitionId}/project") @SecuredBySpring(value = "Controller", description = "TODO", securedType = ProjectDetailsController.class) @PreAuthorize("hasAnyAuthority('project_finance', 'comp_admin', 'support', 'innovation_lead')") public class ProjectDetailsController { @Autowired private CompetitionService competitionService; @Autowired private ProjectService projectService; @Autowired private ProjectDetailsService projectDetailsService; @Autowired private OrganisationService organisationService; @GetMapping("/{projectId}/details") public String viewProjectDetails(@PathVariable("competitionId") final Long competitionId, @PathVariable("projectId") final Long projectId, Model model, UserResource loggedInUser) { ProjectResource projectResource = projectService.getById(projectId); List<ProjectUserResource> projectUsers = projectService.getProjectUsersForProject(projectResource.getId()); OrganisationResource leadOrganisationResource = projectService.getLeadOrganisation(projectId); List<OrganisationResource> partnerOrganisations = sortedOrganisations(getPartnerOrganisations(projectUsers), leadOrganisationResource); model.addAttribute("model", new ProjectDetailsViewModel(projectResource, competitionId, null, leadOrganisationResource.getName(), getProjectManager(projectUsers).orElse(null), getFinanceContactForPartnerOrganisation(projectUsers, partnerOrganisations))); return "project/detail"; } @GetMapping("/{projectId}/edit-duration") public String editProjectDuration(@PathVariable("competitionId") final Long competitionId, @PathVariable("projectId") final Long projectId, Model model, UserResource loggedInUser) { ProjectResource project = projectService.getById(projectId); CompetitionResource competition = competitionService.getById(competitionId); model.addAttribute("model", new ProjectDetailsViewModel(project, competitionId, competition.getName(), null, null, null)); return "project/edit-duration"; } @PostMapping("/{projectId}/update-duration") public String updateProjectDuration(@PathVariable("competitionId") final Long competitionId, @PathVariable("projectId") final Long projectId, @RequestParam(value = "durationInMonths") final Long durationInMonths, Model model, UserResource loggedInUser) { Supplier<String> failureView = () -> "redirect:/competition/" + competitionId + "/project/" + projectId + "/edit-duration"; Supplier<String> successView = () -> "redirect:/project/" + projectId + "/finance-check"; return projectDetailsService.updateProjectDuration(projectId, durationInMonths) .handleSuccessOrFailure(failure -> failureView.get(), success -> successView.get()); } private List<OrganisationResource> getPartnerOrganisations(final List<ProjectUserResource> projectRoles) { return projectRoles.stream() .filter(uar -> uar.getRoleName().equals(PARTNER.getName())) .map(uar -> organisationService.getOrganisationById(uar.getOrganisation())) .collect(Collectors.toList()); } private List<OrganisationResource> sortedOrganisations(List<OrganisationResource> organisations, OrganisationResource lead) { return new PrioritySorting<>(organisations, lead, OrganisationResource::getName).unwrap(); } private Optional<ProjectUserResource> getProjectManager(List<ProjectUserResource> projectUsers) { return simpleFindFirst(projectUsers, pu -> PROJECT_MANAGER.getName().equals(pu.getRoleName())); } private Map<OrganisationResource, ProjectUserResource> getFinanceContactForPartnerOrganisation(List<ProjectUserResource> projectUsers, List<OrganisationResource> partnerOrganisations) { List<ProjectUserResource> financeRoles = simpleFilter(projectUsers, ProjectUserResource::isFinanceContact); Map<OrganisationResource, ProjectUserResource> organisationFinanceContactMap = new LinkedHashMap<>(); partnerOrganisations.stream().forEach(organisation -> organisationFinanceContactMap.put(organisation, simpleFindFirst(financeRoles, financeUserResource -> financeUserResource.getOrganisation().equals(organisation.getId())).orElse(null)) ); return organisationFinanceContactMap; } }
IFS-2313-Edit-Project-Duration Web Layer Security and permissions. Change-Id: If6030446d1101cf9bb0e19f4d37d983a2507a58d
ifs-web-service/ifs-project-setup-mgt-service/src/main/java/org/innovateuk/ifs/project/projectdetails/controller/ProjectDetailsController.java
IFS-2313-Edit-Project-Duration
Java
mit
509303ee35d24ff32e3b14cefc0ede845dc8815f
0
Stealth2800/MCMarkupLanguage
/** * MCMarkupLanguage - Licensed under the MIT License (MIT) * * Copyright (c) Stealth2800 <http://stealthyone.com/> * Copyright (c) contributors <https://github.com/Stealth2800/MCMarkupLanguage> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.stealthyone.mcb.mcml; import mkremins.fanciful.FancyMessage; import org.apache.commons.lang.Validate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class MCMLBuilder { static final Pattern PATTERN_EVENT = Pattern.compile("^\\((txt|ach|itm|cmd|url|scmd): *([\\S\\s]+?)\\);"); static final Pattern PATTERN_TEXT_GROUP = Pattern.compile("\\[(.+)\\]"); static final Pattern PATTERN_CHATCOLOR = Pattern.compile("&([a-f0-9l-o|kr])"); String rawText; final Map<String, Object> replacements = new HashMap<>(); final List<TempPart> parts = new ArrayList<>(); FancyMessage fancyMessage; public MCMLBuilder(String input) { this(input, null); } public MCMLBuilder(String input, Map<String, Object> replacements) { Validate.notNull(input, "Input cannot be null."); this.rawText = input; if (this.replacements != null && replacements != null) { this.replacements.putAll(replacements); } // Identify text groups int lastIndex = 0; final Matcher matcher = PATTERN_TEXT_GROUP.matcher(input); while (matcher.find()) { TempPart part = new TempPart(matcher.group(1)); if (matcher.start() > lastIndex) { // Handle ungrouped text TempPart ungroupedPart = new TempPart(rawText.substring(lastIndex, matcher.start())); parts.add(ungroupedPart); } lastIndex = matcher.end(); // Check for event int offset = rawText.length() - input.substring(lastIndex).length(); final Matcher eventMatcher = PATTERN_EVENT.matcher(input.substring(lastIndex)); if (eventMatcher.find()) { handleEvent(part, eventMatcher); lastIndex = eventMatcher.end() + offset; offset = rawText.length() - input.substring(lastIndex).length(); final Matcher secEventMatcher = PATTERN_EVENT.matcher(input.substring(lastIndex)); if (secEventMatcher.find()) { handleEvent(part, secEventMatcher); lastIndex = secEventMatcher.end() + offset; } } parts.add(part); } if (lastIndex != rawText.length()) { TempPart ungroupedPart = new TempPart(rawText.substring(lastIndex)); if (!parts.contains(ungroupedPart)) { parts.add(ungroupedPart); } } } private void handleEvent(TempPart part, Matcher matcher) { Event event = Event.parseText(this, matcher.group(1), matcher.group(2)); if (event instanceof EventClick) { part.clickEvent = event; } else { part.hoverEvent = event; } } public Object getReplacement(String key) { Validate.notNull(key, "Key cannot be null."); return replacements.get(key); } /** * @return the output FancyMessage instance. */ public FancyMessage getFancyMessage() { if (fancyMessage != null) { return fancyMessage; } fancyMessage = new FancyMessage(); for (int i = 0; i < parts.size(); i++) { TempPart part = parts.get(i); part.buildOn(fancyMessage); if (i < parts.size() - 1) { fancyMessage.then(); } } return null; } /** * @return the raw message that was inputted into this builder. */ public String getRawMessage() { return rawText; } }
src/main/java/com/stealthyone/mcb/mcml/MCMLBuilder.java
/** * MCMarkupLanguage - Licensed under the MIT License (MIT) * * Copyright (c) Stealth2800 <http://stealthyone.com/> * Copyright (c) contributors <https://github.com/Stealth2800/MCMarkupLanguage> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.stealthyone.mcb.mcml; import mkremins.fanciful.FancyMessage; import org.apache.commons.lang.Validate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class MCMLBuilder { static final Pattern PATTERN_EVENT = Pattern.compile("^\\((txt|ach|itm|cmd|url|scmd): *([\\S\\s]+?)\\);"); static final Pattern PATTERN_TEXT_GROUP = Pattern.compile("\\[(.+)\\]"); static final Pattern PATTERN_CHATCOLOR = Pattern.compile("&([a-f0-9l-o|kr])"); String rawText; final Map<String, Object> replacements = new HashMap<>(); final List<TempPart> parts = new ArrayList<>(); public MCMLBuilder(String input) { this(input, null); } public MCMLBuilder(String input, Map<String, Object> replacements) { Validate.notNull(input, "Input cannot be null."); this.rawText = input; if (this.replacements != null && replacements != null) { this.replacements.putAll(replacements); } // Identify text groups int lastIndex = 0; final Matcher matcher = PATTERN_TEXT_GROUP.matcher(input); while (matcher.find()) { TempPart part = new TempPart(matcher.group(1)); if (matcher.start() > lastIndex) { // Handle ungrouped text TempPart ungroupedPart = new TempPart(rawText.substring(lastIndex, matcher.start())); parts.add(ungroupedPart); } lastIndex = matcher.end(); // Check for event int offset = rawText.length() - input.substring(lastIndex).length(); final Matcher eventMatcher = PATTERN_EVENT.matcher(input.substring(lastIndex)); if (eventMatcher.find()) { handleEvent(part, eventMatcher); lastIndex = eventMatcher.end() + offset; offset = rawText.length() - input.substring(lastIndex).length(); final Matcher secEventMatcher = PATTERN_EVENT.matcher(input.substring(lastIndex)); if (secEventMatcher.find()) { handleEvent(part, secEventMatcher); lastIndex = secEventMatcher.end() + offset; } } parts.add(part); } if (lastIndex != rawText.length()) { TempPart ungroupedPart = new TempPart(rawText.substring(lastIndex)); if (!parts.contains(ungroupedPart)) { parts.add(ungroupedPart); } } } private void handleEvent(TempPart part, Matcher matcher) { Event event = Event.parseText(this, matcher.group(1), matcher.group(2)); if (event instanceof EventClick) { part.clickEvent = event; } else { part.hoverEvent = event; } } public Object getReplacement(String key) { Validate.notNull(key, "Key cannot be null."); return replacements.get(key); } /** * @return the output FancyMessage instance. */ public FancyMessage getFancyMessage() { FancyMessage fancyMessage = new FancyMessage(); for (int i = 0; i < parts.size(); i++) { TempPart part = parts.get(i); part.buildOn(fancyMessage); if (i < parts.size() - 1) { fancyMessage.then(); } } return null; } }
Cache the generated FancyMessage and added a method to retrieve the raw text.
src/main/java/com/stealthyone/mcb/mcml/MCMLBuilder.java
Cache the generated FancyMessage and added a method to retrieve the raw text.
Java
mit
e8d80638bed9847bbc1df66529f987a0437b9719
0
kmdouglass/Micro-Manager,kmdouglass/Micro-Manager
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.micromanager.utils; import ij.ImagePlus; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.UUID; import mmcorej.CMMCore; import mmcorej.Configuration; import mmcorej.PropertySetting; import mmcorej.TaggedImage; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * * @author arthur */ public class MDUtils { private final static SimpleDateFormat iso8601modified_ = new SimpleDateFormat("yyyy-MM-dd E HH:mm:ss Z"); public static JSONObject copy(JSONObject map) { try { return new JSONObject(map.toString()); } catch (JSONException e) { return null; } } public static int getPositionIndex(JSONObject map) throws JSONException { return map.getInt("PositionIndex"); } public static void setPositionIndex(JSONObject map, int positionIndex) throws JSONException { map.put("PositionIndex", positionIndex); } public static int getBitDepth(JSONObject map) throws JSONException { if (map.has("Summary")) return map.getJSONObject("Summary").getInt("BitDepth"); return map.getInt("BitDepth"); } public static int getWidth(JSONObject map) throws JSONException { return map.getInt("Width"); } public static void setWidth(JSONObject map, int width) throws JSONException { map.put("Width", width); } public static int getHeight(JSONObject map) throws JSONException { return map.getInt("Height"); } public static void setHeight(JSONObject map, int height) throws JSONException { map.put("Height", height); } public static int getBinning(JSONObject map) throws JSONException { return map.getInt("Binning"); } public static void setBinning(JSONObject map, int binning) throws JSONException { map.put("Binning", binning); } public static int getSliceIndex(JSONObject map) throws JSONException { if (map.has("SliceIndex")) { return map.getInt("SliceIndex"); } else { return map.getInt("Slice"); } } public static void setSliceIndex(JSONObject map, int sliceIndex) throws JSONException { map.put("SliceIndex", sliceIndex); map.put("Slice", sliceIndex); } public static int getChannelIndex(JSONObject map) throws JSONException { return map.getInt("ChannelIndex"); } public static void setChannelIndex(JSONObject map, int channelIndex) throws JSONException { map.put("ChannelIndex", channelIndex); } public static int getFrameIndex(JSONObject map) throws JSONException { if (map.has("Frame")) { return map.getInt("Frame"); } else { return map.getInt("FrameIndex"); } } public static void setFrameIndex(JSONObject map, int frameIndex) throws JSONException { map.put("Frame", frameIndex); map.put("FrameIndex", frameIndex); } public static int getNumPositions(JSONObject map) throws JSONException { if (map.has("Positions")) return map.getInt("Positions"); throw new JSONException("Positions tag not found in summary metadata"); } public static String getPositionName(JSONObject map) throws JSONException { if (map.has("PositionName") && !map.isNull("PositionName")) { return map.getString("PositionName"); } else if (map.has("PositionIndex")) { return "Pos" + map.getString("PositionIndex"); } else { return null; } } public static void setPositionName(JSONObject map, String positionName) throws JSONException { map.put("PositionName", positionName); } public static String getChannelName(JSONObject map) throws JSONException { if (map.has("Channel") && !map.isNull("Channel")) { return map.getString("Channel"); } else { return ""; } } public static int getChannelColor(JSONObject map) throws JSONException { if (map.has("ChColor") && !map.isNull("ChColor")) { return map.getInt("ChColor"); } else { return -1; } } public static String getFileName(JSONObject map) throws JSONException { if (map.has("FileName")) { return map.getString("FileName"); } else { return null; } } public static void setFileName(JSONObject map, String filename) throws JSONException { map.put("FileName", filename); } public static int getIJType(JSONObject map) throws JSONException, MMScriptException { try { return map.getInt("IJType"); } catch (JSONException e) { try { String pixelType = map.getString("PixelType"); if (pixelType.contentEquals("GRAY8")) { return ImagePlus.GRAY8; } else if (pixelType.contentEquals("GRAY16")) { return ImagePlus.GRAY16; } else if (pixelType.contentEquals("GRAY32")) { return ImagePlus.GRAY32; } else if (pixelType.contentEquals("RGB32")) { return ImagePlus.COLOR_RGB; } else { throw new MMScriptException("Can't figure out IJ type."); } } catch (MMScriptException e2) { throw new MMScriptException("Can't figure out IJ type"); } } } public static String getPixelType(JSONObject map) throws JSONException, MMScriptException { try { if (map != null) return map.getString("PixelType"); } catch (JSONException e) { try { int ijType = map.getInt("IJType"); if (ijType == ImagePlus.GRAY8) return "GRAY8"; else if (ijType == ImagePlus.GRAY16) return "GRAY16"; else if (ijType == ImagePlus.GRAY32) return "GRAY32"; else if (ijType == ImagePlus.COLOR_RGB) return "RGB32"; else throw new MMScriptException("Can't figure out pixel type"); // There is no IJType for RGB64. } catch (MMScriptException e2) { throw new MMScriptException ("Can't figure out pixel type"); } } return ""; } public static void addRandomUUID(JSONObject map) throws JSONException { UUID uuid = UUID.randomUUID(); map.put("UUID", uuid.toString()); } public static UUID getUUID(JSONObject map) throws JSONException { if (map.has("UUID")) return UUID.fromString(map.getString("UUID")); else return null; } public static void setPixelType(JSONObject map, int type) throws JSONException { switch (type) { case ImagePlus.GRAY8: map.put("PixelType", "GRAY8"); break; case ImagePlus.GRAY16: map.put("PixelType", "GRAY16"); break; case ImagePlus.COLOR_RGB: map.put("PixelType", "RGB32"); break; case 64: map.put("PixelType", "RGB64"); break; } } public static void setPixelTypeFromByteDepth(JSONObject map, int depth) throws JSONException { switch (depth) { case 1: map.put("PixelType", "GRAY8"); break; case 2: map.put("PixelType", "GRAY16"); break; case 4: map.put("PixelType", "RGB32"); break; case 8: map.put("PixelType", "RGB64"); break; } } public static int getBytesPerPixel(JSONObject map) throws JSONException, MMScriptException { if (isGRAY8(map)) return 1; if (isGRAY16(map)) return 2; if (isGRAY32(map)) return 4; if (isRGB32(map)) return 4; if (isRGB64(map)) return 8; return 0; } public static int getSingleChannelType(JSONObject map) throws JSONException, MMScriptException { String pixelType = getPixelType(map); if (pixelType.contentEquals("GRAY8")) { return ImagePlus.GRAY8; } else if (pixelType.contentEquals("GRAY16")) { return ImagePlus.GRAY16; } else if (pixelType.contentEquals("GRAY32")) { return ImagePlus.GRAY32; } else if (pixelType.contentEquals("RGB32")) { return ImagePlus.GRAY8; } else if (pixelType.contentEquals("RGB64")) { return ImagePlus.GRAY16; } else { throw new MMScriptException("Can't figure out channel type."); } } public static int getNumberOfComponents(JSONObject map) throws MMScriptException, JSONException { String pixelType = getPixelType(map); if (pixelType.contentEquals("GRAY8")) return 1; else if (pixelType.contentEquals("GRAY16")) return 1; else if (pixelType.contentEquals("GRAY32")) return 1; else if (pixelType.contentEquals("RGB32")) return 3; else if (pixelType.contentEquals("RGB64")) return 3; else { throw new MMScriptException("Pixel type \"" + pixelType + "\"not recognized!"); } } public static boolean isGRAY8(JSONObject map) throws JSONException, MMScriptException { return getPixelType(map).contentEquals("GRAY8"); } public static boolean isGRAY16(JSONObject map) throws JSONException, MMScriptException { return getPixelType(map).contentEquals("GRAY16"); } public static boolean isGRAY32(JSONObject map) throws JSONException, MMScriptException { return getPixelType(map).contentEquals("GRAY32"); } public static boolean isRGB32(JSONObject map) throws JSONException, MMScriptException { return getPixelType(map).contentEquals("RGB32"); } public static boolean isRGB64(JSONObject map) throws JSONException, MMScriptException { return getPixelType(map).contentEquals("RGB64"); } public static boolean isGRAY8(TaggedImage img) throws JSONException, MMScriptException { return isGRAY8(img.tags); } public static boolean isGRAY16(TaggedImage img) throws JSONException, MMScriptException { return isGRAY16(img.tags); } public static boolean isRGB32(TaggedImage img) throws JSONException, MMScriptException { return isRGB32(img.tags); } public static boolean isRGB64(TaggedImage img) throws JSONException, MMScriptException { return isRGB64(img.tags); } public static boolean isGRAY(JSONObject map) throws JSONException, MMScriptException { return (isGRAY8(map) || isGRAY16(map) || isGRAY32(map)); } public static boolean isRGB(JSONObject map) throws JSONException, MMScriptException { return (isRGB32(map) || isRGB64(map)); } public static boolean isGRAY(TaggedImage img) throws JSONException, MMScriptException { return isGRAY(img.tags); } public static boolean isRGB(TaggedImage img) throws JSONException, MMScriptException { return isRGB(img.tags); } public static void addConfiguration(JSONObject md, Configuration config) { PropertySetting setting; for (int i = 0; i < config.size(); ++i) { try { setting = config.getSetting(i); String key = setting.getDeviceLabel() + "-" + setting.getPropertyName(); String value = setting.getPropertyValue(); md.put(key, value); } catch (Exception ex) { ReportingUtils.showError(ex); } } } public static String getLabel(JSONObject md) { try { return generateLabel(getChannelIndex(md), getSliceIndex(md), getFrameIndex(md), getPositionIndex(md)); } catch (JSONException ex) { ReportingUtils.logError(ex); return null; } } public static String generateLabel(int channel, int slice, int frame, int position) { return NumberUtils.intToCoreString(channel) + "_" + NumberUtils.intToCoreString(slice) + "_" + NumberUtils.intToCoreString(frame) + "_" + NumberUtils.intToCoreString(position); } public static int[] getIndices(String label) { try { int[] indices = new int[4]; String[] chunks = label.split("_"); int i = 0; for (String chunk : chunks) { indices[i] = NumberUtils.coreStringToInt(chunk); ++i; } return indices; } catch (ParseException ex) { ReportingUtils.logError(ex); return null; } } public static String[] getKeys(JSONObject md) { int n = md.length(); String [] keyArray = new String[n]; Iterator<String> keys = md.keys(); for (int i=0; i<n; ++i) { keyArray[i] = (String) keys.next(); } return keyArray; } public static JSONArray getJSONArrayMember(JSONObject obj, String key) throws JSONException { JSONArray theArray; try { theArray = obj.getJSONArray(key); } catch (JSONException e) { theArray = new JSONArray(obj.getString(key)); } return theArray; } public static String getTime(Date time) { return iso8601modified_.format(time); } public static String getCurrentTime() { return getTime(new Date()); } public static String getROI (CMMCore core) { String roi = ""; int [] x = new int[1]; int [] y = new int[1]; int [] xSize = new int[1]; int [] ySize = new int[1]; try { core.getROI(x, y, xSize, ySize); roi += x[0] + "-" + y[0] + "-" + xSize[0] + "-" + ySize[0]; } catch (Exception ex) { ReportingUtils.logError(ex, "Error in MDUtils::getROI"); } return roi; } public static int getDepth(JSONObject tags) throws MMScriptException, JSONException { String pixelType = getPixelType(tags); if (pixelType.contains("GRAY8")) return 1; else if (pixelType.contains("GRAY16")) return 2; else if (pixelType.contains("RGB32")) return 4; else if (pixelType.contains("RGB64")) return 8; else return 0; } public static int getNumFrames(JSONObject tags) throws JSONException { if (tags.has("Summary")) { JSONObject summary = tags.getJSONObject("Summary"); if (summary.has("Frames")) return Math.max(1,summary.getInt("Frames")); } if (tags.has("Frames")) return Math.max(1,tags.getInt("Frames")); return 1; } public static int getNumSlices(JSONObject tags) throws JSONException { if (tags.has("Summary")) { JSONObject summary = tags.getJSONObject("Summary"); if (summary.has("Slices")) return Math.max(1, summary.getInt("Slices")); } if (tags.has("Slices")) return Math.max(1, tags.getInt("Slices")); return 1; } public static int getNumChannels(JSONObject tags) throws JSONException { if (tags.has("Summary")) { JSONObject summary = tags.getJSONObject("Summary"); if (summary.has("Channels")) return Math.max(1, summary.getInt("Channels")); } if (tags.has("Channels")) return Math.max(1,tags.getInt("Channels")); return 1; } }
mmstudio/src/org/micromanager/utils/MDUtils.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.micromanager.utils; import ij.ImagePlus; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.UUID; import mmcorej.CMMCore; import mmcorej.Configuration; import mmcorej.PropertySetting; import mmcorej.TaggedImage; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * * @author arthur */ public class MDUtils { private final static SimpleDateFormat iso8601modified_ = new SimpleDateFormat("yyyy-MM-dd E HH:mm:ss Z"); public static JSONObject copy(JSONObject map) { try { return new JSONObject(map.toString()); } catch (JSONException e) { return null; } } public static int getPositionIndex(JSONObject map) throws JSONException { return map.getInt("PositionIndex"); } public static void setPositionIndex(JSONObject map, int positionIndex) throws JSONException { map.put("PositionIndex", positionIndex); } public static int getBitDepth(JSONObject map) throws JSONException { if (map.has("Summary")) return map.getJSONObject("Summary").getInt("BitDepth"); return map.getInt("BitDepth"); } public static int getWidth(JSONObject map) throws JSONException { return map.getInt("Width"); } public static void setWidth(JSONObject map, int width) throws JSONException { map.put("Width", width); } public static int getHeight(JSONObject map) throws JSONException { return map.getInt("Height"); } public static void setHeight(JSONObject map, int height) throws JSONException { map.put("Height", height); } public static int getBinning(JSONObject map) throws JSONException { return map.getInt("Binning"); } public static void setBinning(JSONObject map, int binning) throws JSONException { map.put("Binning", binning); } public static int getSliceIndex(JSONObject map) throws JSONException { if (map.has("SliceIndex")) { return map.getInt("SliceIndex"); } else { return map.getInt("Slice"); } } public static void setSliceIndex(JSONObject map, int sliceIndex) throws JSONException { map.put("SliceIndex", sliceIndex); map.put("Slice", sliceIndex); } public static int getChannelIndex(JSONObject map) throws JSONException { return map.getInt("ChannelIndex"); } public static void setChannelIndex(JSONObject map, int channelIndex) throws JSONException { map.put("ChannelIndex", channelIndex); } public static int getFrameIndex(JSONObject map) throws JSONException { if (map.has("Frame")) { return map.getInt("Frame"); } else { return map.getInt("FrameIndex"); } } public static void setFrameIndex(JSONObject map, int frameIndex) throws JSONException { map.put("Frame", frameIndex); map.put("FrameIndex", frameIndex); } public static int getNumPositions(JSONObject map) throws JSONException { if (map.has("Positions")) return map.getInt("Positions"); throw new JSONException("Positions tag not found in summary metadata"); } public static String getPositionName(JSONObject map) throws JSONException { if (map.has("PositionName") && !map.isNull("PositionName")) { return map.getString("PositionName"); } else if (map.has("PositionIndex")) { return "Pos" + map.getString("PositionIndex"); } else { return null; } } public static void setPositionName(JSONObject map, String positionName) throws JSONException { map.put("PositionName", positionName); } public static String getChannelName(JSONObject map) throws JSONException { if (map.has("Channel") && !map.isNull("Channel")) { return map.getString("Channel"); } else { return ""; } } public static int getChannelColor(JSONObject map) throws JSONException { if (map.has("ChColor") && !map.isNull("ChColor")) { return map.getInt("ChColor"); } else { return -1; } } public static String getFileName(JSONObject map) throws JSONException { if (map.has("FileName")) { return map.getString("FileName"); } else { return null; } } public static void setFileName(JSONObject map, String filename) throws JSONException { map.put("FileName", filename); } public static int getIJType(JSONObject map) throws JSONException, MMScriptException { try { return map.getInt("IJType"); } catch (JSONException e) { try { String pixelType = map.getString("PixelType"); if (pixelType.contentEquals("GRAY8")) { return ImagePlus.GRAY8; } else if (pixelType.contentEquals("GRAY16")) { return ImagePlus.GRAY16; } else if (pixelType.contentEquals("GRAY32")) { return ImagePlus.GRAY32; } else if (pixelType.contentEquals("RGB32")) { return ImagePlus.COLOR_RGB; } else { throw new MMScriptException("Can't figure out IJ type."); } } catch (MMScriptException e2) { throw new MMScriptException("Can't figure out IJ type"); } } } public static String getPixelType(JSONObject map) throws JSONException, MMScriptException { try { if (map != null) return map.getString("PixelType"); } catch (JSONException e) { try { int ijType = map.getInt("IJType"); if (ijType == ImagePlus.GRAY8) return "GRAY8"; else if (ijType == ImagePlus.GRAY16) return "GRAY16"; else if (ijType == ImagePlus.GRAY32) return "GRAY32"; else if (ijType == ImagePlus.COLOR_RGB) return "RGB32"; else throw new MMScriptException("Can't figure out pixel type"); // There is no IJType for RGB64. } catch (MMScriptException e2) { throw new MMScriptException ("Can't figure out pixel type"); } } return ""; } public static void addRandomUUID(JSONObject map) throws JSONException { UUID uuid = UUID.randomUUID(); map.put("UUID", uuid.toString()); } public static UUID getUUID(JSONObject map) throws JSONException { if (map.has("UUID")) return UUID.fromString(map.getString("UUID")); else return null; } public static void setPixelType(JSONObject map, int type) throws JSONException { switch (type) { case ImagePlus.GRAY8: map.put("PixelType", "GRAY8"); break; case ImagePlus.GRAY16: map.put("PixelType", "GRAY16"); break; case ImagePlus.COLOR_RGB: map.put("PixelType", "RGB32"); break; case 64: map.put("PixelType", "RGB64"); break; } } public static void setPixelTypeFromByteDepth(JSONObject map, int depth) throws JSONException { switch (depth) { case 1: map.put("PixelType", "GRAY8"); break; case 2: map.put("PixelType", "GRAY16"); break; case 4: map.put("PixelType", "RGB32"); break; case 8: map.put("PixelType", "RGB64"); break; } } public static int getSingleChannelType(JSONObject map) throws JSONException, MMScriptException { String pixelType = getPixelType(map); if (pixelType.contentEquals("GRAY8")) { return ImagePlus.GRAY8; } else if (pixelType.contentEquals("GRAY16")) { return ImagePlus.GRAY16; } else if (pixelType.contentEquals("GRAY32")) { return ImagePlus.GRAY32; } else if (pixelType.contentEquals("RGB32")) { return ImagePlus.GRAY8; } else if (pixelType.contentEquals("RGB64")) { return ImagePlus.GRAY16; } else { throw new MMScriptException("Can't figure out channel type."); } } public static int getNumberOfComponents(JSONObject map) throws MMScriptException, JSONException { String pixelType = getPixelType(map); if (pixelType.contentEquals("GRAY8")) return 1; else if (pixelType.contentEquals("GRAY16")) return 1; else if (pixelType.contentEquals("GRAY32")) return 1; else if (pixelType.contentEquals("RGB32")) return 3; else if (pixelType.contentEquals("RGB64")) return 3; else { throw new MMScriptException("Pixel type \"" + pixelType + "\"not recognized!"); } } public static boolean isGRAY8(JSONObject map) throws JSONException, MMScriptException { return getPixelType(map).contentEquals("GRAY8"); } public static boolean isGRAY16(JSONObject map) throws JSONException, MMScriptException { return getPixelType(map).contentEquals("GRAY16"); } public static boolean isGRAY32(JSONObject map) throws JSONException, MMScriptException { return getPixelType(map).contentEquals("GRAY32"); } public static boolean isRGB32(JSONObject map) throws JSONException, MMScriptException { return getPixelType(map).contentEquals("RGB32"); } public static boolean isRGB64(JSONObject map) throws JSONException, MMScriptException { return getPixelType(map).contentEquals("RGB64"); } public static boolean isGRAY8(TaggedImage img) throws JSONException, MMScriptException { return isGRAY8(img.tags); } public static boolean isGRAY16(TaggedImage img) throws JSONException, MMScriptException { return isGRAY16(img.tags); } public static boolean isRGB32(TaggedImage img) throws JSONException, MMScriptException { return isRGB32(img.tags); } public static boolean isRGB64(TaggedImage img) throws JSONException, MMScriptException { return isRGB64(img.tags); } public static boolean isGRAY(JSONObject map) throws JSONException, MMScriptException { return (isGRAY8(map) || isGRAY16(map) || isGRAY32(map)); } public static boolean isRGB(JSONObject map) throws JSONException, MMScriptException { return (isRGB32(map) || isRGB64(map)); } public static boolean isGRAY(TaggedImage img) throws JSONException, MMScriptException { return isGRAY(img.tags); } public static boolean isRGB(TaggedImage img) throws JSONException, MMScriptException { return isRGB(img.tags); } public static void addConfiguration(JSONObject md, Configuration config) { PropertySetting setting; for (int i = 0; i < config.size(); ++i) { try { setting = config.getSetting(i); String key = setting.getDeviceLabel() + "-" + setting.getPropertyName(); String value = setting.getPropertyValue(); md.put(key, value); } catch (Exception ex) { ReportingUtils.showError(ex); } } } public static String getLabel(JSONObject md) { try { return generateLabel(getChannelIndex(md), getSliceIndex(md), getFrameIndex(md), getPositionIndex(md)); } catch (JSONException ex) { ReportingUtils.logError(ex); return null; } } public static String generateLabel(int channel, int slice, int frame, int position) { return NumberUtils.intToCoreString(channel) + "_" + NumberUtils.intToCoreString(slice) + "_" + NumberUtils.intToCoreString(frame) + "_" + NumberUtils.intToCoreString(position); } public static int[] getIndices(String label) { try { int[] indices = new int[4]; String[] chunks = label.split("_"); int i = 0; for (String chunk : chunks) { indices[i] = NumberUtils.coreStringToInt(chunk); ++i; } return indices; } catch (ParseException ex) { ReportingUtils.logError(ex); return null; } } public static String[] getKeys(JSONObject md) { int n = md.length(); String [] keyArray = new String[n]; Iterator<String> keys = md.keys(); for (int i=0; i<n; ++i) { keyArray[i] = (String) keys.next(); } return keyArray; } public static JSONArray getJSONArrayMember(JSONObject obj, String key) throws JSONException { JSONArray theArray; try { theArray = obj.getJSONArray(key); } catch (JSONException e) { theArray = new JSONArray(obj.getString(key)); } return theArray; } public static String getTime(Date time) { return iso8601modified_.format(time); } public static String getCurrentTime() { return getTime(new Date()); } public static String getROI (CMMCore core) { String roi = ""; int [] x = new int[1]; int [] y = new int[1]; int [] xSize = new int[1]; int [] ySize = new int[1]; try { core.getROI(x, y, xSize, ySize); roi += x[0] + "-" + y[0] + "-" + xSize[0] + "-" + ySize[0]; } catch (Exception ex) { ReportingUtils.logError(ex, "Error in MDUtils::getROI"); } return roi; } public static int getDepth(JSONObject tags) throws MMScriptException, JSONException { String pixelType = getPixelType(tags); if (pixelType.contains("GRAY8")) return 1; else if (pixelType.contains("GRAY16")) return 2; else if (pixelType.contains("RGB32")) return 4; else if (pixelType.contains("RGB64")) return 8; else return 0; } public static int getNumFrames(JSONObject tags) throws JSONException { if (tags.has("Summary")) { JSONObject summary = tags.getJSONObject("Summary"); if (summary.has("Frames")) return Math.max(1,summary.getInt("Frames")); } if (tags.has("Frames")) return Math.max(1,tags.getInt("Frames")); return 1; } public static int getNumSlices(JSONObject tags) throws JSONException { if (tags.has("Summary")) { JSONObject summary = tags.getJSONObject("Summary"); if (summary.has("Slices")) return Math.max(1, summary.getInt("Slices")); } if (tags.has("Slices")) return Math.max(1, tags.getInt("Slices")); return 1; } public static int getNumChannels(JSONObject tags) throws JSONException { if (tags.has("Summary")) { JSONObject summary = tags.getJSONObject("Summary"); if (summary.has("Channels")) return Math.max(1, summary.getInt("Channels")); } if (tags.has("Channels")) return Math.max(1,tags.getInt("Channels")); return 1; } }
getBytesPerPixel git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@10729 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
mmstudio/src/org/micromanager/utils/MDUtils.java
getBytesPerPixel
Java
mit
2a97393187eb327b954b60583d176122af1cbebf
0
jsettlers/settlers-remake,andreas-eberle/settlers-remake,jsettlers/settlers-remake,Peter-Maximilian/settlers-remake,phirschbeck/settlers-remake,andreasb242/settlers-remake,andreas-eberle/settlers-remake,andreas-eberle/settlers-remake,phirschbeck/settlers-remake,phirschbeck/settlers-remake,jsettlers/settlers-remake,andreasb242/settlers-remake,andreasb242/settlers-remake
/******************************************************************************* * Copyright (c) 2015 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *******************************************************************************/ package jsettlers.ai.highlevel; import jsettlers.ai.highlevel.AiPositions.AiPositionFilter; import jsettlers.algorithms.construction.AbstractConstructionMarkableMap; import jsettlers.common.CommonConstants; import jsettlers.common.buildings.EBuildingType; import jsettlers.common.buildings.IMaterialProductionSettings; import jsettlers.common.landscape.ELandscapeType; import jsettlers.common.landscape.EResourceType; import jsettlers.common.map.partition.IPartitionData; import jsettlers.common.map.shapes.MapCircle; import jsettlers.common.mapobject.EMapObjectType; import jsettlers.common.material.EMaterialType; import jsettlers.common.movable.EDirection; import jsettlers.common.movable.EMovableType; import jsettlers.common.movable.IMovable; import jsettlers.common.position.RelativePoint; import jsettlers.common.position.ShortPoint2D; import jsettlers.logic.buildings.Building; import jsettlers.logic.buildings.WorkAreaBuilding; import jsettlers.logic.map.grid.MainGrid; import jsettlers.logic.map.grid.flags.FlagsGrid; import jsettlers.logic.map.grid.landscape.LandscapeGrid; import jsettlers.logic.map.grid.movable.MovableGrid; import jsettlers.logic.map.grid.objects.AbstractHexMapObject; import jsettlers.logic.map.grid.objects.ObjectsGrid; import jsettlers.logic.map.grid.partition.PartitionsGrid; import jsettlers.logic.movable.Movable; import jsettlers.logic.player.Player; import jsettlers.logic.player.Team; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Vector; import static jsettlers.common.buildings.EBuildingType.BIG_TOWER; import static jsettlers.common.buildings.EBuildingType.CASTLE; import static jsettlers.common.buildings.EBuildingType.FISHER; import static jsettlers.common.buildings.EBuildingType.LUMBERJACK; import static jsettlers.common.buildings.EBuildingType.TOWER; import static jsettlers.common.mapobject.EMapObjectType.STONE; import static jsettlers.common.mapobject.EMapObjectType.TREE_ADULT; import static jsettlers.common.mapobject.EMapObjectType.TREE_GROWING; import static jsettlers.common.movable.EMovableType.SWORDSMAN_L1; import static jsettlers.common.movable.EMovableType.SWORDSMAN_L2; import static jsettlers.common.movable.EMovableType.SWORDSMAN_L3; /** * This class calculates statistics based on the grids which are used by highlevel and lowlevel KI. The statistics are calculated once and read * multiple times within one AiExecutor step triggerd by the game clock. * * @author codingberlin */ public class AiStatistics { private static final EBuildingType[] REFERENCE_POINT_FINDER_BUILDING_ORDER = { LUMBERJACK, TOWER, BIG_TOWER, CASTLE }; public static final int NEAR_STONE_DISTANCE = 5; private final Queue<Building> buildings; private final PlayerStatistic[] playerStatistics; private final Map<EMapObjectType, AiPositions> sortedCuttableObjectsInDefaultPartition; private final AiPositions[] sortedResourceTypes; private final AiPositions sortedRiversInDefaultPartition; private final MainGrid mainGrid; private final LandscapeGrid landscapeGrid; private final ObjectsGrid objectsGrid; private final PartitionsGrid partitionsGrid; private final MovableGrid movableGrid; private final FlagsGrid flagsGrid; private final AbstractConstructionMarkableMap constructionMarksGrid; private final AiMapInformation aiMapInformation; private final long[] resourceCountInDefaultPartition; public AiStatistics(MainGrid mainGrid) { this.buildings = Building.getAllBuildings(); this.mainGrid = mainGrid; this.landscapeGrid = mainGrid.getLandscapeGrid(); this.objectsGrid = mainGrid.getObjectsGrid(); this.partitionsGrid = mainGrid.getPartitionsGrid(); this.movableGrid = mainGrid.getMovableGrid(); this.flagsGrid = mainGrid.getFlagsGrid(); this.constructionMarksGrid = mainGrid.getConstructionMarksGrid(); this.playerStatistics = new PlayerStatistic[mainGrid.getGuiInputGrid().getNumberOfPlayers()]; this.aiMapInformation = new AiMapInformation(this.partitionsGrid); calculateIsFishNearBy(); for (byte i = 0; i < mainGrid.getGuiInputGrid().getNumberOfPlayers(); i++) { this.playerStatistics[i] = new PlayerStatistic(); } sortedRiversInDefaultPartition = new AiPositions(); sortedCuttableObjectsInDefaultPartition = new HashMap<EMapObjectType, AiPositions>(); sortedResourceTypes = new AiPositions[EResourceType.VALUES.length]; for (int i = 0; i < sortedResourceTypes.length; i++) { sortedResourceTypes[i] = new AiPositions(); } resourceCountInDefaultPartition = new long[EResourceType.VALUES.length]; } private void calculateIsFishNearBy() { // TODO @Andreas Eberle implement linearly scanning algorithm for (int x = 0; x < partitionsGrid.getWidth(); x++) { for (int y = 0; y < partitionsGrid.getHeight(); y++) { if (landscapeGrid.getResourceTypeAt(x, y) == EResourceType.FISH && landscapeGrid.getResourceAmountAt(x, y) > 0) { for (ShortPoint2D position : new MapCircle(x, y, FISHER.getWorkRadius())) { if (mainGrid.isInBounds(position.x, position.y)) { int index = position.x * partitionsGrid.getWidth() + position.y; aiMapInformation.wasFishNearByAtGameStart.set(index, true); } } } } } } public byte getFlatternEffortAtPositionForBuilding(final ShortPoint2D position, final EBuildingType buildingType) { byte flattenEffort = constructionMarksGrid.calculateConstructionMarkValue(position.x, position.y, buildingType.getProtectedTiles()); if (flattenEffort == -1) { return Byte.MAX_VALUE; } return flattenEffort; } public void updateStatistics() { for (PlayerStatistic playerStatistic : playerStatistics) { playerStatistic.clearAll(); } sortedRiversInDefaultPartition.clear(); sortedCuttableObjectsInDefaultPartition.clear(); for (AiPositions xCoordinatesMap : sortedResourceTypes) { xCoordinatesMap.clear(); } updateBuildingStatistics(); updateMapStatistics(); } private void updateBuildingStatistics() { for (Building building : buildings) { PlayerStatistic playerStatistic = playerStatistics[building.getPlayerId()]; EBuildingType type = building.getBuildingType(); updateNumberOfNotFinishedBuildings(playerStatistic, building); updateBuildingsNumbers(playerStatistic, building, type); updateBuildingPositions(playerStatistic, type, building); } } private void updateBuildingPositions(PlayerStatistic playerStatistic, EBuildingType type, Building building) { if (!playerStatistic.buildingPositions.containsKey(type)) { playerStatistic.buildingPositions.put(type, new ArrayList<ShortPoint2D>()); } playerStatistic.buildingPositions.get(type).add(building.getPos()); if (type == EBuildingType.WINEGROWER) { playerStatistic.wineGrowerWorkAreas.add(((WorkAreaBuilding) building).getWorkAreaCenter()); } else if (type == EBuildingType.FARM) { playerStatistic.farmWorkAreas.add(((WorkAreaBuilding) building).getWorkAreaCenter()); } } private void updateBuildingsNumbers(PlayerStatistic playerStatistic, Building building, EBuildingType type) { playerStatistic.totalBuildingsNumbers[type.ordinal]++; if (building.getStateProgress() == 1f) { playerStatistic.buildingsNumbers[type.ordinal]++; } } private void updateNumberOfNotFinishedBuildings(PlayerStatistic playerStatistic, Building building) { playerStatistic.numberOfTotalBuildings++; if (building.getStateProgress() < 1f) { playerStatistic.numberOfNotFinishedBuildings++; if (building.getBuildingType().isMilitaryBuilding()) { playerStatistic.numberOfNotOccupiedMilitaryBuildings++; } } else if (building.getBuildingType().isMilitaryBuilding()) { if (building.isOccupied()) { playerStatistic.isAlive = true; } else { playerStatistic.numberOfNotOccupiedMilitaryBuildings++; } } } private void updateMapStatistics() { aiMapInformation.clear(); updatePartitionIdsToBuildOn(); short width = mainGrid.getWidth(); short height = mainGrid.getHeight(); Arrays.fill(resourceCountInDefaultPartition, 0); for (short x = 0; x < width; x++) { for (short y = 0; y < height; y++) { Player player = partitionsGrid.getPlayerAt(x, y); int mapInformationPlayerId; if (player != null) { mapInformationPlayerId = player.playerId; } else { mapInformationPlayerId = aiMapInformation.resourceAndGrassCount.length - 1; } if (landscapeGrid.getResourceAmountAt(x, y) > 0) { EResourceType resourceType = landscapeGrid.getResourceTypeAt(x, y); sortedResourceTypes[resourceType.ordinal].addNoCollission(x, y); if (resourceType != EResourceType.FISH) { aiMapInformation.resourceAndGrassCount[mapInformationPlayerId][resourceType.ordinal]++; if (player != null) { playerStatistics[player.playerId].resourceCount[resourceType.ordinal]++; } else { resourceCountInDefaultPartition[resourceType.ordinal]++; } } else if (landscapeGrid.getLandscapeTypeAt(x, y) == ELandscapeType.WATER1) { int fishMapInformationPlayerId = mapInformationPlayerId; if (mapInformationPlayerId == aiMapInformation.resourceAndGrassCount.length - 1) { fishMapInformationPlayerId = mapInformationPlayerIdOfPosition((short) (x + 3), y); if (fishMapInformationPlayerId == aiMapInformation.resourceAndGrassCount.length - 1) { fishMapInformationPlayerId = mapInformationPlayerIdOfPosition((short) (x - 3), y); if (fishMapInformationPlayerId == aiMapInformation.resourceAndGrassCount.length - 1) { fishMapInformationPlayerId = mapInformationPlayerIdOfPosition(x, (short) (y + 3)); if (fishMapInformationPlayerId == aiMapInformation.resourceAndGrassCount.length - 1) { fishMapInformationPlayerId = mapInformationPlayerIdOfPosition(x, (short) (y - 3)); } } } } aiMapInformation.resourceAndGrassCount[fishMapInformationPlayerId][resourceType.ordinal]++; if (fishMapInformationPlayerId != aiMapInformation.resourceAndGrassCount.length - 1) { playerStatistics[fishMapInformationPlayerId].resourceCount[resourceType.ordinal]++; } else { resourceCountInDefaultPartition[resourceType.ordinal]++; } } } if (landscapeGrid.getLandscapeTypeAt(x, y).isGrass()) { aiMapInformation.resourceAndGrassCount[mapInformationPlayerId][aiMapInformation.GRASS_INDEX]++; } Movable movable = movableGrid.getMovableAt(x, y); if (movable != null) { byte movablePlayerId = movable.getPlayerId(); PlayerStatistic movablePlayerStatistic = playerStatistics[movablePlayerId]; EMovableType movableType = movable.getMovableType(); if (!movablePlayerStatistic.movablePositions.containsKey(movableType)) { movablePlayerStatistic.movablePositions.put(movableType, new Vector<ShortPoint2D>()); } movablePlayerStatistic.movablePositions.get(movableType).add(movable.getPos()); if (player != null && player.playerId != movablePlayerId && movableType.isSoldier() && getEnemiesOf(player.playerId).contains(movablePlayerId)) { playerStatistics[player.playerId].enemyTroopsInTown.addNoCollission(movable.getPos().x, movable.getPos().y); } } if (player == null) { updateFreeLand(x, y); } else if (partitionsGrid.getPartitionIdAt(x, y) == playerStatistics[player.playerId].partitionIdToBuildOn) { updatePlayerLand(x, y, player); } if (player != null && isBorderOf(x, y, player.playerId)) { if (partitionsGrid.getPartitionIdAt(x, y) == playerStatistics[player.playerId].partitionIdToBuildOn) { playerStatistics[player.playerId].border.add(x, y); } else { playerStatistics[player.playerId].otherPartitionBorder.add(x, y); } } } } } private int mapInformationPlayerIdOfPosition(short x, short y) { if (!mainGrid.isInBounds(x, y)) { return aiMapInformation.resourceAndGrassCount.length - 1; } byte playerId = mainGrid.getPartitionsGrid().getPlayerIdAt(x, y); if (playerId == -1) { return aiMapInformation.resourceAndGrassCount.length - 1; } return playerId; } private boolean isBorderOf(int x, int y, byte playerId) { return isIngestibleBy(x + 1, y + 1, playerId) || isIngestibleBy(x + 1, y - 1, playerId) || isIngestibleBy(x - 1, y + 1, playerId) || isIngestibleBy(x - 1, y - 1, playerId); } private boolean isIngestibleBy(int x, int y, byte playerId) { return mainGrid.isInBounds(x, y) && partitionsGrid.getPlayerIdAt(x, y) != playerId && !mainGrid.getLandscapeGrid().getLandscapeTypeAt(x, y).isBlocking && !partitionsGrid.isEnforcedByTower(x, y); } private void updatePlayerLand(short x, short y, Player player) { byte playerId = player.playerId; PlayerStatistic playerStatistic = playerStatistics[playerId]; if (mainGrid.getFlagsGrid().isProtected(x, y)) { AbstractHexMapObject o = objectsGrid.getObjectsAt(x, y); if (o != null) { if (o.hasCuttableObject(STONE) && isCuttableByPlayer(x, y, player.playerId)) { playerStatistic.stones.addNoCollission(x, y); } else if (o.hasMapObjectTypes(TREE_GROWING, TREE_ADULT) && isCuttableByPlayer(x, y, player.playerId)) { playerStatistic.trees.addNoCollission(x, y); } } } else { playerStatistic.landToBuildOn.addNoCollission(x, y); } ELandscapeType landscape = landscapeGrid.getLandscapeTypeAt(x, y); if (landscape.isRiver()) { playerStatistic.rivers.addNoCollission(x, y); } if (objectsGrid.hasMapObjectType(x, y, EMapObjectType.WINE_GROWING, EMapObjectType.WINE_HARVESTABLE)) { playerStatistic.wineCount++; } } private boolean isCuttableByPlayer(short x, short y, byte playerId) { byte[] playerIds = new byte[4]; playerIds[0] = partitionsGrid.getPlayerIdAt(x - 2, y - 2); playerIds[1] = partitionsGrid.getPlayerIdAt(x - 2, y + 2); playerIds[2] = partitionsGrid.getPlayerIdAt(x + 2, y - 2); playerIds[3] = partitionsGrid.getPlayerIdAt(x + 2, y + 2); for (byte positionPlayerId : playerIds) { if (positionPlayerId != playerId) { return false; } } return true; } private void updateFreeLand(short x, short y) { if (objectsGrid.hasCuttableObject(x, y, TREE_ADULT)) { AiPositions trees = sortedCuttableObjectsInDefaultPartition.get(TREE_ADULT); if (trees == null) { trees = new AiPositions(); sortedCuttableObjectsInDefaultPartition.put(TREE_ADULT, trees); } trees.addNoCollission(x, y); } if (objectsGrid.hasCuttableObject(x, y, STONE)) { AiPositions stones = sortedCuttableObjectsInDefaultPartition.get(STONE); if (stones == null) { stones = new AiPositions(); sortedCuttableObjectsInDefaultPartition.put(STONE, stones); } stones.addNoCollission(x, y); updateNearStones(x, y); } ELandscapeType landscape = landscapeGrid.getLandscapeTypeAt(x, y); if (landscape.isRiver()) { sortedRiversInDefaultPartition.addNoCollission(x, y); } } private void updateNearStones(short x, short y) { for (EDirection dir : EDirection.VALUES) { int currX = dir.getNextTileX(x, NEAR_STONE_DISTANCE); int currY = dir.getNextTileY(y, NEAR_STONE_DISTANCE); if (mainGrid.isInBounds(currX, currY)) { byte playerId = partitionsGrid.getPlayerIdAt(currX, currY); if (playerId != -1 && hasPlayersBlockedPartition(playerId, x, y)) { playerStatistics[playerId].stonesNearBy.addNoCollission(x, y); } } } } private void updatePartitionIdsToBuildOn() { for (byte playerId = 0; playerId < playerStatistics.length; playerId++) { ShortPoint2D referencePosition = null; for (EBuildingType referenceFinderBuildingType : REFERENCE_POINT_FINDER_BUILDING_ORDER) { if (getTotalNumberOfBuildingTypeForPlayer(referenceFinderBuildingType, playerId) > 0) { referencePosition = getBuildingPositionsOfTypeForPlayer(referenceFinderBuildingType, playerId).get(0); break; } } if (referencePosition != null) { PlayerStatistic playerStatistic = playerStatistics[playerId]; playerStatistic.referencePosition = referencePosition; playerStatistic.partitionIdToBuildOn = partitionsGrid.getPartitionIdAt(referencePosition.x, referencePosition.y); playerStatistic.blockedPartitionId = landscapeGrid.getBlockedPartitionAt(referencePosition.x,referencePosition.y); playerStatistic.materialProduction = partitionsGrid.getMaterialProductionAt(referencePosition.x, referencePosition.y); playerStatistic.materials = partitionsGrid.getPartitionDataForManagerAt(referencePosition.x, referencePosition.y); } } } public Building getBuildingAt(ShortPoint2D point) { return (Building) objectsGrid.getMapObjectAt(point.x, point.y, EMapObjectType.BUILDING); } public ShortPoint2D getNearestResourcePointForPlayer( ShortPoint2D point, EResourceType resourceType, byte playerId, int searchDistance, AiPositionFilter filter) { return getNearestPointInDefaultPartitionOutOfSortedMap(point, sortedResourceTypes[resourceType.ordinal], playerId, searchDistance, filter); } public ShortPoint2D getNearestFishPointForPlayer(ShortPoint2D point, final byte playerId, int currentNearestPointDistance) { return sortedResourceTypes[EResourceType.FISH.ordinal].getNearestPoint(point, currentNearestPointDistance, new AiPositionFilter() { @Override public boolean contains(int x, int y) { return isPlayerThere(x + 3, y) || isPlayerThere(x - 3, y) || isPlayerThere(x, y + 3) || isPlayerThere(x, y - 3); } private boolean isPlayerThere(int x, int y) { return mainGrid.isInBounds(x, y) && partitionsGrid.getPartitionAt(x, y).getPlayerId() == playerId; } }); } public ShortPoint2D getNearestResourcePointInDefaultPartitionFor( ShortPoint2D point, EResourceType resourceType, int currentNearestPointDistance, AiPositionFilter filter) { return getNearestResourcePointForPlayer(point, resourceType, (byte) -1, currentNearestPointDistance, filter); } public ShortPoint2D getNearestCuttableObjectPointInDefaultPartitionFor( ShortPoint2D point, EMapObjectType cuttableObject, int searchDistance, AiPositionFilter filter) { return getNearestCuttableObjectPointForPlayer(point, cuttableObject, searchDistance, (byte) -1, filter); } public ShortPoint2D getNearestCuttableObjectPointForPlayer(ShortPoint2D point, EMapObjectType cuttableObject, int searchDistance, byte playerId, AiPositionFilter filter) { AiPositions sortedResourcePoints = sortedCuttableObjectsInDefaultPartition.get(cuttableObject); if (sortedResourcePoints == null) { return null; } return getNearestPointInDefaultPartitionOutOfSortedMap(point, sortedResourcePoints, playerId, searchDistance, filter); } private ShortPoint2D getNearestPointInDefaultPartitionOutOfSortedMap( ShortPoint2D point, AiPositions sortedPoints, final byte playerId, int searchDistance, final AiPositionFilter filter) { return sortedPoints.getNearestPoint(point, searchDistance, new AiPositions.CombinedAiPositionFilter(new AiPositionFilter() { @Override public boolean contains(int x, int y) { return partitionsGrid.getPartitionAt(x, y).getPlayerId() == playerId; } }, filter)); } public boolean hasPlayersBlockedPartition(byte playerId, int x, int y) { return landscapeGrid.getBlockedPartitionAt(x, y) == playerStatistics[playerId].blockedPartitionId; } public List<ShortPoint2D> getMovablePositionsByTypeForPlayer(EMovableType movableType, byte playerId) { if (!playerStatistics[playerId].movablePositions.containsKey(movableType)) { return Collections.emptyList(); } return playerStatistics[playerId].movablePositions.get(movableType); } public int getTotalNumberOfBuildingTypeForPlayer(EBuildingType type, byte playerId) { return playerStatistics[playerId].totalBuildingsNumbers[type.ordinal]; } public int getTotalWineCountForPlayer(byte playerId) { return playerStatistics[playerId].wineCount; } public int getNumberOfBuildingTypeForPlayer(EBuildingType type, byte playerId) { return playerStatistics[playerId].buildingsNumbers[type.ordinal]; } public int getNumberOfNotFinishedBuildingsForPlayer(byte playerId) { return playerStatistics[playerId].numberOfNotFinishedBuildings; } public int getNumberOfTotalBuildingsForPlayer(byte playerId) { return playerStatistics[playerId].numberOfTotalBuildings; } public List<ShortPoint2D> getBuildingPositionsOfTypeForPlayer(EBuildingType type, byte playerId) { if (!playerStatistics[playerId].buildingPositions.containsKey(type)) { return Collections.emptyList(); } return playerStatistics[playerId].buildingPositions.get(type); } public List<ShortPoint2D> getBuildingPositionsOfTypesForPlayer(EnumSet<EBuildingType> buildingTypes, byte playerId) { List<ShortPoint2D> buildingPositions = new Vector<ShortPoint2D>(); for (EBuildingType buildingType : buildingTypes) { buildingPositions.addAll(getBuildingPositionsOfTypeForPlayer(buildingType, playerId)); } return buildingPositions; } public AiPositions getStonesForPlayer(byte playerId) { return playerStatistics[playerId].stones; } public AiPositions getTreesForPlayer(byte playerId) { return playerStatistics[playerId].trees; } public AiPositions getLandForPlayer(byte playerId) { return playerStatistics[playerId].landToBuildOn; } public boolean blocksWorkingAreaOfOtherBuilding(ShortPoint2D point, byte playerId, EBuildingType buildingType) { for (ShortPoint2D workAreaCenter : playerStatistics[playerId].wineGrowerWorkAreas) { for (RelativePoint blockedPoint : buildingType.getBlockedTiles()) { if (workAreaCenter.getOnGridDistTo(blockedPoint.calculatePoint(point)) <= EBuildingType.WINEGROWER.getWorkRadius()) { return true; } } } for (ShortPoint2D workAreaCenter : playerStatistics[playerId].farmWorkAreas) { for (RelativePoint blockedPoint : buildingType.getBlockedTiles()) { if (workAreaCenter.getOnGridDistTo(blockedPoint.calculatePoint(point)) <= EBuildingType.FARM.getWorkRadius()) { return true; } } } return false; } public boolean southIsFreeForPlayer(ShortPoint2D point, byte playerId) { return pointIsFreeForPlayer(point.x, (short) (point.y + 12), playerId) && pointIsFreeForPlayer((short) (point.x + 5), (short) (point.y + 12), playerId) && pointIsFreeForPlayer((short) (point.x + 10), (short) (point.y + 12), playerId) && pointIsFreeForPlayer(point.x, (short) (point.y + 6), playerId) && pointIsFreeForPlayer((short) (point.x + 5), (short) (point.y + 6), playerId) && pointIsFreeForPlayer((short) (point.x + 10), (short) (point.y + 6), playerId); } private boolean pointIsFreeForPlayer(short x, short y, byte playerId) { return mainGrid.isInBounds(x, y) && partitionsGrid.getPlayerIdAt(x, y) == playerId && !objectsGrid.isBuildingAt(x, y) && !flagsGrid.isProtected(x, y) && landscapeGrid.areAllNeighborsOf(x, y, 0, 2, ELandscapeType.GRASS, ELandscapeType.EARTH); } public boolean wasFishNearByAtGameStart(ShortPoint2D position) { return aiMapInformation.wasFishNearByAtGameStart.get(position.x * partitionsGrid.getWidth() + position.y); } public IMovable getNearestSwordsmanOf(ShortPoint2D targetPosition, byte playerId) { List<ShortPoint2D> soldierPositions = getMovablePositionsByTypeForPlayer(SWORDSMAN_L3, playerId); if (soldierPositions.size() == 0) { soldierPositions = getMovablePositionsByTypeForPlayer(SWORDSMAN_L2, playerId); } if (soldierPositions.size() == 0) { soldierPositions = getMovablePositionsByTypeForPlayer(SWORDSMAN_L1, playerId); } if (soldierPositions.size() == 0) { return null; } ShortPoint2D nearestSoldierPosition = detectNearestPointFromList(targetPosition, soldierPositions); return movableGrid.getMovableAt(nearestSoldierPosition.x, nearestSoldierPosition.y); } public static ShortPoint2D detectNearestPointFromList(ShortPoint2D referencePoint, List<ShortPoint2D> points) { if (points.isEmpty()) { return null; } return detectNearestPointsFromList(referencePoint, points, 1).get(0); } public static List<ShortPoint2D> detectNearestPointsFromList(final ShortPoint2D referencePoint, List<ShortPoint2D> points, int amountOfPointsToDetect) { if (amountOfPointsToDetect <= 0) { return Collections.emptyList(); } if (points.size() <= amountOfPointsToDetect) { return points; } Collections.sort(points, new Comparator<ShortPoint2D>() { @Override public int compare(ShortPoint2D o1, ShortPoint2D o2) { return o1.getOnGridDistTo(referencePoint) - o2.getOnGridDistTo(referencePoint); } }); return points.subList(0, amountOfPointsToDetect); } public int getNumberOfMaterialTypeForPlayer(EMaterialType type, byte playerId) { if (playerStatistics[playerId].materials == null) { return 0; } return playerStatistics[playerId].materials.getAmountOf(type); } public MainGrid getMainGrid() { return mainGrid; } public ShortPoint2D getNearestRiverPointInDefaultPartitionFor(ShortPoint2D referencePoint, int searchDistance, AiPositionFilter filter) { return getNearestPointInDefaultPartitionOutOfSortedMap(referencePoint, sortedRiversInDefaultPartition, (byte) -1, searchDistance, filter); } public int getNumberOfNotFinishedBuildingTypesForPlayer(EBuildingType buildingType, byte playerId) { return getTotalNumberOfBuildingTypeForPlayer(buildingType, playerId) - getNumberOfBuildingTypeForPlayer(buildingType, playerId); } public AiPositions getRiversForPlayer(byte playerId) { return playerStatistics[playerId].rivers; } public List<Byte> getEnemiesOf(byte playerId) { List<Byte> enemies = new ArrayList<Byte>(); for (Team team : partitionsGrid.getTeams()) { if (!team.isMember(playerId)) { for (Player player : team.getMembers()) { enemies.add(player.playerId); } } } return enemies; } public List<Byte> getAliveEnemiesOf(byte playerId) { List<Byte> aliveEnemies = new ArrayList<>(); for (byte enemyId : getEnemiesOf(playerId)) { if (isAlive(enemyId)) { aliveEnemies.add(enemyId); } } return aliveEnemies; } public ShortPoint2D calculateAveragePointFromList(List<ShortPoint2D> points) { int averageX = 0; int averageY = 0; for (ShortPoint2D point : points) { averageX += point.x; averageY += point.y; } return new ShortPoint2D(averageX / points.size(), averageY / points.size()); } public AiPositions getEnemiesInTownOf(byte playerId) { return playerStatistics[playerId].enemyTroopsInTown; } public IMaterialProductionSettings getMaterialProduction(byte playerId) { return playerStatistics[playerId].materialProduction; } public ShortPoint2D getPositionOfPartition(byte playerId) { return playerStatistics[playerId].referencePosition; } public AiPositions getBorderOf(byte playerId) { return playerStatistics[playerId].border; } public AiPositions getOtherPartitionBorderOf(byte playerId) { return playerStatistics[playerId].otherPartitionBorder; } public boolean isAlive(byte playerId) { return playerStatistics[playerId].isAlive; } public AiMapInformation getAiMapInformation() { return aiMapInformation; } public long resourceCountInDefaultPartition(EResourceType resourceType) { return resourceCountInDefaultPartition[resourceType.ordinal]; } public long resourceCountOfPlayer(EResourceType resourceType, byte playerId) { return playerStatistics[playerId].resourceCount[resourceType.ordinal]; } public List<ShortPoint2D> threatenedBorderOf(byte playerId) { if (playerStatistics[playerId].threatenedBorder == null) { AiPositions borderOfOtherPlayers = new AiPositions(); for (byte otherPlayerId = 0; otherPlayerId < playerStatistics.length; otherPlayerId++) { if (otherPlayerId == playerId || !isAlive(otherPlayerId)) { continue; } borderOfOtherPlayers.addAllNoCollision(getBorderOf(otherPlayerId)); } playerStatistics[playerId].threatenedBorder = new ArrayList<>(); AiPositions myBorder = getBorderOf(playerId); for (int i = 0; i < myBorder.size(); i += 10) { ShortPoint2D myBorderPosition = myBorder.get(i); if (mainGrid.getPartitionsGrid().getTowerCountAt(myBorderPosition.x, myBorderPosition.y) == 0 && borderOfOtherPlayers.getNearestPoint(myBorderPosition, CommonConstants.TOWER_RADIUS) != null) { playerStatistics[playerId].threatenedBorder.add(myBorderPosition); } } } return playerStatistics[playerId].threatenedBorder; } public AiPositions getStonesNearBy(byte playerId) { return playerStatistics[playerId].stonesNearBy; } private static class PlayerStatistic { ShortPoint2D referencePosition; boolean isAlive; final int[] totalBuildingsNumbers = new int[EBuildingType.NUMBER_OF_BUILDINGS]; final int[] buildingsNumbers = new int[EBuildingType.NUMBER_OF_BUILDINGS]; final Map<EBuildingType, List<ShortPoint2D>> buildingPositions = new HashMap<EBuildingType, List<ShortPoint2D>>(); final List<ShortPoint2D> farmWorkAreas = new Vector<ShortPoint2D>(); final List<ShortPoint2D> wineGrowerWorkAreas = new Vector<ShortPoint2D>(); short partitionIdToBuildOn; public short blockedPartitionId; IPartitionData materials; final AiPositions landToBuildOn = new AiPositions(); final AiPositions border = new AiPositions(); final AiPositions otherPartitionBorder = new AiPositions(); final Map<EMovableType, List<ShortPoint2D>> movablePositions = new HashMap<EMovableType, List<ShortPoint2D>>(); final AiPositions stones = new AiPositions(); final AiPositions stonesNearBy = new AiPositions(); final AiPositions trees = new AiPositions(); final AiPositions rivers = new AiPositions(); final AiPositions enemyTroopsInTown = new AiPositions(); List<ShortPoint2D> threatenedBorder; final long[] resourceCount = new long[EResourceType.VALUES.length]; int numberOfNotFinishedBuildings; int numberOfTotalBuildings; int numberOfNotOccupiedMilitaryBuildings; int wineCount; IMaterialProductionSettings materialProduction; PlayerStatistic() { clearIntegers(); } public void clearAll() { isAlive = false; materials = null; buildingPositions.clear(); enemyTroopsInTown.clear(); stones.clear(); stonesNearBy.clear(); trees.clear(); rivers.clear(); landToBuildOn.clear(); border.clear(); otherPartitionBorder.clear(); movablePositions.clear(); farmWorkAreas.clear(); wineGrowerWorkAreas.clear(); threatenedBorder = null; clearIntegers(); } private void clearIntegers() { Arrays.fill(totalBuildingsNumbers, 0); Arrays.fill(buildingsNumbers, 0); Arrays.fill(resourceCount, 0); numberOfNotFinishedBuildings = 0; numberOfTotalBuildings = 0; numberOfNotOccupiedMilitaryBuildings = 0; wineCount = 0; partitionIdToBuildOn = Short.MIN_VALUE; blockedPartitionId = Short.MIN_VALUE; } } }
jsettlers.logic/src/main/java/jsettlers/ai/highlevel/AiStatistics.java
/******************************************************************************* * Copyright (c) 2015 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *******************************************************************************/ package jsettlers.ai.highlevel; import jsettlers.ai.highlevel.AiPositions.AiPositionFilter; import jsettlers.algorithms.construction.AbstractConstructionMarkableMap; import jsettlers.common.CommonConstants; import jsettlers.common.buildings.EBuildingType; import jsettlers.common.buildings.IMaterialProductionSettings; import jsettlers.common.landscape.ELandscapeType; import jsettlers.common.landscape.EResourceType; import jsettlers.common.map.partition.IPartitionData; import jsettlers.common.map.shapes.MapCircle; import jsettlers.common.mapobject.EMapObjectType; import jsettlers.common.material.EMaterialType; import jsettlers.common.movable.EDirection; import jsettlers.common.movable.EMovableType; import jsettlers.common.movable.IMovable; import jsettlers.common.position.RelativePoint; import jsettlers.common.position.ShortPoint2D; import jsettlers.logic.buildings.Building; import jsettlers.logic.buildings.WorkAreaBuilding; import jsettlers.logic.map.grid.MainGrid; import jsettlers.logic.map.grid.flags.FlagsGrid; import jsettlers.logic.map.grid.landscape.LandscapeGrid; import jsettlers.logic.map.grid.movable.MovableGrid; import jsettlers.logic.map.grid.objects.AbstractHexMapObject; import jsettlers.logic.map.grid.objects.ObjectsGrid; import jsettlers.logic.map.grid.partition.PartitionsGrid; import jsettlers.logic.movable.Movable; import jsettlers.logic.player.Player; import jsettlers.logic.player.Team; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Vector; import static jsettlers.common.buildings.EBuildingType.BIG_TOWER; import static jsettlers.common.buildings.EBuildingType.CASTLE; import static jsettlers.common.buildings.EBuildingType.FISHER; import static jsettlers.common.buildings.EBuildingType.LUMBERJACK; import static jsettlers.common.buildings.EBuildingType.TOWER; import static jsettlers.common.mapobject.EMapObjectType.STONE; import static jsettlers.common.mapobject.EMapObjectType.TREE_ADULT; import static jsettlers.common.mapobject.EMapObjectType.TREE_GROWING; import static jsettlers.common.movable.EMovableType.SWORDSMAN_L1; import static jsettlers.common.movable.EMovableType.SWORDSMAN_L2; import static jsettlers.common.movable.EMovableType.SWORDSMAN_L3; /** * This class calculates statistics based on the grids which are used by highlevel and lowlevel KI. The statistics are calculated once and read * multiple times within one AiExecutor step triggerd by the game clock. * * @author codingberlin */ public class AiStatistics { private static final EBuildingType[] REFERENCE_POINT_FINDER_BUILDING_ORDER = { LUMBERJACK, TOWER, BIG_TOWER, CASTLE }; public static final int NEAR_STONE_DISTANCE = 5; private final Queue<Building> buildings; private final PlayerStatistic[] playerStatistics; private final Map<EMapObjectType, AiPositions> sortedCuttableObjectsInDefaultPartition; private final AiPositions[] sortedResourceTypes; private final AiPositions sortedRiversInDefaultPartition; private final MainGrid mainGrid; private final LandscapeGrid landscapeGrid; private final ObjectsGrid objectsGrid; private final PartitionsGrid partitionsGrid; private final MovableGrid movableGrid; private final FlagsGrid flagsGrid; private final AbstractConstructionMarkableMap constructionMarksGrid; private final AiMapInformation aiMapInformation; private final long[] resourceCountInDefaultPartition; public AiStatistics(MainGrid mainGrid) { this.buildings = Building.getAllBuildings(); this.mainGrid = mainGrid; this.landscapeGrid = mainGrid.getLandscapeGrid(); this.objectsGrid = mainGrid.getObjectsGrid(); this.partitionsGrid = mainGrid.getPartitionsGrid(); this.movableGrid = mainGrid.getMovableGrid(); this.flagsGrid = mainGrid.getFlagsGrid(); this.constructionMarksGrid = mainGrid.getConstructionMarksGrid(); this.playerStatistics = new PlayerStatistic[mainGrid.getGuiInputGrid().getNumberOfPlayers()]; this.aiMapInformation = new AiMapInformation(this.partitionsGrid); calculateIsFishNearBy(); for (byte i = 0; i < mainGrid.getGuiInputGrid().getNumberOfPlayers(); i++) { this.playerStatistics[i] = new PlayerStatistic(); } sortedRiversInDefaultPartition = new AiPositions(); sortedCuttableObjectsInDefaultPartition = new HashMap<EMapObjectType, AiPositions>(); sortedResourceTypes = new AiPositions[EResourceType.VALUES.length]; for (int i = 0; i < sortedResourceTypes.length; i++) { sortedResourceTypes[i] = new AiPositions(); } resourceCountInDefaultPartition = new long[EResourceType.VALUES.length]; } private void calculateIsFishNearBy() { // TODO @Andreas Eberle implement linearly scanning algorithm for (int x = 0; x < partitionsGrid.getWidth(); x++) { for (int y = 0; y < partitionsGrid.getHeight(); y++) { if (landscapeGrid.getResourceTypeAt(x, y) == EResourceType.FISH && landscapeGrid.getResourceAmountAt(x, y) > 0) { for (ShortPoint2D position : new MapCircle(x, y, FISHER.getWorkRadius())) { if (mainGrid.isInBounds(position.x, position.y)) { int index = position.x * partitionsGrid.getWidth() + position.y; aiMapInformation.wasFishNearByAtGameStart.set(index, true); } } } } } } public byte getFlatternEffortAtPositionForBuilding(final ShortPoint2D position, final EBuildingType buildingType) { byte flattenEffort = constructionMarksGrid.calculateConstructionMarkValue(position.x, position.y, buildingType.getProtectedTiles()); if (flattenEffort == -1) { return Byte.MAX_VALUE; } return flattenEffort; } public void updateStatistics() { for (PlayerStatistic playerStatistic : playerStatistics) { playerStatistic.clearAll(); } sortedRiversInDefaultPartition.clear(); sortedCuttableObjectsInDefaultPartition.clear(); for (AiPositions xCoordinatesMap : sortedResourceTypes) { xCoordinatesMap.clear(); } updateBuildingStatistics(); updateMapStatistics(); } private void updateBuildingStatistics() { for (Building building : buildings) { PlayerStatistic playerStatistic = playerStatistics[building.getPlayerId()]; EBuildingType type = building.getBuildingType(); updateNumberOfNotFinishedBuildings(playerStatistic, building); updateBuildingsNumbers(playerStatistic, building, type); updateBuildingPositions(playerStatistic, type, building); } } private void updateBuildingPositions(PlayerStatistic playerStatistic, EBuildingType type, Building building) { if (!playerStatistic.buildingPositions.containsKey(type)) { playerStatistic.buildingPositions.put(type, new ArrayList<ShortPoint2D>()); } playerStatistic.buildingPositions.get(type).add(building.getPos()); if (type == EBuildingType.WINEGROWER) { playerStatistic.wineGrowerWorkAreas.add(((WorkAreaBuilding) building).getWorkAreaCenter()); } else if (type == EBuildingType.FARM) { playerStatistic.farmWorkAreas.add(((WorkAreaBuilding) building).getWorkAreaCenter()); } } private void updateBuildingsNumbers(PlayerStatistic playerStatistic, Building building, EBuildingType type) { playerStatistic.totalBuildingsNumbers[type.ordinal]++; if (building.getStateProgress() == 1f) { playerStatistic.buildingsNumbers[type.ordinal]++; } } private void updateNumberOfNotFinishedBuildings(PlayerStatistic playerStatistic, Building building) { playerStatistic.numberOfTotalBuildings++; if (building.getStateProgress() < 1f) { playerStatistic.numberOfNotFinishedBuildings++; if (building.getBuildingType().isMilitaryBuilding()) { playerStatistic.numberOfNotOccupiedMilitaryBuildings++; } } else if (building.getBuildingType().isMilitaryBuilding()) { if (building.isOccupied()) { playerStatistic.isAlive = true; } else { playerStatistic.numberOfNotOccupiedMilitaryBuildings++; } } } private void updateMapStatistics() { aiMapInformation.clear(); updatePartitionIdsToBuildOn(); short width = mainGrid.getWidth(); short height = mainGrid.getHeight(); Arrays.fill(resourceCountInDefaultPartition, 0); for (short x = 0; x < width; x++) { for (short y = 0; y < height; y++) { Player player = partitionsGrid.getPlayerAt(x, y); int mapInformationPlayerId; if (player != null) { mapInformationPlayerId = player.playerId; } else { mapInformationPlayerId = aiMapInformation.resourceAndGrassCount.length - 1; } if (landscapeGrid.getResourceAmountAt(x, y) > 0) { EResourceType resourceType = landscapeGrid.getResourceTypeAt(x, y); sortedResourceTypes[resourceType.ordinal].addNoCollission(x, y); if (resourceType != EResourceType.FISH) { aiMapInformation.resourceAndGrassCount[mapInformationPlayerId][resourceType.ordinal]++; if (player != null) { playerStatistics[player.playerId].resourceCount[resourceType.ordinal]++; } else { resourceCountInDefaultPartition[resourceType.ordinal]++; } } else if (landscapeGrid.getLandscapeTypeAt(x, y) == ELandscapeType.WATER1) { int fishMapInformationPlayerId = mapInformationPlayerId; if (mapInformationPlayerId == aiMapInformation.resourceAndGrassCount.length - 1) { fishMapInformationPlayerId = mapInformationPlayerIdOfPosition((short) (x + 3), y); if (fishMapInformationPlayerId == aiMapInformation.resourceAndGrassCount.length - 1) { fishMapInformationPlayerId = mapInformationPlayerIdOfPosition((short) (x - 3), y); if (fishMapInformationPlayerId == aiMapInformation.resourceAndGrassCount.length - 1) { fishMapInformationPlayerId = mapInformationPlayerIdOfPosition(x, (short) (y + 3)); if (fishMapInformationPlayerId == aiMapInformation.resourceAndGrassCount.length - 1) { fishMapInformationPlayerId = mapInformationPlayerIdOfPosition(x, (short) (y - 3)); } } } } aiMapInformation.resourceAndGrassCount[fishMapInformationPlayerId][resourceType.ordinal]++; if (fishMapInformationPlayerId != aiMapInformation.resourceAndGrassCount.length - 1) { playerStatistics[fishMapInformationPlayerId].resourceCount[resourceType.ordinal]++; } else { resourceCountInDefaultPartition[resourceType.ordinal]++; } } } if (landscapeGrid.getLandscapeTypeAt(x, y).isGrass()) { aiMapInformation.resourceAndGrassCount[mapInformationPlayerId][aiMapInformation.GRASS_INDEX]++; } Movable movable = movableGrid.getMovableAt(x, y); if (movable != null) { byte movablePlayerId = movable.getPlayerId(); PlayerStatistic movablePlayerStatistic = playerStatistics[movablePlayerId]; EMovableType movableType = movable.getMovableType(); if (!movablePlayerStatistic.movablePositions.containsKey(movableType)) { movablePlayerStatistic.movablePositions.put(movableType, new Vector<ShortPoint2D>()); } movablePlayerStatistic.movablePositions.get(movableType).add(movable.getPos()); if (player != null && player.playerId != movablePlayerId && movableType.isSoldier() && getEnemiesOf(player.playerId).contains(movablePlayerId)) { playerStatistics[player.playerId].enemyTroopsInTown.addNoCollission(movable.getPos().x, movable.getPos().y); } } if (player == null) { updateFreeLand(x, y); } else if (partitionsGrid.getPartitionIdAt(x, y) == playerStatistics[player.playerId].partitionIdToBuildOn) { updatePlayerLand(x, y, player); } if (player != null && isBorderOf(x, y, player.playerId)) { if (partitionsGrid.getPartitionIdAt(x, y) == playerStatistics[player.playerId].partitionIdToBuildOn) { playerStatistics[player.playerId].border.add(x, y); } else { playerStatistics[player.playerId].otherPartitionBorder.add(x, y); } } } } } private int mapInformationPlayerIdOfPosition(short x, short y) { if (!mainGrid.isInBounds(x, y)) { return aiMapInformation.resourceAndGrassCount.length - 1; } byte playerId = mainGrid.getPartitionsGrid().getPlayerIdAt(x, y); if (playerId == -1) { return aiMapInformation.resourceAndGrassCount.length - 1; } return playerId; } private boolean isBorderOf(int x, int y, byte playerId) { return isIngestibleBy(x + 1, y + 1, playerId) || isIngestibleBy(x + 1, y - 1, playerId) || isIngestibleBy(x - 1, y + 1, playerId) || isIngestibleBy(x - 1, y - 1, playerId); } private boolean isIngestibleBy(int x, int y, byte playerId) { return mainGrid.isInBounds(x, y) && partitionsGrid.getPlayerIdAt(x, y) != playerId && !mainGrid.getLandscapeGrid().getLandscapeTypeAt(x, y).isBlocking && !partitionsGrid.isEnforcedByTower(x, y); } private void updatePlayerLand(short x, short y, Player player) { byte playerId = player.playerId; PlayerStatistic playerStatistic = playerStatistics[playerId]; if (mainGrid.getFlagsGrid().isProtected(x, y)) { AbstractHexMapObject o = objectsGrid.getObjectsAt(x, y); if (o != null) { if (o.hasCuttableObject(STONE) && isCuttableByPlayer(x, y, player.playerId)) { playerStatistic.stones.addNoCollission(x, y); } else if (o.hasMapObjectTypes(TREE_GROWING, TREE_ADULT) && isCuttableByPlayer(x, y, player.playerId)) { playerStatistic.trees.addNoCollission(x, y); } } } else { playerStatistic.landToBuildOn.addNoCollission(x, y); } ELandscapeType landscape = landscapeGrid.getLandscapeTypeAt(x, y); if (landscape.isRiver()) { playerStatistic.rivers.addNoCollission(x, y); } if (objectsGrid.hasMapObjectType(x, y, EMapObjectType.WINE_GROWING, EMapObjectType.WINE_HARVESTABLE)) { playerStatistic.wineCount++; } } private boolean isCuttableByPlayer(short x, short y, byte playerId) { byte[] playerIds = new byte[4]; playerIds[0] = partitionsGrid.getPlayerIdAt(x - 2, y - 2); playerIds[1] = partitionsGrid.getPlayerIdAt(x - 2, y + 2); playerIds[2] = partitionsGrid.getPlayerIdAt(x + 2, y - 2); playerIds[3] = partitionsGrid.getPlayerIdAt(x + 2, y + 2); for (byte positionPlayerId : playerIds) { if (positionPlayerId != playerId) { return false; } } return true; } private void updateFreeLand(short x, short y) { if (objectsGrid.hasCuttableObject(x, y, TREE_ADULT)) { AiPositions trees = sortedCuttableObjectsInDefaultPartition.get(TREE_ADULT); if (trees == null) { trees = new AiPositions(); sortedCuttableObjectsInDefaultPartition.put(TREE_ADULT, trees); } trees.addNoCollission(x, y); } if (objectsGrid.hasCuttableObject(x, y, STONE)) { AiPositions stones = sortedCuttableObjectsInDefaultPartition.get(STONE); if (stones == null) { stones = new AiPositions(); sortedCuttableObjectsInDefaultPartition.put(STONE, stones); } stones.addNoCollission(x, y); updateNearStones(x, y); } ELandscapeType landscape = landscapeGrid.getLandscapeTypeAt(x, y); if (landscape.isRiver()) { sortedRiversInDefaultPartition.addNoCollission(x, y); } } private void updateNearStones(short x, short y) { for (EDirection dir : EDirection.VALUES) { int currX = dir.getNextTileX(x, NEAR_STONE_DISTANCE); int currY = dir.getNextTileY(y, NEAR_STONE_DISTANCE); if (mainGrid.isInBounds(currX, currY)) { byte playerId = partitionsGrid.getPlayerIdAt(currX, currY); if (playerId != -1 && hasPlayersBlockedPartition(playerId, x, y)) { playerStatistics[playerId].stonesNearBy.addNoCollission(x, y); } } } } private void updatePartitionIdsToBuildOn() { for (byte playerId = 0; playerId < playerStatistics.length; playerId++) { ShortPoint2D referencePosition = null; for (EBuildingType referenceFinderBuildingType : REFERENCE_POINT_FINDER_BUILDING_ORDER) { if (getTotalNumberOfBuildingTypeForPlayer(referenceFinderBuildingType, playerId) > 0) { referencePosition = getBuildingPositionsOfTypeForPlayer(referenceFinderBuildingType, playerId).get(0); break; } } if (referencePosition != null) { playerStatistics[playerId].referencePosition = referencePosition; playerStatistics[playerId].partitionIdToBuildOn = partitionsGrid.getPartitionIdAt(referencePosition.x, referencePosition.y); playerStatistics[playerId].materialProduction = partitionsGrid.getMaterialProductionAt(referencePosition.x, referencePosition.y); playerStatistics[playerId].materials = partitionsGrid.getPartitionDataForManagerAt(referencePosition.x, referencePosition.y); } } } public Building getBuildingAt(ShortPoint2D point) { return (Building) objectsGrid.getMapObjectAt(point.x, point.y, EMapObjectType.BUILDING); } public ShortPoint2D getNearestResourcePointForPlayer( ShortPoint2D point, EResourceType resourceType, byte playerId, int searchDistance, AiPositionFilter filter) { return getNearestPointInDefaultPartitionOutOfSortedMap(point, sortedResourceTypes[resourceType.ordinal], playerId, searchDistance, filter); } public ShortPoint2D getNearestFishPointForPlayer(ShortPoint2D point, final byte playerId, int currentNearestPointDistance) { return sortedResourceTypes[EResourceType.FISH.ordinal].getNearestPoint(point, currentNearestPointDistance, new AiPositionFilter() { @Override public boolean contains(int x, int y) { return isPlayerThere(x + 3, y) || isPlayerThere(x - 3, y) || isPlayerThere(x, y + 3) || isPlayerThere(x, y - 3); } private boolean isPlayerThere(int x, int y) { return mainGrid.isInBounds(x, y) && partitionsGrid.getPartitionAt(x, y).getPlayerId() == playerId; } }); } public ShortPoint2D getNearestResourcePointInDefaultPartitionFor( ShortPoint2D point, EResourceType resourceType, int currentNearestPointDistance, AiPositionFilter filter) { return getNearestResourcePointForPlayer(point, resourceType, (byte) -1, currentNearestPointDistance, filter); } public ShortPoint2D getNearestCuttableObjectPointInDefaultPartitionFor( ShortPoint2D point, EMapObjectType cuttableObject, int searchDistance, AiPositionFilter filter) { return getNearestCuttableObjectPointForPlayer(point, cuttableObject, searchDistance, (byte) -1, filter); } public ShortPoint2D getNearestCuttableObjectPointForPlayer(ShortPoint2D point, EMapObjectType cuttableObject, int searchDistance, byte playerId, AiPositionFilter filter) { AiPositions sortedResourcePoints = sortedCuttableObjectsInDefaultPartition.get(cuttableObject); if (sortedResourcePoints == null) { return null; } return getNearestPointInDefaultPartitionOutOfSortedMap(point, sortedResourcePoints, playerId, searchDistance, filter); } private ShortPoint2D getNearestPointInDefaultPartitionOutOfSortedMap( ShortPoint2D point, AiPositions sortedPoints, final byte playerId, int searchDistance, final AiPositionFilter filter) { return sortedPoints.getNearestPoint(point, searchDistance, new AiPositions.CombinedAiPositionFilter(new AiPositionFilter() { @Override public boolean contains(int x, int y) { return partitionsGrid.getPartitionAt(x, y).getPlayerId() == playerId; } }, filter)); } public boolean hasPlayersBlockedPartition(byte playerId, int x, int y) { ShortPoint2D referencePosition = playerStatistics[playerId].referencePosition; return landscapeGrid.getBlockedPartitionAt(x, y) == landscapeGrid.getBlockedPartitionAt(referencePosition.x, referencePosition.y); } public List<ShortPoint2D> getMovablePositionsByTypeForPlayer(EMovableType movableType, byte playerId) { if (!playerStatistics[playerId].movablePositions.containsKey(movableType)) { return Collections.emptyList(); } return playerStatistics[playerId].movablePositions.get(movableType); } public int getTotalNumberOfBuildingTypeForPlayer(EBuildingType type, byte playerId) { return playerStatistics[playerId].totalBuildingsNumbers[type.ordinal]; } public int getTotalWineCountForPlayer(byte playerId) { return playerStatistics[playerId].wineCount; } public int getNumberOfBuildingTypeForPlayer(EBuildingType type, byte playerId) { return playerStatistics[playerId].buildingsNumbers[type.ordinal]; } public int getNumberOfNotFinishedBuildingsForPlayer(byte playerId) { return playerStatistics[playerId].numberOfNotFinishedBuildings; } public int getNumberOfTotalBuildingsForPlayer(byte playerId) { return playerStatistics[playerId].numberOfTotalBuildings; } public List<ShortPoint2D> getBuildingPositionsOfTypeForPlayer(EBuildingType type, byte playerId) { if (!playerStatistics[playerId].buildingPositions.containsKey(type)) { return Collections.emptyList(); } return playerStatistics[playerId].buildingPositions.get(type); } public List<ShortPoint2D> getBuildingPositionsOfTypesForPlayer(EnumSet<EBuildingType> buildingTypes, byte playerId) { List<ShortPoint2D> buildingPositions = new Vector<ShortPoint2D>(); for (EBuildingType buildingType : buildingTypes) { buildingPositions.addAll(getBuildingPositionsOfTypeForPlayer(buildingType, playerId)); } return buildingPositions; } public AiPositions getStonesForPlayer(byte playerId) { return playerStatistics[playerId].stones; } public AiPositions getTreesForPlayer(byte playerId) { return playerStatistics[playerId].trees; } public AiPositions getLandForPlayer(byte playerId) { return playerStatistics[playerId].landToBuildOn; } public boolean blocksWorkingAreaOfOtherBuilding(ShortPoint2D point, byte playerId, EBuildingType buildingType) { for (ShortPoint2D workAreaCenter : playerStatistics[playerId].wineGrowerWorkAreas) { for (RelativePoint blockedPoint : buildingType.getBlockedTiles()) { if (workAreaCenter.getOnGridDistTo(blockedPoint.calculatePoint(point)) <= EBuildingType.WINEGROWER.getWorkRadius()) { return true; } } } for (ShortPoint2D workAreaCenter : playerStatistics[playerId].farmWorkAreas) { for (RelativePoint blockedPoint : buildingType.getBlockedTiles()) { if (workAreaCenter.getOnGridDistTo(blockedPoint.calculatePoint(point)) <= EBuildingType.FARM.getWorkRadius()) { return true; } } } return false; } public boolean southIsFreeForPlayer(ShortPoint2D point, byte playerId) { return pointIsFreeForPlayer(point.x, (short) (point.y + 12), playerId) && pointIsFreeForPlayer((short) (point.x + 5), (short) (point.y + 12), playerId) && pointIsFreeForPlayer((short) (point.x + 10), (short) (point.y + 12), playerId) && pointIsFreeForPlayer(point.x, (short) (point.y + 6), playerId) && pointIsFreeForPlayer((short) (point.x + 5), (short) (point.y + 6), playerId) && pointIsFreeForPlayer((short) (point.x + 10), (short) (point.y + 6), playerId); } private boolean pointIsFreeForPlayer(short x, short y, byte playerId) { return mainGrid.isInBounds(x, y) && partitionsGrid.getPlayerIdAt(x, y) == playerId && !objectsGrid.isBuildingAt(x, y) && !flagsGrid.isProtected(x, y) && landscapeGrid.areAllNeighborsOf(x, y, 0, 2, ELandscapeType.GRASS, ELandscapeType.EARTH); } public boolean wasFishNearByAtGameStart(ShortPoint2D position) { return aiMapInformation.wasFishNearByAtGameStart.get(position.x * partitionsGrid.getWidth() + position.y); } public IMovable getNearestSwordsmanOf(ShortPoint2D targetPosition, byte playerId) { List<ShortPoint2D> soldierPositions = getMovablePositionsByTypeForPlayer(SWORDSMAN_L3, playerId); if (soldierPositions.size() == 0) { soldierPositions = getMovablePositionsByTypeForPlayer(SWORDSMAN_L2, playerId); } if (soldierPositions.size() == 0) { soldierPositions = getMovablePositionsByTypeForPlayer(SWORDSMAN_L1, playerId); } if (soldierPositions.size() == 0) { return null; } ShortPoint2D nearestSoldierPosition = detectNearestPointFromList(targetPosition, soldierPositions); return movableGrid.getMovableAt(nearestSoldierPosition.x, nearestSoldierPosition.y); } public static ShortPoint2D detectNearestPointFromList(ShortPoint2D referencePoint, List<ShortPoint2D> points) { if (points.isEmpty()) { return null; } return detectNearestPointsFromList(referencePoint, points, 1).get(0); } public static List<ShortPoint2D> detectNearestPointsFromList(final ShortPoint2D referencePoint, List<ShortPoint2D> points, int amountOfPointsToDetect) { if (amountOfPointsToDetect <= 0) { return Collections.emptyList(); } if (points.size() <= amountOfPointsToDetect) { return points; } Collections.sort(points, new Comparator<ShortPoint2D>() { @Override public int compare(ShortPoint2D o1, ShortPoint2D o2) { return o1.getOnGridDistTo(referencePoint) - o2.getOnGridDistTo(referencePoint); } }); return points.subList(0, amountOfPointsToDetect); } public int getNumberOfMaterialTypeForPlayer(EMaterialType type, byte playerId) { if (playerStatistics[playerId].materials == null) { return 0; } return playerStatistics[playerId].materials.getAmountOf(type); } public MainGrid getMainGrid() { return mainGrid; } public ShortPoint2D getNearestRiverPointInDefaultPartitionFor(ShortPoint2D referencePoint, int searchDistance, AiPositionFilter filter) { return getNearestPointInDefaultPartitionOutOfSortedMap(referencePoint, sortedRiversInDefaultPartition, (byte) -1, searchDistance, filter); } public int getNumberOfNotFinishedBuildingTypesForPlayer(EBuildingType buildingType, byte playerId) { return getTotalNumberOfBuildingTypeForPlayer(buildingType, playerId) - getNumberOfBuildingTypeForPlayer(buildingType, playerId); } public AiPositions getRiversForPlayer(byte playerId) { return playerStatistics[playerId].rivers; } public List<Byte> getEnemiesOf(byte playerId) { List<Byte> enemies = new ArrayList<Byte>(); for (Team team : partitionsGrid.getTeams()) { if (!team.isMember(playerId)) { for (Player player : team.getMembers()) { enemies.add(player.playerId); } } } return enemies; } public List<Byte> getAliveEnemiesOf(byte playerId) { List<Byte> aliveEnemies = new ArrayList<>(); for (byte enemyId : getEnemiesOf(playerId)) { if (isAlive(enemyId)) { aliveEnemies.add(enemyId); } } return aliveEnemies; } public ShortPoint2D calculateAveragePointFromList(List<ShortPoint2D> points) { int averageX = 0; int averageY = 0; for (ShortPoint2D point : points) { averageX += point.x; averageY += point.y; } return new ShortPoint2D(averageX / points.size(), averageY / points.size()); } public AiPositions getEnemiesInTownOf(byte playerId) { return playerStatistics[playerId].enemyTroopsInTown; } public IMaterialProductionSettings getMaterialProduction(byte playerId) { return playerStatistics[playerId].materialProduction; } public ShortPoint2D getPositionOfPartition(byte playerId) { return playerStatistics[playerId].referencePosition; } public AiPositions getBorderOf(byte playerId) { return playerStatistics[playerId].border; } public AiPositions getOtherPartitionBorderOf(byte playerId) { return playerStatistics[playerId].otherPartitionBorder; } public boolean isAlive(byte playerId) { return playerStatistics[playerId].isAlive; } public AiMapInformation getAiMapInformation() { return aiMapInformation; } public long resourceCountInDefaultPartition(EResourceType resourceType) { return resourceCountInDefaultPartition[resourceType.ordinal]; } public long resourceCountOfPlayer(EResourceType resourceType, byte playerId) { return playerStatistics[playerId].resourceCount[resourceType.ordinal]; } public List<ShortPoint2D> threatenedBorderOf(byte playerId) { if (playerStatistics[playerId].threatenedBorder == null) { AiPositions borderOfOtherPlayers = new AiPositions(); for (byte otherPlayerId = 0; otherPlayerId < playerStatistics.length; otherPlayerId++) { if (otherPlayerId == playerId || !isAlive(otherPlayerId)) { continue; } borderOfOtherPlayers.addAllNoCollision(getBorderOf(otherPlayerId)); } playerStatistics[playerId].threatenedBorder = new ArrayList<>(); AiPositions myBorder = getBorderOf(playerId); for (int i = 0; i < myBorder.size(); i += 10) { ShortPoint2D myBorderPosition = myBorder.get(i); if (mainGrid.getPartitionsGrid().getTowerCountAt(myBorderPosition.x, myBorderPosition.y) == 0 && borderOfOtherPlayers.getNearestPoint(myBorderPosition, CommonConstants.TOWER_RADIUS) != null) { playerStatistics[playerId].threatenedBorder.add(myBorderPosition); } } } return playerStatistics[playerId].threatenedBorder; } public AiPositions getStonesNearBy(byte playerId) { return playerStatistics[playerId].stonesNearBy; } private static class PlayerStatistic { ShortPoint2D referencePosition; boolean isAlive; final int[] totalBuildingsNumbers = new int[EBuildingType.NUMBER_OF_BUILDINGS]; final int[] buildingsNumbers = new int[EBuildingType.NUMBER_OF_BUILDINGS]; final Map<EBuildingType, List<ShortPoint2D>> buildingPositions = new HashMap<EBuildingType, List<ShortPoint2D>>(); final List<ShortPoint2D> farmWorkAreas = new Vector<ShortPoint2D>(); final List<ShortPoint2D> wineGrowerWorkAreas = new Vector<ShortPoint2D>(); short partitionIdToBuildOn; IPartitionData materials; final AiPositions landToBuildOn = new AiPositions(); final AiPositions border = new AiPositions(); final AiPositions otherPartitionBorder = new AiPositions(); final Map<EMovableType, List<ShortPoint2D>> movablePositions = new HashMap<EMovableType, List<ShortPoint2D>>(); final AiPositions stones = new AiPositions(); final AiPositions stonesNearBy = new AiPositions(); final AiPositions trees = new AiPositions(); final AiPositions rivers = new AiPositions(); final AiPositions enemyTroopsInTown = new AiPositions(); List<ShortPoint2D> threatenedBorder; final long[] resourceCount = new long[EResourceType.VALUES.length]; int numberOfNotFinishedBuildings; int numberOfTotalBuildings; int numberOfNotOccupiedMilitaryBuildings; int wineCount; IMaterialProductionSettings materialProduction; PlayerStatistic() { clearIntegers(); } public void clearAll() { isAlive = false; materials = null; buildingPositions.clear(); enemyTroopsInTown.clear(); stones.clear(); stonesNearBy.clear(); trees.clear(); rivers.clear(); landToBuildOn.clear(); border.clear(); otherPartitionBorder.clear(); movablePositions.clear(); farmWorkAreas.clear(); wineGrowerWorkAreas.clear(); threatenedBorder = null; clearIntegers(); } private void clearIntegers() { Arrays.fill(totalBuildingsNumbers, 0); Arrays.fill(buildingsNumbers, 0); Arrays.fill(resourceCount, 0); numberOfNotFinishedBuildings = 0; numberOfTotalBuildings = 0; numberOfNotOccupiedMilitaryBuildings = 0; wineCount = 0; partitionIdToBuildOn = Short.MIN_VALUE; } } }
Optimized SameBlockedPartitionLikePlayerFilter by calculating the blocked partition of a player only once.
jsettlers.logic/src/main/java/jsettlers/ai/highlevel/AiStatistics.java
Optimized SameBlockedPartitionLikePlayerFilter by calculating the blocked partition of a player only once.
Java
mit
e033bf4a25eeb8211422cbaeff6044ee803601e9
0
overengineering/space-travels-3,overengineering/space-travels-3,overengineering/space-travels-3
package com.draga.spaceTravels3.manager; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.math.Vector2; import com.draga.spaceTravels3.Constants; public class InputManager { public static final float DEAD_ZONE = 0.15f; private static final String LOGGING_TAG = InputManager.class.getSimpleName(); /** * Change tilt range. E.g. 1.0f = 90 degree max. 0.5f = 45 degrees max. */ private static final float ACCELEROMETER_RANGE = 0.5f; private static Vector2 inputForce; /** * Returns a vector with length from 0 to 1, representing where the input is pointing to, * abstracting away the fact that it could be a mobile accelerometer, mouse clicks, etc. * * @return A Vector2 of length from 0 to 1 of where the input is pointing */ public static Vector2 getInputForce() { return inputForce.cpy(); } public static void update() { Vector2 input; switch (Gdx.app.getType()) { // TODO: preferences based with adapters? case Android: case iOS: switch (SettingsManager.getSettings().inputType) { case ACCELEROMETER: input = getAccelerometerInput(); break; case TOUCH: input = getTouchInput(); break; default: Gdx.app.error( LOGGING_TAG, SettingsManager.getSettings().inputType + " input type not implemented."); input = new Vector2(); } break; case Desktop: input = getKeyboardInput(); if (input.isZero()) { input = getTouchInput(); } break; default: Gdx.app.error( LOGGING_TAG, "Device type " + Gdx.input.getRotation() + " not implemented."); input = new Vector2(); break; } inputForce = input; } private static Vector2 getAccelerometerInput() { Vector2 input = getDeviceAccelerationForDeviceOrientation() .scl(1f / ACCELEROMETER_RANGE); // Max the gravity by the Earth gravity to avoid excessive force being applied if the device is shaken. input = input.clamp(0, Constants.General.EARTH_GRAVITY); // Scale the input by the Earth's gravity so that I'll be between 1 and 0 input = input.scl(1 / Constants.General.EARTH_GRAVITY); input.x = applyDeadZone(input.x); input.y = applyDeadZone(input.y); return input; } private static Vector2 getTouchInput() { Vector2 input; if (Gdx.input.isButtonPressed(Input.Buttons.LEFT)) { // Height flipped because 0,0 of input is top left, unlike to rest of the API. input = new Vector2(Gdx.input.getX(), Gdx.graphics.getHeight() - Gdx.input.getY()); float smallestDimension = Math.min(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Vector2 screenCenter = new Vector2(Gdx.graphics.getWidth() / 2f, Gdx.graphics.getHeight() / 2f); // This was my idea but before I could put it down Lee totally sneakily // solved just a tiny bit of it. (Stefano) // Distance between the click and the center of the screen. input.sub(screenCenter); // Brings it to [-1,1] input.scl(1/(smallestDimension / 2f)).clamp(0, 1); input.x = applyDeadZone(input.x); input.y = applyDeadZone(input.y); } else { input = Vector2.Zero; } return input; } /** * Checks arrow, WASD and num pad keys and add 1 for each direction requested, then brings the * vector between 0 and 1. */ private static Vector2 getKeyboardInput() { Vector2 input = new Vector2().setZero(); if (Gdx.input.isKeyPressed(Input.Keys.UP) || Gdx.input.isKeyPressed(Input.Keys.W) || Gdx.input.isKeyPressed(Input.Keys.DPAD_UP)) { input.add(0, 1); } if (Gdx.input.isKeyPressed(Input.Keys.RIGHT) || Gdx.input.isKeyPressed(Input.Keys.D) || Gdx.input.isKeyPressed(Input.Keys.DPAD_RIGHT)) { input.add(1, 0); } if (Gdx.input.isKeyPressed(Input.Keys.DOWN) || Gdx.input.isKeyPressed(Input.Keys.S) || Gdx.input.isKeyPressed(Input.Keys.DPAD_DOWN)) { input.add(0, -1); } if (Gdx.input.isKeyPressed(Input.Keys.LEFT) || Gdx.input.isKeyPressed(Input.Keys.A) || Gdx.input.isKeyPressed(Input.Keys.DPAD_LEFT)) { input.add(-1, 0); } input.clamp(0, 1); return input; } private static Vector2 getDeviceAccelerationForDeviceOrientation() { Vector2 input = new Vector2(Gdx.input.getAccelerometerX(), Gdx.input.getAccelerometerY()); adjustAccelerometerForScreenRotation(input); return input; } private static float applyDeadZone(float value) { float sign = Math.signum(value); if (Math.abs(value) > DEAD_ZONE) { // Move range up by dead zone. value -= DEAD_ZONE * sign; // Squash to (dead zone to 1). So dead zone is 0, screen max is 1 value /= (1 - DEAD_ZONE); } else { value = 0f; } return value; } private static void adjustAccelerometerForScreenRotation(Vector2 input) { // Rotate the vector "manually" instead of using input.rotate(Gdx.input.getRotation()) // because it doesn't need expensive operations. switch (Gdx.input.getRotation()) { case 0: break; case 90: //noinspection SuspiciousNameCombination input.set(input.y, -input.x); break; case 180: input.set(-input.x, -input.y); break; case 270: //noinspection SuspiciousNameCombination input.set(-input.y, input.x); break; default: Gdx.app.error( LOGGING_TAG, "Orientation " + Gdx.input.getRotation() + " not implemented."); } } }
core/src/com/draga/spaceTravels3/manager/InputManager.java
package com.draga.spaceTravels3.manager; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.math.Vector2; import com.draga.spaceTravels3.Constants; import com.sun.istack.internal.Pool; public class InputManager { public static final float DEAD_ZONE = 0.15f; private static final String LOGGING_TAG = InputManager.class.getSimpleName(); /** * Change tilt range. E.g. 1.0f = 90 degree max. 0.5f = 45 degrees max. */ private static final float ACCELEROMETER_RANGE = 0.5f; private static Vector2 inputForce; /** * Returns a vector with length from 0 to 1, representing where the input is pointing to, * abstracting away the fact that it could be a mobile accelerometer, mouse clicks, etc. * * @return A Vector2 of length from 0 to 1 of where the input is pointing */ public static Vector2 getInputForce() { return inputForce.cpy(); } public static void update() { Vector2 input; switch (Gdx.app.getType()) { // TODO: preferences based with adapters? case Android: case iOS: switch (SettingsManager.getSettings().inputType) { case ACCELEROMETER: input = getAccelerometerInput(); break; case TOUCH: input = getTouchInput(); break; default: Gdx.app.error( LOGGING_TAG, SettingsManager.getSettings().inputType + " input type not implemented."); input = new Vector2(); } break; case Desktop: input = getKeyboardInput(); if (input.isZero()) { input = getTouchInput(); } break; default: Gdx.app.error( LOGGING_TAG, "Device type " + Gdx.input.getRotation() + " not implemented."); input = new Vector2(); break; } inputForce = input; } private static Vector2 getAccelerometerInput() { Vector2 input = getDeviceAccelerationForDeviceOrientation() .scl(1f / ACCELEROMETER_RANGE); // Max the gravity by the Earth gravity to avoid excessive force being applied if the device is shaken. input = input.clamp(0, Constants.General.EARTH_GRAVITY); // Scale the input by the Earth's gravity so that I'll be between 1 and 0 input = input.scl(1 / Constants.General.EARTH_GRAVITY); input.x = applyDeadZone(input.x); input.y = applyDeadZone(input.y); return input; } private static Vector2 getTouchInput() { Vector2 input; if (Gdx.input.isButtonPressed(Input.Buttons.LEFT)) { // Height flipped because 0,0 of input is top left, unlike to rest of the API. input = new Vector2(Gdx.input.getX(), Gdx.graphics.getHeight() - Gdx.input.getY()); float smallestDimension = Math.min(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Vector2 screenCenter = new Vector2(Gdx.graphics.getWidth() / 2f, Gdx.graphics.getHeight() / 2f); // This was my idea but before I could put it down Lee totally sneakily // solved just a tiny bit of it. (Stefano) // Distance between the click and the center of the screen. input.sub(screenCenter); // Brings it to [-1,1] input.scl(1/(smallestDimension / 2f)).clamp(0, 1); input.x = applyDeadZone(input.x); input.y = applyDeadZone(input.y); } else { input = Vector2.Zero; } return input; } /** * Checks arrow, WASD and num pad keys and add 1 for each direction requested, then brings the * vector between 0 and 1. */ private static Vector2 getKeyboardInput() { Vector2 input = new Vector2().setZero(); if (Gdx.input.isKeyPressed(Input.Keys.UP) || Gdx.input.isKeyPressed(Input.Keys.W) || Gdx.input.isKeyPressed(Input.Keys.DPAD_UP)) { input.add(0, 1); } if (Gdx.input.isKeyPressed(Input.Keys.RIGHT) || Gdx.input.isKeyPressed(Input.Keys.D) || Gdx.input.isKeyPressed(Input.Keys.DPAD_RIGHT)) { input.add(1, 0); } if (Gdx.input.isKeyPressed(Input.Keys.DOWN) || Gdx.input.isKeyPressed(Input.Keys.S) || Gdx.input.isKeyPressed(Input.Keys.DPAD_DOWN)) { input.add(0, -1); } if (Gdx.input.isKeyPressed(Input.Keys.LEFT) || Gdx.input.isKeyPressed(Input.Keys.A) || Gdx.input.isKeyPressed(Input.Keys.DPAD_LEFT)) { input.add(-1, 0); } input.clamp(0, 1); return input; } private static Vector2 getDeviceAccelerationForDeviceOrientation() { Vector2 input = new Vector2(Gdx.input.getAccelerometerX(), Gdx.input.getAccelerometerY()); adjustAccelerometerForScreenRotation(input); return input; } private static float applyDeadZone(float value) { float sign = Math.signum(value); if (Math.abs(value) > DEAD_ZONE) { // Move range up by dead zone. value -= DEAD_ZONE * sign; // Squash to (dead zone to 1). So dead zone is 0, screen max is 1 value /= (1 - DEAD_ZONE); } else { value = 0f; } return value; } private static void adjustAccelerometerForScreenRotation(Vector2 input) { // Rotate the vector "manually" instead of using input.rotate(Gdx.input.getRotation()) // because it doesn't need expensive operations. switch (Gdx.input.getRotation()) { case 0: break; case 90: //noinspection SuspiciousNameCombination input.set(input.y, -input.x); break; case 180: input.set(-input.x, -input.y); break; case 270: //noinspection SuspiciousNameCombination input.set(-input.y, input.x); break; default: Gdx.app.error( LOGGING_TAG, "Orientation " + Gdx.input.getRotation() + " not implemented."); } } }
fix wrong import
core/src/com/draga/spaceTravels3/manager/InputManager.java
fix wrong import
Java
mit
a120eb4215e8f2a99e0809e5be5330012f3b5520
0
ligoj/ligoj,ligoj/ligoj,ligoj/ligoj,ligoj/ligoj
/* * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE) */ package org.ligoj.app.resource.plugin; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Paths; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.activation.FileTypeMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FilenameUtils; import lombok.extern.slf4j.Slf4j; /** * <p> * This servlet enables Servlet 2.x compliant containers to serve up Webjars resources * </p> * <p> * Copied from org.webjars:webjars-servlet-2.x:1.5, because we need to retrieve webjars resources from Thread * Classloader and not only in web-inf/lib. We also removed cache management. * </p> */ @Slf4j public class WebjarsServlet extends HttpServlet { /** * serial version uid */ private static final long serialVersionUID = 2461047578940577569L; /** * Additional mime types */ private final Map<String, String> mimeTypes = new HashMap<>(); /** * Constructor registering additional MIME types. */ public WebjarsServlet() { // Register additional MIME types mimeTypes.put("woff", "application/font-woff"); mimeTypes.put("woff2", "font/woff2"); mimeTypes.put("ttf", "application/x-font-truetype"); mimeTypes.put("eot", "application/vnd.ms-fontobject"); mimeTypes.put("svg", "image/svg+xml"); mimeTypes.put("otf", "application/x-font-opentype"); } @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final String webjarsResourceURI = "META-INF/resources" + request.getRequestURI().replaceFirst(request.getContextPath(), ""); log.debug("Webjars resource requested: {}", webjarsResourceURI); if (isDirectoryRequest(webjarsResourceURI)) { // Directory listing is forbidden, but act as a 404 for security purpose. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Regular file, use the last resource instead of the first found final Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(webjarsResourceURI); URL webjarsResourceURL = null; while(resources.hasMoreElements()) { webjarsResourceURL = resources.nextElement(); } if (webjarsResourceURL == null) { // File not found --> 404 response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { serveFile(response, webjarsResourceURI, webjarsResourceURL.openStream()); } } /** * Copy the file stream to the response using the right mime type */ private void serveFile(final HttpServletResponse response, final String webjarsResourceURI, final InputStream inputStream) throws IOException { try { final String filename = getFileName(webjarsResourceURI); response.setContentType(guessMimeType(filename)); inputStream.transferTo(response.getOutputStream()); response.flushBuffer(); } finally { inputStream.close(); } } /** * Guess the MIME type from the file name. * * @param filename * The requested file name. * @return The resolved MIME type. May be <code>null</code>. */ protected String guessMimeType(final String filename) { // First, get the mime type provided by the Servlet container String mimeType = this.getServletContext().getMimeType(filename); if (mimeType == null) { // Use the static extension based extension mimeType = mimeTypes.get(FilenameUtils.getExtension(filename)); } if (mimeType == null) { // Use the mime type guess by JSE mimeType = FileTypeMap.getDefaultFileTypeMap().getContentType(filename); } return mimeType; } /** * Is it a directory request ? * * @param uri * Requested resource's URI. * @return <code>true</code> when URI is a directory request */ private static boolean isDirectoryRequest(final String uri) { return uri.endsWith("/"); } /** * Retrieve file name from given URI. * * @param webjarsResourceURI * Requested resource's URI. * @return The resolved file name. */ private String getFileName(final String webjarsResourceURI) { return Paths.get(webjarsResourceURI).toFile().getName(); } }
app-api/src/main/java/org/ligoj/app/resource/plugin/WebjarsServlet.java
/* * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE) */ package org.ligoj.app.resource.plugin; import java.io.IOException; import java.io.InputStream; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import javax.activation.FileTypeMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FilenameUtils; import lombok.extern.slf4j.Slf4j; /** * <p> * This servlet enables Servlet 2.x compliant containers to serve up Webjars resources * </p> * <p> * Copied from org.webjars:webjars-servlet-2.x:1.5, because we need to retrieve webjars resources from Thread * Classloader and not only in web-inf/lib. We also removed cache management. * </p> */ @Slf4j public class WebjarsServlet extends HttpServlet { /** * serial version uid */ private static final long serialVersionUID = 2461047578940577569L; /** * Additional mime types */ private final Map<String, String> mimeTypes = new HashMap<>(); /** * Constructor registering additional MIME types. */ public WebjarsServlet() { // Register additional MIME types mimeTypes.put("woff", "application/font-woff"); mimeTypes.put("woff2", "font/woff2"); mimeTypes.put("ttf", "application/x-font-truetype"); mimeTypes.put("eot", "application/vnd.ms-fontobject"); mimeTypes.put("svg", "image/svg+xml"); mimeTypes.put("otf", "application/x-font-opentype"); } @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final String webjarsResourceURI = "META-INF/resources" + request.getRequestURI().replaceFirst(request.getContextPath(), ""); log.debug("Webjars resource requested: {}", webjarsResourceURI); if (isDirectoryRequest(webjarsResourceURI)) { // Directory listing is forbidden, but act as a 404 for security purpose. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Regular file final InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(webjarsResourceURI); if (inputStream == null) { // File not found --> 404 response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { serveFile(response, webjarsResourceURI, inputStream); } } /** * Copy the file stream to the response using the right mime type */ private void serveFile(final HttpServletResponse response, final String webjarsResourceURI, final InputStream inputStream) throws IOException { try { final String filename = getFileName(webjarsResourceURI); response.setContentType(guessMimeType(filename)); inputStream.transferTo(response.getOutputStream()); response.flushBuffer(); } finally { inputStream.close(); } } /** * Guess the MIME type from the file name. * * @param filename * The requested file name. * @return The resolved MIME type. May be <code>null</code>. */ protected String guessMimeType(final String filename) { // First, get the mime type provided by the Servlet container String mimeType = this.getServletContext().getMimeType(filename); if (mimeType == null) { // Use the static extension based extension mimeType = mimeTypes.get(FilenameUtils.getExtension(filename)); } if (mimeType == null) { // Use the mime type guess by JSE mimeType = FileTypeMap.getDefaultFileTypeMap().getContentType(filename); } return mimeType; } /** * Is it a directory request ? * * @param uri * Requested resource's URI. * @return <code>true</code> when URI is a directory request */ private static boolean isDirectoryRequest(final String uri) { return uri.endsWith("/"); } /** * Retrieve file name from given URI. * * @param webjarsResourceURI * Requested resource's URI. * @return The resolved file name. */ private String getFileName(final String webjarsResourceURI) { return Paths.get(webjarsResourceURI).toFile().getName(); } }
Support multiple versions of the same plug-in in classpath
app-api/src/main/java/org/ligoj/app/resource/plugin/WebjarsServlet.java
Support multiple versions of the same plug-in in classpath
Java
mit
dc4a9cc561697ef876d638d093888ce7391bb60a
0
InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service
package org.innovateuk.ifs.application.transactional; import org.innovateuk.ifs.application.domain.ApplicationStatistics; import org.innovateuk.ifs.application.mapper.ApplicationCountSummaryPageMapper; import org.innovateuk.ifs.application.repository.ApplicationRepository; import org.innovateuk.ifs.application.repository.ApplicationStatisticsRepository; import org.innovateuk.ifs.application.resource.ApplicationCountSummaryPageResource; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.transactional.BaseTransactionalService; import org.innovateuk.ifs.user.repository.OrganisationRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; import java.util.Optional; import static org.innovateuk.ifs.application.transactional.ApplicationSummaryServiceImpl.SUBMITTED_STATES; import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError; import static org.innovateuk.ifs.util.EntityLookupCallbacks.find; import static org.springframework.data.domain.Sort.Direction.ASC; import static org.springframework.data.domain.Sort.Direction.DESC; @Service public class ApplicationCountSummaryServiceImpl extends BaseTransactionalService implements ApplicationCountSummaryService { @Autowired private ApplicationCountSummaryPageMapper applicationCountSummaryPageMapper; @Autowired private ApplicationStatisticsRepository applicationStatisticsRepository; private static final Map<String, Sort> SORT_FIELD_TO_DB_SORT_FIELDS = new HashMap<String, Sort>() {{ put("id", new Sort(ASC, "id")); put("appTitle", new Sort(ASC, "name", "id")); put("leadOrg", new Sort(ASC, "leadOrganisation", "id")); put("assignedApps", new Sort(ASC, "assessors", "id")); put("completedApps", new Sort(ASC, "submitted", "id")); }}; @Override public ServiceResult<ApplicationCountSummaryPageResource> getApplicationCountSummariesByCompetitionId(long competitionId, int pageIndex, int pageSize, Optional<String> filter) { String filterStr = filter.map(String::trim).orElse(""); Pageable pageable = new PageRequest(pageIndex, pageSize); Page<ApplicationStatistics> applicationStatistics = applicationStatisticsRepository.findByCompetitionAndApplicationProcessActivityStateStateIn(competitionId, SUBMITTED_STATES, filterStr, pageable); return find(applicationStatistics, notFoundError(Page.class)).andOnSuccessReturn(stats -> applicationCountSummaryPageMapper.mapToResource(stats)); } @Override public ServiceResult<ApplicationCountSummaryPageResource> getApplicationCountSummariesByCompetitionIdAndInnovationArea(long competitionId, long assessorId, int pageIndex, int pageSize, Optional<Long> innovationArea, String sortField) { Sort sort = getApplicationSummarySortField(sortField); Pageable pageable = new PageRequest(pageIndex, pageSize, sort); Page<ApplicationStatistics> applicationStatistics = applicationStatisticsRepository.findByCompetitionAndInnovationAreaProcessActivityStateStateIn(competitionId, assessorId, SUBMITTED_STATES, innovationArea.orElse(null), pageable); return find(applicationStatistics, notFoundError(Page.class)).andOnSuccessReturn(stats -> applicationCountSummaryPageMapper.mapToResource(stats)); } private Sort getApplicationSummarySortField(String sortBy) { Sort result = SORT_FIELD_TO_DB_SORT_FIELDS.get(sortBy); return result != null ? result : SORT_FIELD_TO_DB_SORT_FIELDS.get("id"); } }
ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/application/transactional/ApplicationCountSummaryServiceImpl.java
package org.innovateuk.ifs.application.transactional; import org.innovateuk.ifs.application.domain.ApplicationStatistics; import org.innovateuk.ifs.application.mapper.ApplicationCountSummaryPageMapper; import org.innovateuk.ifs.application.repository.ApplicationRepository; import org.innovateuk.ifs.application.repository.ApplicationStatisticsRepository; import org.innovateuk.ifs.application.resource.ApplicationCountSummaryPageResource; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.transactional.BaseTransactionalService; import org.innovateuk.ifs.user.repository.OrganisationRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; import java.util.Optional; import static org.innovateuk.ifs.application.transactional.ApplicationSummaryServiceImpl.SUBMITTED_STATES; import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError; import static org.innovateuk.ifs.util.EntityLookupCallbacks.find; import static org.springframework.data.domain.Sort.Direction.ASC; import static org.springframework.data.domain.Sort.Direction.DESC; @Service public class ApplicationCountSummaryServiceImpl extends BaseTransactionalService implements ApplicationCountSummaryService { @Autowired private ApplicationCountSummaryPageMapper applicationCountSummaryPageMapper; @Autowired private ApplicationStatisticsRepository applicationStatisticsRepository; private static final Map<String, Sort> SORT_FIELD_TO_DB_SORT_FIELDS = new HashMap<String, Sort>() {{ put("appTitle", new Sort(ASC, new String[]{"name", "id"})); put("leadOrg", new Sort(ASC, new String[]{"leadOrganisation", "id"})); put("assignedApps", new Sort(ASC, new String[]{"assessors", "id"})); put("completedApps", new Sort(ASC, new String[]{"submitted", "id"})); }}; @Override public ServiceResult<ApplicationCountSummaryPageResource> getApplicationCountSummariesByCompetitionId(long competitionId, int pageIndex, int pageSize, Optional<String> filter) { String filterStr = filter.map(String::trim).orElse(""); Pageable pageable = new PageRequest(pageIndex, pageSize); Page<ApplicationStatistics> applicationStatistics = applicationStatisticsRepository.findByCompetitionAndApplicationProcessActivityStateStateIn(competitionId, SUBMITTED_STATES, filterStr, pageable); return find(applicationStatistics, notFoundError(Page.class)).andOnSuccessReturn(stats -> applicationCountSummaryPageMapper.mapToResource(stats)); } @Override public ServiceResult<ApplicationCountSummaryPageResource> getApplicationCountSummariesByCompetitionIdAndInnovationArea(long competitionId, long assessorId, int pageIndex, int pageSize, Optional<Long> innovationArea, String sortField) { Sort sort = getApplicationSummarySortField(sortField); Pageable pageable = new PageRequest(pageIndex, pageSize, sort); Page<ApplicationStatistics> applicationStatistics = applicationStatisticsRepository.findByCompetitionAndInnovationAreaProcessActivityStateStateIn(competitionId, assessorId, SUBMITTED_STATES, innovationArea.orElse(null), pageable); return find(applicationStatistics, notFoundError(Page.class)).andOnSuccessReturn(stats -> applicationCountSummaryPageMapper.mapToResource(stats)); } private Sort getApplicationSummarySortField(String sortBy) { Sort result = SORT_FIELD_TO_DB_SORT_FIELDS.get(sortBy); return result != null ? result : new Sort(ASC, new String[]{"id"}); } }
IFS-321 Tidy up of service for review comment.
ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/application/transactional/ApplicationCountSummaryServiceImpl.java
IFS-321 Tidy up of service for review comment.
Java
cc0-1.0
31cfbbef4a98de6d5e01c7ea63bb37d063a4f4ae
0
dmascenik/teamrank
package com.danmascenik.tools.teamrank; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import com.danmascenik.tools.teamrank.Rank.RankComparator; /** * A square matrix containing the raw data for a team rank calculation, encapsulating all the details of * transforming the matrix such that the power method will yield a stationary vector. New instances must be * constructed using the inner {@link Builder} class. <br/> * <br/> * Key assumptions to ensure convergence to a stationary vector:<br> * <br/> * <ol> * <li><b>The matrix must be stochastic</b>: This means that all the entries are non-negative and the sum of * the entries in each column is 1. Since a team member can only vote for another team member once, every * entry in the matrix is either zero or one. Simply dividing each entry by the number of non-zero entries in * the column ensures that the column adds up to one.<br/> * <br/> * But what if a column is all zeros? This happens when a team member didn't vote for anyone. <i>To make the * matrix stochastic, we will assume that voting for no one is the same as voting for everyone.</i><br/> * <br/> * </li> * <li><b>The matrix must be irreducible</b>: In order to guarantee that the power method will converge to a * single stationary vector regardless of the starting vector, there can't be any sub-groups whose votes only * come from their fellow members. However, cliques are inevitable even on modestly sized teams. Everyone * can't possibly know everything about everyone else. To make the matrix irreducible, we will assume that * <i>if a team member randomly selects another team member and gets to know them, there is some probability * that they will discover some positive influence, regardless of how they voted.</i> The probability that * positive influence will come from an unexpected source injects a probability factor to make the matrix * irreducible.</li> * </ol> * * @author Dan Mascenik * @param <T> The type used for voters'/votees' unique identifier (e.g. their name as a String, or a mapped * UUID). This type must be suitable for use as a key in a HashMap. */ public class VoteMatrix<T> { public static final float BREAKOUT_PROBABILITY = 0.15f; public static final int MAX_ITERATIONS = 1000; public static final float CONVERGENCE_MAX_DELTA = 0.0001f; private float[][] v; private float[][] a; private boolean hasVotes = false; private float bProb = BREAKOUT_PROBABILITY; private int iterationCount = -1; /** * Correlates voters'/votees' unique identifiers to indices on the axes of the square v. */ private Map<T,Integer> indexMap = new HashMap<T,Integer>(); /** * The reverse index of {@link #indexMap} */ private Map<Integer,T> revIndex = new HashMap<Integer,T>(); private VoteMatrix(Set<T> ids) { Objects.requireNonNull(ids); int size = ids.size(); if (size == 0) { throw new IllegalArgumentException(VoteMatrix.class.getName() + " requires at least one voter"); } v = new float[size][size]; a = new float[size][size]; int idx = 0; for (T id : ids) { indexMap.put(id, idx); revIndex.put(idx, id); idx++; } } private void putVote(T from, T to) { if (from.equals(to)) { return; // don't count self votes } int f = getVoterIndex(from); int t = getVoterIndex(to); v[f][t] = 1f; hasVotes = true; } private int getVoterIndex(T id) { if (!indexMap.keySet().contains(id)) { throw new IllegalArgumentException("Unknown voter: " + id); } return indexMap.get(id).intValue(); } /** * Makes the provided square matrix stochastic by dividing every value by the number of non-zero values in * its column. For all-zero columns, set the value to the inverse of the number of rows in the matrix. This * means that if someone doesn't vote for anyone, it's the same as if they voted for everyone. This does not * affect the results of {@link #getVoters(Object)} or {@link #getVotes(Object)} */ private void makeStochastic() { for (int from = 0; from < v.length; from++) { int count = 0; for (int to = 0; to < v.length; to++) { if (v[from][to] > 0.0f) { count++; } } for (int to = 0; to < v.length; to++) { if (count == 0.0f) { if (from != to) { a[from][to] = (float)(1.0f / (v.length - 1)); } } else { v[from][to] = (float)(v[from][to] / count); } } } } /** * Votes may be cyclic, making the matrix reducible, thus not having a stationary vector. Since finding a * stationary vector (the dominant eigenvector) of the matrix is how we plan to get a rank, this is a * problem. This problem is overcome by introducing some probability that people will not strictly stick to * their votes. How do we get away with this? Even on a small team, everyone won't know everything about * everyone else. There is a chance that given the opportunity to learn more about any individual, they will * discover something that they find positive, whether they voted for that person or not. Larry Page and * Sergey Brin chose 15% for PageRank, so that is the default. * * @param bProb */ public void setBreakoutProbability(float breakoutProbability) { if (!(breakoutProbability > 0f) || breakoutProbability > 1f) { throw new IllegalArgumentException( "Breakout probability must be greater than zero and less than or equal to one"); } this.bProb = breakoutProbability; } public float getBreakoutProbability() { return this.bProb; } public float[] getDominantEigenvector() { /* Calculate the stochastic, irreducible matrix by adding v to a and introducing the probability factor to * the result. */ float[][] g = new float[v.length][v.length]; for (int from = 0; from < v.length; from++) { for (int to = 0; to < v.length; to++) { g[from][to] = (v[from][to] + a[from][to]) * (1 - bProb) + bProb / v.length; } } iterationCount = 0; // Initial vector of all ones float[] iin = new float[g.length]; for (int i = 0; i < g.length; i++) { iin[i] = 1; } float[] iout = new float[g.length]; /* Here's the power method in action. The stochastic, irreducible matrix is multiplied by the initial * vector of all 1's, resulting in another vector. The matrix is then multiplied by that vector. This * process continues until the result has converged on a stationary vector (the dominant eigenvector). */ while (iterationCount < MAX_ITERATIONS && !converged(iin, iout)) { if (iterationCount != 0) { iin = iout; } iout = multiply(g, iin); iout = normalize(iout); iterationCount++; } return iout; } /** * Returns the ranking results as a sorted list of {@link Rank}s, with the highest first. * * @param usePercentages true will return the scores as percentages (adding up to 100%), otherwise raw * scores will be returned. */ public List<Rank<T>> getResults(boolean usePercentages) { float[] i = getDominantEigenvector(); float total = 0f; if (usePercentages) { for (float score : i) { total += score; } } List<Rank<T>> results = new ArrayList<Rank<T>>(); for (int x = 0; x < i.length; x++) { float score = usePercentages ? i[x] / total : i[x]; Rank<T> rank = new Rank<T>(getVoterForIndex(x), score); results.add(rank); } Collections.sort(results, new RankComparator()); return results; } /** * Convenience method for {@link #getResults(boolean)} with usePercentages set to false. */ public List<Rank<T>> getResults() { return getResults(false); } /** * Returns the number of iterations it took for the power method to converge the last time * {@link #getDominantEigenvector()} was called. If {@link #getDominantEigenvector()} has not yet been * called, this will return -1. */ public int getIterationCount() { return this.iterationCount; } /** * Returns the identifiers of all the votes cast by the provided voter. * * @param id */ public Set<T> getVotes(T id) { float[] row = v[getVoterIndex(id)]; Set<T> votes = new HashSet<T>(); for (int idx = 0; idx < row.length; idx++) { float v = row[idx]; if (v > 0) { votes.add(revIndex.get(idx)); } } return votes; } /** * Returns the identifiers of all those who voted for the provided team member. * * @param id */ public Set<T> getVoters(T id) { int rcptIdx = getVoterIndex(id); Set<T> voters = new HashSet<T>(); for (int idx = 0; idx < v.length; idx++) { float vote = v[idx][rcptIdx]; if (vote > 0) { voters.add(revIndex.get(idx)); } } return voters; } /** * Returns the raw value from the specified spot in the v * * @param from * @param to */ public float valueAt(T from, T to) { int f = getVoterIndex(from); int t = getVoterIndex(to); return v[f][t] + a[f][t]; } public T getVoterForIndex(int idx) { T voter = revIndex.get(idx); if (voter == null) { throw new IllegalArgumentException("Invalid index: " + idx); } return voter; } /** * Returns true if none of the array elements differ by more than 0.0001 * * @param in * @param out * @return */ protected static boolean converged(float[] in, float[] out) { if (in.length != out.length) { throw new IllegalArgumentException("input arrays must be of the same length"); } for (int i = 0; i < in.length; i++) { float diff = in[i] - out[i]; diff = Math.abs(diff); if (diff > CONVERGENCE_MAX_DELTA) { return false; } } return true; } /** * Normalizes a vector by dividing each element by the value of the nth element, making the last element * equal to one. * * @param v * @return */ protected static float[] normalize(float[] v) { if (v.length == 0 || v[v.length - 1] == 0) { throw new IllegalArgumentException( "Vector to normalize must have a non-zero length and a non-zero last element"); } for (int i = 0; i < v.length; i++) { v[i] = v[i] / v[v.length - 1]; } return v; } /** * Multiplies the matrix m by the vector v * * @param m * @param v * @return */ protected static float[] multiply(float[][] m, float[] v) { if (m.length != v.length) { throw new IllegalArgumentException("vector is not the same length as the square matrix"); } float[] out = new float[v.length]; for (int y = 0; y < m.length; y++) { float temp = 0; for (int x = 0; x < m.length; x++) { temp += v[x] * m[x][y]; } out[y] = temp; } return out; } /** * Constructs a {@link VoteMatrix} and inserts votes into it. Votes are idempotent; i.e., if one person * votes for another multiple times, it still only counts once. */ public static class Builder<TT> { private VoteMatrix<TT> voteMatrix; private boolean isBuilt = false; /** * @param ids A set of unique identifiers for the team members */ public Builder(Set<TT> ids) { Objects.requireNonNull(ids); voteMatrix = new VoteMatrix<TT>(ids); } public void castVote(TT from, TT to) { assertNotBuilt(); voteMatrix.putVote(from, to); } public void validate(TT id) { voteMatrix.getVoterIndex(id); } /** * Convenience method for {@link #castVote(Object, Object)} that loops over multiple votes */ public void castVotes(TT from, Set<TT> to) { for (TT t : to) { castVote(from, t); } } /** * Returns the completed {@link VoteMatrix} and prevents any further modifications. */ public synchronized VoteMatrix<TT> build() { assertNotBuilt(); isBuilt = true; if (!voteMatrix.hasVotes) { throw new IllegalStateException("Cannot build - v contains no votes!"); } VoteMatrix<TT> m = voteMatrix; voteMatrix = null; m.makeStochastic(); return m; } private synchronized void assertNotBuilt() { if (isBuilt) { throw new IllegalStateException(VoteMatrix.class.getName() + " was already built!"); } } } }
src/main/java/com/danmascenik/tools/teamrank/VoteMatrix.java
package com.danmascenik.tools.teamrank; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.danmascenik.tools.teamrank.Rank.RankComparator; /** * A square matrix containing the raw data for a team rank calculation, encapsulating all the details of * transforming the matrix such that the power method will yield a stationary vector. New instances must be * constructed using the inner {@link Builder} class. <br/> * <br/> * Key assumptions to ensure convergence to a stationary vector:<br> * <br/> * <ol> * <li><b>The matrix must be stochastic</b>: This means that all the entries are non-negative and the sum of * the entries in each column is 1. Since a team member can only vote for another team member once, every * entry in the matrix is either zero or one. Simply dividing each entry by the number of non-zero entries in * the column ensures that the column adds up to one.<br/> * <br/> * But what if a column is all zeros? This happens when a team member didn't vote for anyone. <i>To make the * matrix stochastic, we will assume that voting for no one is the same as voting for everyone.</i><br/> * <br/> * </li> * <li><b>The matrix must be irreducible</b>: In order to guarantee that the power method will converge to a * single stationary vector regardless of the starting vector, there can't be any sub-groups whose votes only * come from their fellow members. However, cliques are inevitable even on modestly sized teams. Everyone * can't possibly know everything about everyone else. To make the matrix irreducible, we will assume that * <i>if a team member randomly selects another team member and gets to know them, there is some probability * that they will discover some positive influence, regardless of how they voted.</i> The probability that * positive influence will come from an unexpected source injects a probability factor to make the matrix * irreducible.</li> * </ol> * * @author Dan Mascenik * @param <T> The type used for voters'/votees' unique identifier (e.g. their name as a String, or a mapped * UUID). This type must be suitable for use as a key in a HashMap. */ public class VoteMatrix<T> { public static final float BREAKOUT_PROBABILITY = 0.15f; public static final int MAX_ITERATIONS = 1000; public static final float CONVERGENCE_MAX_DELTA = 0.0001f; private float[][] v; private float[][] a; private boolean hasVotes = false; private float bProb = BREAKOUT_PROBABILITY; private int iterationCount = -1; /** * Correlates voters'/votees' unique identifiers to indices on the axes of the square v. */ private Map<T,Integer> indexMap = new HashMap<T,Integer>(); /** * The reverse index of {@link #indexMap} */ private Map<Integer,T> revIndex = new HashMap<Integer,T>(); private VoteMatrix(Set<T> ids) { int size = ids.size(); if (size == 0) { throw new IllegalArgumentException(VoteMatrix.class.getName() + " requires at least one voter"); } v = new float[size][size]; a = new float[size][size]; int idx = 0; for (T id : ids) { indexMap.put(id, idx); revIndex.put(idx, id); idx++; } } private void putVote(T from, T to) { if (from.equals(to)) { return; // don't count self votes } int f = getVoterIndex(from); int t = getVoterIndex(to); v[f][t] = 1f; hasVotes = true; } private int getVoterIndex(T id) { if (!indexMap.keySet().contains(id)) { throw new IllegalArgumentException("Unknown voter: " + id); } return indexMap.get(id).intValue(); } /** * Makes the provided square matrix stochastic by dividing every value by the number of non-zero values in * its column. For all-zero columns, set the value to the inverse of the number of rows in the matrix. This * means that if someone doesn't vote for anyone, it's the same as if they voted for everyone. This does not * affect the results of {@link #getVoters(Object)} or {@link #getVotes(Object)} */ private void makeStochastic() { for (int from = 0; from < v.length; from++) { int count = 0; for (int to = 0; to < v.length; to++) { if (v[from][to] > 0.0f) { count++; } } for (int to = 0; to < v.length; to++) { if (count == 0.0f) { if (from != to) { a[from][to] = (float)(1.0f / (v.length - 1)); } } else { v[from][to] = (float)(v[from][to] / count); } } } } /** * Votes may be cyclic, making the matrix reducible, thus not having a stationary vector. Since finding a * stationary vector (the dominant eigenvector) of the matrix is how we plan to get a rank, this is a * problem. This problem is overcome by introducing some probability that people will not strictly stick to * their votes. How do we get away with this? Even on a small team, everyone won't know everything about * everyone else. There is a chance that given the opportunity to learn more about any individual, they will * discover something that they find positive, whether they voted for that person or not. Larry Page and * Sergey Brin chose 15% for PageRank, so that is the default. * * @param bProb */ public void setBreakoutProbability(float breakoutProbability) { if (!(breakoutProbability > 0f) || breakoutProbability > 1f) { throw new IllegalArgumentException( "Breakout probability must be greater than zero and less than or equal to one"); } this.bProb = breakoutProbability; } public float getBreakoutProbability() { return this.bProb; } public float[] getDominantEigenvector() { /* Calculate the stochastic, irreducible matrix by adding v to a and introducing the probability factor to * the result. */ float[][] g = new float[v.length][v.length]; for (int from = 0; from < v.length; from++) { for (int to = 0; to < v.length; to++) { g[from][to] = (v[from][to] + a[from][to]) * (1 - bProb) + bProb / v.length; } } iterationCount = 0; // Initial vector of all ones float[] iin = new float[g.length]; for (int i = 0; i < g.length; i++) { iin[i] = 1; } float[] iout = new float[g.length]; /* Here's the power method in action. The stochastic, irreducible matrix is multiplied by the initial * vector of all 1's, resulting in another vector. The matrix is then multiplied by that vector. This * process continues until the result has converged on a stationary vector (the dominant eigenvector). */ while (iterationCount < MAX_ITERATIONS && !converged(iin, iout)) { if (iterationCount != 0) { iin = iout; } iout = multiply(g, iin); iout = normalize(iout); iterationCount++; } return iout; } /** * Returns the ranking results as a sorted list of {@link Rank}s, with the highest first. * * @param usePercentages true will return the scores as percentages (adding up to 100%), otherwise raw * scores will be returned. */ public List<Rank<T>> getResults(boolean usePercentages) { float[] i = getDominantEigenvector(); float total = 0f; if (usePercentages) { for (float score : i) { total += score; } } List<Rank<T>> results = new ArrayList<Rank<T>>(); for (int x = 0; x < i.length; x++) { float score = usePercentages ? i[x] / total : i[x]; Rank<T> rank = new Rank<T>(getVoterForIndex(x), score); results.add(rank); } Collections.sort(results, new RankComparator()); return results; } /** * Convenience method for {@link #getResults(boolean)} with usePercentages set to false. */ public List<Rank<T>> getResults() { return getResults(false); } /** * Returns the number of iterations it took for the power method to converge the last time * {@link #getDominantEigenvector()} was called. If {@link #getDominantEigenvector()} has not yet been * called, this will return -1. */ public int getIterationCount() { return this.iterationCount; } /** * Returns the identifiers of all the votes cast by the provided voter. * * @param id */ public Set<T> getVotes(T id) { float[] row = v[getVoterIndex(id)]; Set<T> votes = new HashSet<T>(); for (int idx = 0; idx < row.length; idx++) { float v = row[idx]; if (v > 0) { votes.add(revIndex.get(idx)); } } return votes; } /** * Returns the identifiers of all those who voted for the provided team member. * * @param id */ public Set<T> getVoters(T id) { int rcptIdx = getVoterIndex(id); Set<T> voters = new HashSet<T>(); for (int idx = 0; idx < v.length; idx++) { float vote = v[idx][rcptIdx]; if (vote > 0) { voters.add(revIndex.get(idx)); } } return voters; } /** * Returns the raw value from the specified spot in the v * * @param from * @param to */ public float valueAt(T from, T to) { int f = getVoterIndex(from); int t = getVoterIndex(to); return v[f][t] + a[f][t]; } public T getVoterForIndex(int idx) { T voter = revIndex.get(idx); if (voter == null) { throw new IllegalArgumentException("Invalid index: " + idx); } return voter; } /** * Returns true if none of the array elements differ by more than 0.0001 * * @param in * @param out * @return */ protected static boolean converged(float[] in, float[] out) { if (in.length != out.length) { throw new IllegalArgumentException("input arrays must be of the same length"); } for (int i = 0; i < in.length; i++) { float diff = in[i] - out[i]; diff = Math.abs(diff); if (diff > CONVERGENCE_MAX_DELTA) { return false; } } return true; } /** * Normalizes a vector by dividing each element by the value of the nth element, making the last element * equal to one. * * @param v * @return */ protected static float[] normalize(float[] v) { if (v.length == 0 || v[v.length - 1] == 0) { throw new IllegalArgumentException( "Vector to normalize must have a non-zero length and a non-zero last element"); } for (int i = 0; i < v.length; i++) { v[i] = v[i] / v[v.length - 1]; } return v; } /** * Multiplies the matrix m by the vector v * * @param m * @param v * @return */ protected static float[] multiply(float[][] m, float[] v) { if (m.length != v.length) { throw new IllegalArgumentException("vector is not the same length as the square matrix"); } float[] out = new float[v.length]; for (int y = 0; y < m.length; y++) { float temp = 0; for (int x = 0; x < m.length; x++) { temp += v[x] * m[x][y]; } out[y] = temp; } return out; } /** * Constructs a {@link VoteMatrix} and inserts votes into it. Votes are idempotent; i.e., if one person * votes for another multiple times, it still only counts once. */ public static class Builder<TT> { private VoteMatrix<TT> voteMatrix; private boolean isBuilt = false; /** * @param ids A set of unique identifiers for the team members */ public Builder(Set<TT> ids) { voteMatrix = new VoteMatrix<TT>(ids); } public void castVote(TT from, TT to) { assertNotBuilt(); voteMatrix.putVote(from, to); } public void validate(TT id) { voteMatrix.getVoterIndex(id); } /** * Convenience method for {@link #castVote(Object, Object)} that loops over multiple votes */ public void castVotes(TT from, Set<TT> to) { for (TT t : to) { castVote(from, t); } } /** * Returns the completed {@link VoteMatrix} and prevents any further modifications. */ public synchronized VoteMatrix<TT> build() { assertNotBuilt(); isBuilt = true; if (!voteMatrix.hasVotes) { throw new IllegalStateException("Cannot build - v contains no votes!"); } VoteMatrix<TT> m = voteMatrix; voteMatrix = null; m.makeStochastic(); return m; } private synchronized void assertNotBuilt() { if (isBuilt) { throw new IllegalStateException(VoteMatrix.class.getName() + " was already built!"); } } } }
A couple more explicit not-null checks
src/main/java/com/danmascenik/tools/teamrank/VoteMatrix.java
A couple more explicit not-null checks
Java
epl-1.0
dd45cdafe4c7107f2763dc14f3dc24ce44d8ea92
0
opendaylight/netvirt,opendaylight/netvirt,opendaylight/netvirt,opendaylight/netvirt,opendaylight/netvirt
/* * Copyright (c) 2014 - 2016 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.netvirt.openstack.netvirt.impl; import static org.opendaylight.netvirt.openstack.netvirt.api.Action.ADD; import static org.opendaylight.netvirt.openstack.netvirt.api.Action.DELETE; import static org.opendaylight.netvirt.openstack.netvirt.api.Action.UPDATE; import com.google.common.base.Preconditions; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.opendaylight.netvirt.openstack.netvirt.AbstractEvent; import org.opendaylight.netvirt.openstack.netvirt.AbstractHandler; import org.opendaylight.netvirt.openstack.netvirt.ConfigInterface; import org.opendaylight.netvirt.openstack.netvirt.NeutronL3AdapterEvent; import org.opendaylight.netvirt.openstack.netvirt.api.Action; import org.opendaylight.netvirt.openstack.netvirt.api.ArpProvider; import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService; import org.opendaylight.netvirt.openstack.netvirt.api.Constants; import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher; import org.opendaylight.netvirt.openstack.netvirt.api.GatewayMacResolver; import org.opendaylight.netvirt.openstack.netvirt.api.GatewayMacResolverListener; import org.opendaylight.netvirt.openstack.netvirt.api.IcmpEchoProvider; import org.opendaylight.netvirt.openstack.netvirt.api.InboundNatProvider; import org.opendaylight.netvirt.openstack.netvirt.api.L3ForwardingProvider; import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager; import org.opendaylight.netvirt.openstack.netvirt.api.OutboundNatProvider; import org.opendaylight.netvirt.openstack.netvirt.api.RoutingProvider; import org.opendaylight.netvirt.openstack.netvirt.api.SecurityServicesManager; import org.opendaylight.netvirt.openstack.netvirt.api.Southbound; import org.opendaylight.netvirt.openstack.netvirt.api.Status; import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode; import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager; import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFloatingIP; import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork; import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter; import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter_Interface; import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup; import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs; import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronFloatingIPCRUD; import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD; import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD; import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort; import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet; import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD; import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl.NeutronIAwareUtil; import org.opendaylight.netvirt.utils.neutron.utils.NeutronModelsDataStoreHelper; import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.Routers; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Neutron L3 Adapter implements a hub-like adapter for the various Neutron events. Based on * these events, the abstract router callbacks can be generated to the multi-tenant aware router, * as well as the multi-tenant router forwarding provider. */ public class NeutronL3Adapter extends AbstractHandler implements GatewayMacResolverListener, ConfigInterface { private static final Logger LOG = LoggerFactory.getLogger(NeutronL3Adapter.class); // The implementation for each of these services is resolved by the OSGi Service Manager private volatile ConfigurationService configurationService; private volatile TenantNetworkManager tenantNetworkManager; private volatile NodeCacheManager nodeCacheManager; private volatile INeutronNetworkCRUD neutronNetworkCache; private volatile INeutronSubnetCRUD neutronSubnetCache; private volatile INeutronPortCRUD neutronPortCache; private volatile INeutronFloatingIPCRUD neutronFloatingIpCache; private volatile L3ForwardingProvider l3ForwardingProvider; private volatile InboundNatProvider inboundNatProvider; private volatile OutboundNatProvider outboundNatProvider; private volatile ArpProvider arpProvider; private volatile RoutingProvider routingProvider; private volatile GatewayMacResolver gatewayMacResolver; private volatile SecurityServicesManager securityServicesManager; private volatile IcmpEchoProvider icmpEchoProvider; private class FloatIpData { // br-int of node where floating ip is associated with tenant port private final Long dpid; // patch port in br-int used to reach br-ex private final Long ofPort; // segmentation id of the net where fixed ip is instantiated private final String segId; // mac address assigned to neutron port of floating ip private final String macAddress; private final String floatingIpAddress; // ip address given to tenant vm private final String fixedIpAddress; private final String neutronRouterMac; FloatIpData(final Long dpid, final Long ofPort, final String segId, final String macAddress, final String floatingIpAddress, final String fixedIpAddress, final String neutronRouterMac) { this.dpid = dpid; this.ofPort = ofPort; this.segId = segId; this.macAddress = macAddress; this.floatingIpAddress = floatingIpAddress; this.fixedIpAddress = fixedIpAddress; this.neutronRouterMac = neutronRouterMac; } } private Map<String, String> networkIdToRouterMacCache; private Map<String, List<Neutron_IPs>> networkIdToRouterIpListCache; private Map<String, NeutronRouter_Interface> subnetIdToRouterInterfaceCache; private Map<String, Pair<Long, Uuid>> neutronPortToDpIdCache; private Map<String, FloatIpData> floatIpDataMapCache; private String externalRouterMac; private Boolean enabled = false; private Boolean isCachePopulationDone = false; private Map<String, NeutronPort> portCleanupCache; private Map<String, NeutronNetwork> networkCleanupCache; private Southbound southbound; private DistributedArpService distributedArpService; private NeutronModelsDataStoreHelper neutronModelsDataStoreHelper; private static final String OWNER_ROUTER_INTERFACE = "network:router_interface"; private static final String OWNER_ROUTER_INTERFACE_DISTRIBUTED = "network:router_interface_distributed"; private static final String OWNER_ROUTER_GATEWAY = "network:router_gateway"; private static final String OWNER_FLOATING_IP = "network:floatingip"; private static final String DEFAULT_EXT_RTR_MAC = "00:00:5E:00:01:01"; public NeutronL3Adapter(NeutronModelsDataStoreHelper neutronHelper) { LOG.info(">>>>>> NeutronL3Adapter constructor {}", this.getClass()); this.neutronModelsDataStoreHelper = neutronHelper; } private void initL3AdapterMembers() { Preconditions.checkNotNull(configurationService); if (configurationService.isL3ForwardingEnabled()) { this.networkIdToRouterMacCache = new HashMap<>(); this.networkIdToRouterIpListCache = new HashMap<>(); this.subnetIdToRouterInterfaceCache = new HashMap<>(); this.neutronPortToDpIdCache = new HashMap<>(); this.floatIpDataMapCache = new HashMap<>(); this.externalRouterMac = configurationService.getDefaultGatewayMacAddress(null); if (this.externalRouterMac == null) { this.externalRouterMac = DEFAULT_EXT_RTR_MAC; } this.enabled = true; LOG.info("OVSDB L3 forwarding is enabled"); } else { LOG.debug("OVSDB L3 forwarding is disabled"); } this.portCleanupCache = new HashMap<>(); this.networkCleanupCache = new HashMap<>(); } // // Callbacks from AbstractHandler // @Override public void processEvent(AbstractEvent abstractEvent) { if (!(abstractEvent instanceof NeutronL3AdapterEvent)) { LOG.error("Unable to process abstract event " + abstractEvent); return; } if (!this.enabled) { return; } NeutronL3AdapterEvent ev = (NeutronL3AdapterEvent) abstractEvent; switch (ev.getAction()) { case UPDATE: if (ev.getSubType() == NeutronL3AdapterEvent.SubType.SUBTYPE_EXTERNAL_MAC_UPDATE) { updateExternalRouterMac( ev.getMacAddress().getValue() ); } else { LOG.warn("Received update for an unexpected event " + ev); } break; case ADD: // fall through... // break; case DELETE: // fall through... // break; default: LOG.warn("Unable to process event " + ev); break; } } // // Callbacks from GatewayMacResolverListener // @Override public void gatewayMacResolved(Long externalNetworkBridgeDpid, IpAddress gatewayIpAddress, MacAddress macAddress) { LOG.info("got gatewayMacResolved callback for ip {} on dpid {} to mac {}", gatewayIpAddress, externalNetworkBridgeDpid, macAddress); if (!this.enabled) { return; } if (macAddress == null || macAddress.getValue() == null) { // TODO: handle cases when mac is null return; } // // Enqueue event so update is handled by adapter's thread // enqueueEvent( new NeutronL3AdapterEvent(externalNetworkBridgeDpid, gatewayIpAddress, macAddress) ); } private void populateL3ForwardingCaches() { if (!this.enabled) { return; } if(this.isCachePopulationDone || this.neutronFloatingIpCache == null || this.neutronPortCache == null ||this.neutronNetworkCache == null) { return; } this.isCachePopulationDone = true; LOG.debug("Populating NetVirt L3 caches from data store configuration"); Routers routers = this.neutronModelsDataStoreHelper.readAllNeutronRouters(); Ports ports = this.neutronModelsDataStoreHelper.readAllNeutronPorts(); if(routers != null && routers.getRouter() != null && ports != null) { LOG.debug("L3 Cache Population : {} Neutron router present in data store",routers.getRouter().size()); for( Router router : routers.getRouter()) { LOG.debug("L3 Cache Population : Populate caches for router {}",router); if(!ports.getPort().isEmpty()) { for( Port port : ports.getPort()) { if (port.getDeviceId().equals(router.getUuid().getValue()) && port.getDeviceOwner().equals(OWNER_ROUTER_INTERFACE)) { LOG.debug("L3 Cache Population : Router interface {} found.",port); networkIdToRouterMacCache.put(port.getNetworkId().getValue() , port.getMacAddress()); networkIdToRouterIpListCache.put(port.getNetworkId().getValue(), NeutronIAwareUtil.convertMDSalIpToNeutronIp(port.getFixedIps())); subnetIdToRouterInterfaceCache.put(port.getFixedIps().get(0).getSubnetId().getValue(), NeutronIAwareUtil.convertMDSalInterfaceToNeutronRouterInterface(port)); } } }else { LOG.warn("L3 Cache Population :Did not find any port information " + "in config Data Store for router {}",router); } } } LOG.debug("NetVirt L3 caches population is done"); } private Pair<Long, Uuid> getDpIdOfNeutronPort(String neutronTenantPortUuid) { if(neutronPortToDpIdCache.get(neutronTenantPortUuid) == null) { List<Node> bridges = this.southbound.readOvsdbTopologyBridgeNodes(); LOG.debug("getDpIdOfNeutronPort : {} bridges present in ovsdb topology",bridges.size()); for(Node bridge : bridges) { List<OvsdbTerminationPointAugmentation> interfaces = southbound.extractTerminationPointAugmentations(bridge); if(interfaces != null && !interfaces.isEmpty()) { LOG.debug("getDpIdOfNeutronPort : {} termination point present on bridge {}", interfaces.size(), bridge.getNodeId()); for (OvsdbTerminationPointAugmentation intf : interfaces) { NeutronPort neutronPort = tenantNetworkManager.getTenantPort(intf); if(neutronPort != null && neutronPort.getID().equals(neutronTenantPortUuid)) { Long dpId = getDpidForIntegrationBridge(bridge); Uuid interfaceUuid = intf.getInterfaceUuid(); LOG.debug("getDpIdOfNeutronPort : Found bridge {} and interface {} for the tenant neutron" + " port {}",dpId,interfaceUuid,neutronTenantPortUuid); handleInterfaceEventAdd(neutronPort.getPortUUID(), dpId, interfaceUuid); break; } } } } } return neutronPortToDpIdCache.get(neutronTenantPortUuid); } private Collection<FloatIpData> getAllFloatingIPsWithMetadata() { LOG.debug("getAllFloatingIPsWithMetadata : Fechting all floating Ips and it's metadata"); List<NeutronFloatingIP> neutronFloatingIps = neutronFloatingIpCache.getAllFloatingIPs(); if(neutronFloatingIps != null && !neutronFloatingIps.isEmpty()) { for (NeutronFloatingIP neutronFloatingIP : neutronFloatingIps) { if(!floatIpDataMapCache.containsKey(neutronFloatingIP.getID())){ LOG.debug("Metadata for floating ip {} is not present in the cache. " + "Fetching from data store.",neutronFloatingIP.getID()); this.getFloatingIPWithMetadata(neutronFloatingIP.getID()); } } } LOG.debug("getAllFloatingIPsWithMetadata : {} floating points found in data store",floatIpDataMapCache.size()); return floatIpDataMapCache.values(); } private FloatIpData getFloatingIPWithMetadata(String neutronFloatingId) { LOG.debug("getFloatingIPWithMetadata : Get Floating ip and it's meta data for neutron " + "floating id {} ",neutronFloatingId); if(floatIpDataMapCache.get(neutronFloatingId) == null) { NeutronFloatingIP neutronFloatingIP = neutronFloatingIpCache.getFloatingIP(neutronFloatingId); if (neutronFloatingIP == null) { LOG.error("getFloatingIPWithMetadata : Floating ip {} is missing from data store, that should not happen",neutronFloatingId); return null; } List<NeutronPort> neutronPorts = neutronPortCache.getAllPorts(); NeutronPort neutronPortForFloatIp = null; for (NeutronPort neutronPort : neutronPorts) { if (neutronPort.getDeviceOwner().equals(OWNER_FLOATING_IP) && neutronPort.getDeviceID().equals(neutronFloatingIP.getID())) { neutronPortForFloatIp = neutronPort; break; } } String neutronTenantPortUuid = neutronFloatingIP.getPortUUID(); if(neutronTenantPortUuid == null) { return null; } Pair<Long, Uuid> nodeIfPair = this.getDpIdOfNeutronPort(neutronTenantPortUuid); String floatingIpMac = neutronPortForFloatIp == null ? null : neutronPortForFloatIp.getMacAddress(); String fixedIpAddress = neutronFloatingIP.getFixedIPAddress(); String floatingIpAddress = neutronFloatingIP.getFloatingIPAddress(); NeutronPort tenantNeutronPort = neutronPortCache.getPort(neutronTenantPortUuid); NeutronNetwork tenantNeutronNetwork = tenantNeutronPort != null ? neutronNetworkCache.getNetwork(tenantNeutronPort.getNetworkUUID()) : null; String providerSegmentationId = tenantNeutronNetwork != null ? tenantNeutronNetwork.getProviderSegmentationID() : null; String neutronRouterMac = tenantNeutronNetwork != null ? networkIdToRouterMacCache.get(tenantNeutronNetwork.getID()) : null; if (nodeIfPair == null || neutronTenantPortUuid == null || providerSegmentationId == null || providerSegmentationId.isEmpty() || floatingIpMac == null || floatingIpMac.isEmpty() || neutronRouterMac == null || neutronRouterMac.isEmpty()) { LOG.debug("getFloatingIPWithMetadata :Floating IP {}<->{}, incomplete floatPort {} tenantPortUuid {} " + "seg {} mac {} rtrMac {}", fixedIpAddress, floatingIpAddress, neutronPortForFloatIp, neutronTenantPortUuid, providerSegmentationId, floatingIpMac, neutronRouterMac); return null; } // get ofport for patch port in br-int final Long dpId = nodeIfPair.getLeft(); final Long ofPort = findOFPortForExtPatch(dpId); if (ofPort == null) { LOG.warn("getFloatingIPWithMetadata : Unable to locate OF port of patch port " + "to connect floating ip to external bridge. dpid {}", dpId); return null; } final FloatIpData floatIpData = new FloatIpData(dpId, ofPort, providerSegmentationId, floatingIpMac, floatingIpAddress, fixedIpAddress, neutronRouterMac); floatIpDataMapCache.put(neutronFloatingIP.getID(), floatIpData); } return floatIpDataMapCache.get(neutronFloatingId); } /** * Invoked to configure the mac address for the external gateway in br-ex. ovsdb netvirt needs help in getting * mac for given ip in br-ex (bug 3378). For example, since ovsdb has no real arp, it needs a service in can * subscribe so that the mac address associated to the gateway ip address is available. * * @param externalRouterMacUpdate The mac address to be associated to the gateway. */ public void updateExternalRouterMac(final String externalRouterMacUpdate) { Preconditions.checkNotNull(externalRouterMacUpdate); flushExistingIpRewrite(); this.externalRouterMac = externalRouterMacUpdate; rebuildExistingIpRewrite(); } /** * Process the event. * * @param action the {@link Action} action to be handled. * @param subnet An instance of NeutronSubnet object. */ public void handleNeutronSubnetEvent(final NeutronSubnet subnet, Action action) { LOG.debug("Neutron subnet {} event : {}", action, subnet.toString()); if (action == ADD) { this.storeNetworkInCleanupCache(neutronNetworkCache.getNetwork(subnet.getNetworkUUID())); } } /** * Process the port event as a router interface event. * For a not delete action, since a port is only create when the tennat uses the subnet, it is required to * verify if all routers across all nodes have the interface for the port's subnet(s) configured. * * @param action the {@link Action} action to be handled. * @param neutronPort An instance of NeutronPort object. */ public void handleNeutronPortEvent(final NeutronPort neutronPort, Action action) { LOG.debug("Neutron port {} event : {}", action, neutronPort.toString()); if (action == UPDATE) { // FIXME: Bug 4971 Move cleanup cache to SG Impl this.updatePortInCleanupCache(neutronPort, neutronPort.getOriginalPort()); if (neutronPort.getPortSecurityEnabled()) { this.processSecurityGroupUpdate(neutronPort); } if (isPortSecurityEnableUpdated(neutronPort)) { this.processPortSecurityEnableUpdated(neutronPort); } } if (!this.enabled) { return; } final boolean isDelete = action == DELETE; if (action == DELETE) { // Bug 5164: Cleanup Floating IP OpenFlow Rules when port is deleted. this.cleanupFloatingIPRules(neutronPort); } else if (action == UPDATE){ // Bug 5353: VM restart cause floatingIp flows to be removed this.updateFloatingIPRules(neutronPort); } if (neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_GATEWAY)){ if (!isDelete) { LOG.info("Port {} is network router gateway interface, " + "triggering gateway resolution for the attached external network", neutronPort); this.triggerGatewayMacResolver(neutronPort); }else{ NeutronNetwork externalNetwork = neutronNetworkCache.getNetwork(neutronPort.getNetworkUUID()); if (null == externalNetwork) { externalNetwork = this.getNetworkFromCleanupCache(neutronPort.getNetworkUUID()); } if (externalNetwork != null && externalNetwork.isRouterExternal()) { final NeutronSubnet externalSubnet = getExternalNetworkSubnet(neutronPort); // TODO support IPv6 if (externalSubnet != null && externalSubnet.getIpVersion() == 4) { gatewayMacResolver.stopPeriodicRefresh(new Ipv4Address(externalSubnet.getGatewayIP())); } } } } // Treat the port event as a router interface event if the port belongs to router. This is a // helper for handling cases when handleNeutronRouterInterfaceEvent is not available // if (neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_INTERFACE) || neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_INTERFACE_DISTRIBUTED)) { if (neutronPort.getFixedIPs() != null) { for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { NeutronRouter_Interface neutronRouterInterface = new NeutronRouter_Interface(neutronIP.getSubnetUUID(), neutronPort.getPortUUID()); // id of router interface to be same as subnet neutronRouterInterface.setID(neutronIP.getSubnetUUID()); neutronRouterInterface.setTenantID(neutronPort.getTenantID()); this.handleNeutronRouterInterfaceEvent(null /*neutronRouter*/, neutronRouterInterface, action); } } } else { // We made it here, port is not used as a router interface. If this is not a delete action, make sure that // all nodes that are supposed to have a router interface for the port's subnet(s), have it configured. We // need to do this check here because a router interface is not added to a node until tenant becomes needed // there. // if (!isDelete && neutronPort.getFixedIPs() != null) { for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { NeutronRouter_Interface neutronRouterInterface = subnetIdToRouterInterfaceCache.get(neutronIP.getSubnetUUID()); if (neutronRouterInterface != null) { this.handleNeutronRouterInterfaceEvent(null /*neutronRouter*/, neutronRouterInterface, action); } } } this.updateL3ForNeutronPort(neutronPort, isDelete); } } /** * Process the event. * * @param action the {@link Action} action to be handled. * @param neutronRouter An instance of NeutronRouter object. */ public void handleNeutronRouterEvent(final NeutronRouter neutronRouter, Action action) { LOG.debug("Neutron router {} event : {}", action, neutronRouter.toString()); } /** * Process the event enforcing actions and verifying dependencies between all router's interface. For example, * delete the ports on the same subnet. * * @param action the {@link Action} action to be handled. * @param neutronRouter An instance of NeutronRouter object. * @param neutronRouterInterface An instance of NeutronRouter_Interface object. */ public void handleNeutronRouterInterfaceEvent(final NeutronRouter neutronRouter, final NeutronRouter_Interface neutronRouterInterface, Action action) { LOG.debug("Router interface {} got event {}. Subnet {}", neutronRouterInterface.getPortUUID(), action, neutronRouterInterface.getSubnetUUID()); if (!this.enabled) { return; } final boolean isDelete = action == DELETE; this.programFlowsForNeutronRouterInterface(neutronRouterInterface, isDelete); // As neutron router interface is added/removed, we need to iterate through all the neutron ports and // see if they are affected by l3 // for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) { boolean currPortShouldBeDeleted = false; // Note: delete in this case only applies to 1)router interface delete and 2)ports on the same subnet if (isDelete) { if (neutronPort.getFixedIPs() != null) { for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { if (neutronRouterInterface.getSubnetUUID().equalsIgnoreCase(neutronIP.getSubnetUUID())) { currPortShouldBeDeleted = true; break; } } } } this.updateL3ForNeutronPort(neutronPort, currPortShouldBeDeleted); } } /** * Invoked when a neutron message regarding the floating ip association is sent to odl via ml2. If the action is * a creation, it will first add ARP rules for the given floating ip and then configure the DNAT (rewrite the * packets from the floating IP address to the internal fixed ip) rules on OpenFlow Table 30 and SNAT rules (other * way around) on OpenFlow Table 100. * * @param actionIn the {@link Action} action to be handled. * @param neutronFloatingIP An {@link NeutronFloatingIP} instance of NeutronFloatingIP object. */ public void handleNeutronFloatingIPEvent(final NeutronFloatingIP neutronFloatingIP, Action actionIn) { Preconditions.checkNotNull(neutronFloatingIP); LOG.debug(" Floating IP {} {}<->{}, network uuid {}", actionIn, neutronFloatingIP.getFixedIPAddress(), neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getFloatingNetworkUUID()); if (!this.enabled) { return; } Action action; // Consider action to be delete if getFixedIPAddress is null // if (neutronFloatingIP.getFixedIPAddress() == null) { action = DELETE; } else { action = actionIn; } // this.programFlowsForFloatingIP(neutronFloatingIP, action == Action.DELETE); if (action != DELETE) { // must be first, as it updates floatIpDataMapCache programFlowsForFloatingIPArpAdd(neutronFloatingIP); programFlowsForFloatingIPInbound(neutronFloatingIP, ADD); programFlowsForFloatingIPOutbound(neutronFloatingIP, ADD); } else { programFlowsForFloatingIPOutbound(neutronFloatingIP, DELETE); programFlowsForFloatingIPInbound(neutronFloatingIP, DELETE); // must be last, as it updates floatIpDataMapCache programFlowsForFloatingIPArpDelete(neutronFloatingIP.getID()); } } /** * This method performs creation or deletion of in-bound rules into Table 30 for a existing available floating * ip, otherwise for newer one. */ private void programFlowsForFloatingIPInbound(final NeutronFloatingIP neutronFloatingIP, final Action action) { Preconditions.checkNotNull(neutronFloatingIP); final FloatIpData fid = getFloatingIPWithMetadata(neutronFloatingIP.getID()); if (fid == null) { LOG.trace("programFlowsForFloatingIPInboundAdd {} for {} uuid {} not in local cache", action, neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getID()); return; } programInboundIpRewriteStage1(fid.dpid, fid.ofPort, fid.segId, fid.floatingIpAddress, fid.fixedIpAddress, action); } /** * This method performs creation or deletion of out-bound rules into Table 100 for a existing available floating * ip, otherwise for newer one. */ private void programFlowsForFloatingIPOutbound(final NeutronFloatingIP neutronFloatingIP, final Action action) { Preconditions.checkNotNull(neutronFloatingIP); final FloatIpData fid = getFloatingIPWithMetadata(neutronFloatingIP.getID()); if (fid == null) { LOG.trace("programFlowsForFloatingIPOutbound {} for {} uuid {} not in local cache", action, neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getID()); return; } programOutboundIpRewriteStage1(fid, action); } private void flushExistingIpRewrite() { for (FloatIpData fid : getAllFloatingIPsWithMetadata()) { programOutboundIpRewriteStage1(fid, DELETE); } } private void rebuildExistingIpRewrite() { for (FloatIpData fid : getAllFloatingIPsWithMetadata()) { programOutboundIpRewriteStage1(fid, ADD); } } /** * This method creates ARP response rules into OpenFlow Table 30 for a given floating ip. In order to connect * to br-ex from br-int, a patch-port is used. Thus, the patch-port will be responsible to respond the ARP * requests. */ private void programFlowsForFloatingIPArpAdd(final NeutronFloatingIP neutronFloatingIP) { Preconditions.checkNotNull(neutronFloatingIP); Preconditions.checkNotNull(neutronFloatingIP.getFixedIPAddress()); Preconditions.checkNotNull(neutronFloatingIP.getFloatingIPAddress()); // find bridge Node where floating ip is configured by looking up cache for its port final NeutronPort neutronPortForFloatIp = findNeutronPortForFloatingIp(neutronFloatingIP.getID()); final String neutronTenantPortUuid = neutronFloatingIP.getPortUUID(); final Pair<Long, Uuid> nodeIfPair = this.getDpIdOfNeutronPort(neutronTenantPortUuid); final String floatingIpMac = neutronPortForFloatIp == null ? null : neutronPortForFloatIp.getMacAddress(); final String fixedIpAddress = neutronFloatingIP.getFixedIPAddress(); final String floatingIpAddress = neutronFloatingIP.getFloatingIPAddress(); final NeutronPort tenantNeutronPort = neutronPortCache.getPort(neutronTenantPortUuid); final NeutronNetwork tenantNeutronNetwork = tenantNeutronPort != null ? neutronNetworkCache.getNetwork(tenantNeutronPort.getNetworkUUID()) : null; final String providerSegmentationId = tenantNeutronNetwork != null ? tenantNeutronNetwork.getProviderSegmentationID() : null; final String neutronRouterMac = tenantNeutronNetwork != null ? networkIdToRouterMacCache.get(tenantNeutronNetwork.getID()) : null; if (nodeIfPair == null || neutronTenantPortUuid == null || providerSegmentationId == null || providerSegmentationId.isEmpty() || floatingIpMac == null || floatingIpMac.isEmpty() || neutronRouterMac == null || neutronRouterMac.isEmpty()) { LOG.trace("Floating IP {}<->{}, incomplete floatPort {} tenantPortUuid {} seg {} mac {} rtrMac {}", fixedIpAddress, floatingIpAddress, neutronPortForFloatIp, neutronTenantPortUuid, providerSegmentationId, floatingIpMac, neutronRouterMac); return; } // get ofport for patch port in br-int final Long dpId = nodeIfPair.getLeft(); final Long ofPort = findOFPortForExtPatch(dpId); if (ofPort == null) { LOG.warn("Unable to locate OF port of patch port to connect floating ip to external bridge. dpid {}", dpId); return; } // Respond to ARPs for the floating ip address by default, via the patch port that connects br-int to br-ex // if (distributedArpService.programStaticRuleStage1(dpId, encodeExcplicitOFPort(ofPort), floatingIpMac, floatingIpAddress, ADD)) { final FloatIpData floatIpData = new FloatIpData(dpId, ofPort, providerSegmentationId, floatingIpMac, floatingIpAddress, fixedIpAddress, neutronRouterMac); floatIpDataMapCache.put(neutronFloatingIP.getID(), floatIpData); LOG.info("Floating IP {}<->{} programmed ARP mac {} on OFport {} seg {} dpid {}", neutronFloatingIP.getFixedIPAddress(), neutronFloatingIP.getFloatingIPAddress(), floatingIpMac, ofPort, providerSegmentationId, dpId); } } private void programFlowsForFloatingIPArpDelete(final String neutronFloatingIPUuid) { final FloatIpData floatIpData = getFloatingIPWithMetadata(neutronFloatingIPUuid); if (floatIpData == null) { LOG.trace("programFlowsForFloatingIPArpDelete for uuid {} is not needed", neutronFloatingIPUuid); return; } if (distributedArpService.programStaticRuleStage1(floatIpData.dpid, encodeExcplicitOFPort(floatIpData.ofPort), floatIpData.macAddress, floatIpData.floatingIpAddress, DELETE)) { floatIpDataMapCache.remove(neutronFloatingIPUuid); LOG.info("Floating IP {} un-programmed ARP mac {} on {} dpid {}", floatIpData.floatingIpAddress, floatIpData.macAddress, floatIpData.ofPort, floatIpData.dpid); } } private NeutronPort findNeutronPortForFloatingIp(final String floatingIpUuid) { for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) { if (neutronPort.getDeviceOwner().equals(OWNER_FLOATING_IP) && neutronPort.getDeviceID().equals(floatingIpUuid)) { return neutronPort; } } return null; } private Long findOFPortForExtPatch(Long dpId) { final String brInt = configurationService.getIntegrationBridgeName(); final String brExt = configurationService.getExternalBridgeName(); final String portNameInt = configurationService.getPatchPortName(new ImmutablePair<>(brInt, brExt)); Preconditions.checkNotNull(dpId); Preconditions.checkNotNull(portNameInt); final long dpidPrimitive = dpId; for (Node node : nodeCacheManager.getBridgeNodes()) { if (dpidPrimitive == southbound.getDataPathId(node)) { final OvsdbTerminationPointAugmentation terminationPointOfBridge = southbound.getTerminationPointOfBridge(node, portNameInt); return terminationPointOfBridge == null ? null : terminationPointOfBridge.getOfport(); } } return null; } /** * Process the event. * * @param action the {@link Action} action to be handled. * @param neutronNetwork An {@link NeutronNetwork} instance of NeutronFloatingIP object. */ public void handleNeutronNetworkEvent(final NeutronNetwork neutronNetwork, Action action) { LOG.debug("neutronNetwork {}: network: {}", action, neutronNetwork); if (action == UPDATE) { this.updateNetworkInCleanupCache(neutronNetwork); } } // // Callbacks from OVSDB's southbound handler // /** * Process the event. * * @param bridgeNode An instance of Node object. * @param intf An {@link org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105 * .OvsdbTerminationPointAugmentation} instance of OvsdbTerminationPointAugmentation object. * @param neutronNetwork An {@link NeutronNetwork} instance of NeutronNetwork * object. * @param action the {@link Action} action to be handled. */ public void handleInterfaceEvent(final Node bridgeNode, final OvsdbTerminationPointAugmentation intf, final NeutronNetwork neutronNetwork, Action action) { LOG.debug("southbound interface {} node:{} interface:{}, neutronNetwork:{}", action, bridgeNode.getNodeId().getValue(), intf.getName(), neutronNetwork); final NeutronPort neutronPort = tenantNetworkManager.getTenantPort(intf); if (action != DELETE && neutronPort != null) { // FIXME: Bug 4971 Move cleanup cache to SG Impl storePortInCleanupCache(neutronPort); } if (!this.enabled) { return; } final Long dpId = getDpidForIntegrationBridge(bridgeNode); final Uuid interfaceUuid = intf.getInterfaceUuid(); LOG.trace("southbound interface {} node:{} interface:{}, neutronNetwork:{} port:{} dpid:{} intfUuid:{}", action, bridgeNode.getNodeId().getValue(), intf.getName(), neutronNetwork, neutronPort, dpId, interfaceUuid); if (neutronPort != null) { final String neutronPortUuid = neutronPort.getPortUUID(); if (action != DELETE && dpId != null && interfaceUuid != null) { handleInterfaceEventAdd(neutronPortUuid, dpId, interfaceUuid); } handleNeutronPortEvent(neutronPort, action); } if (action == DELETE && interfaceUuid != null) { handleInterfaceEventDelete(intf, dpId); } } private void handleInterfaceEventAdd(final String neutronPortUuid, Long dpId, final Uuid interfaceUuid) { neutronPortToDpIdCache.put(neutronPortUuid, new ImmutablePair<>(dpId, interfaceUuid)); LOG.debug("handleInterfaceEvent add cache entry NeutronPortUuid {} : dpid {}, ifUuid {}", neutronPortUuid, dpId, interfaceUuid.getValue()); } private void handleInterfaceEventDelete(final OvsdbTerminationPointAugmentation intf, final Long dpId) { // Remove entry from neutronPortToDpIdCache based on interface uuid for (Map.Entry<String, Pair<Long, Uuid>> entry : neutronPortToDpIdCache.entrySet()) { final String currPortUuid = entry.getKey(); if (intf.getInterfaceUuid().equals(entry.getValue().getRight())) { LOG.debug("handleInterfaceEventDelete remove cache entry NeutronPortUuid {} : dpid {}, ifUuid {}", currPortUuid, dpId, intf.getInterfaceUuid().getValue()); neutronPortToDpIdCache.remove(currPortUuid); break; } } } // // Internal helpers // private void updateL3ForNeutronPort(final NeutronPort neutronPort, final boolean isDelete) { final String networkUUID = neutronPort.getNetworkUUID(); final String routerMacAddress = networkIdToRouterMacCache.get(networkUUID); if(!isDelete) { // If there is no router interface handling the networkUUID, we are done if (routerMacAddress == null || routerMacAddress.isEmpty()) { return; } // If this is the neutron port for the router interface itself, ignore it as well. Ports that represent the // router interface are handled via handleNeutronRouterInterfaceEvent. if (routerMacAddress.equalsIgnoreCase(neutronPort.getMacAddress())) { return; } } final NeutronNetwork neutronNetwork = neutronNetworkCache.getNetwork(networkUUID); final String providerSegmentationId = neutronNetwork != null ? neutronNetwork.getProviderSegmentationID() : null; final String tenantMac = neutronPort.getMacAddress(); if (providerSegmentationId == null || providerSegmentationId.isEmpty() || tenantMac == null || tenantMac.isEmpty()) { // done: go no further w/out all the info needed... return; } final Action action = isDelete ? DELETE : ADD; List<Node> nodes = nodeCacheManager.getBridgeNodes(); if (nodes.isEmpty()) { LOG.trace("updateL3ForNeutronPort has no nodes to work with"); } for (Node node : nodes) { final Long dpid = getDpidForIntegrationBridge(node); if (dpid == null) { continue; } if (neutronPort.getFixedIPs() == null) { continue; } for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { final String tenantIpStr = neutronIP.getIpAddress(); if (tenantIpStr.isEmpty()) { continue; } // Configure L3 fwd. We do that regardless of tenant network present, because these rules are // still needed when routing to subnets non-local to node (bug 2076). programL3ForwardingStage1(node, dpid, providerSegmentationId, tenantMac, tenantIpStr, action); } } } private void processSecurityGroupUpdate(NeutronPort neutronPort) { LOG.trace("processSecurityGroupUpdate:" + neutronPort); /** * Get updated data and original data for the the changed. Identify the security groups that got * added and removed and call the appropriate providers for updating the flows. */ try { List<NeutronSecurityGroup> addedGroup = getsecurityGroupChanged(neutronPort, neutronPort.getOriginalPort()); List<NeutronSecurityGroup> deletedGroup = getsecurityGroupChanged(neutronPort.getOriginalPort(), neutronPort); if (null != addedGroup && !addedGroup.isEmpty()) { securityServicesManager.syncSecurityGroup(neutronPort,addedGroup,true); } if (null != deletedGroup && !deletedGroup.isEmpty()) { securityServicesManager.syncSecurityGroup(neutronPort,deletedGroup,false); } } catch (Exception e) { LOG.error("Exception in processSecurityGroupUpdate", e); } } private void processPortSecurityEnableUpdated(NeutronPort neutronPort) { LOG.trace("processPortSecurityEnableUpdated:" + neutronPort); securityServicesManager.syncFixedSecurityGroup(neutronPort, neutronPort.getPortSecurityEnabled()); } private boolean isPortSecurityEnableUpdated(NeutronPort neutronPort) { LOG.trace("isPortSecuirtyEnableUpdated:" + neutronPort); if (neutronPort.getOriginalPort().getPortSecurityEnabled() != neutronPort.getPortSecurityEnabled()) { return true; } return false; } private List<NeutronSecurityGroup> getsecurityGroupChanged(NeutronPort port1, NeutronPort port2) { LOG.trace("getsecurityGroupChanged:" + "Port1:" + port1 + "Port2" + port2); if (port1 == null) { return null; } List<NeutronSecurityGroup> list1 = new ArrayList<>(port1.getSecurityGroups()); if (port2 == null) { return list1; } List<NeutronSecurityGroup> list2 = new ArrayList<>(port2.getSecurityGroups()); for (Iterator<NeutronSecurityGroup> iterator = list1.iterator(); iterator.hasNext();) { NeutronSecurityGroup securityGroup1 = iterator.next(); for (NeutronSecurityGroup securityGroup2 :list2) { if (securityGroup1.getID().equals(securityGroup2.getID())) { iterator.remove(); } } } return list1; } private void programL3ForwardingStage1(Node node, Long dpid, String providerSegmentationId, String macAddress, String ipStr, Action actionForNode) { if (actionForNode == DELETE) { LOG.trace("Deleting Flow : programL3ForwardingStage1 for node {} providerId {} mac {} ip {} action {}", node.getNodeId().getValue(), providerSegmentationId, macAddress, ipStr, actionForNode); } if (actionForNode == ADD) { LOG.trace("Adding Flow : programL3ForwardingStage1 for node {} providerId {} mac {} ip {} action {}", node.getNodeId().getValue(), providerSegmentationId, macAddress, ipStr, actionForNode); } this.programL3ForwardingStage2(node, dpid, providerSegmentationId, macAddress, ipStr, actionForNode); } private Status programL3ForwardingStage2(Node node, Long dpid, String providerSegmentationId, String macAddress, String address, Action actionForNode) { Status status; try { InetAddress inetAddress = InetAddress.getByName(address); status = l3ForwardingProvider == null ? new Status(StatusCode.SUCCESS) : l3ForwardingProvider.programForwardingTableEntry(dpid, providerSegmentationId, inetAddress, macAddress, actionForNode); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { LOG.debug("ProgramL3Forwarding {} for mac:{} addr:{} node:{} action:{}", l3ForwardingProvider == null ? "skipped" : "programmed", macAddress, address, node.getNodeId().getValue(), actionForNode); } else { LOG.error("ProgramL3Forwarding failed for mac:{} addr:{} node:{} action:{} status:{}", macAddress, address, node.getNodeId().getValue(), actionForNode, status); } return status; } // -- private void programFlowsForNeutronRouterInterface(final NeutronRouter_Interface destNeutronRouterInterface, Boolean isDelete) { Preconditions.checkNotNull(destNeutronRouterInterface); final NeutronPort neutronPort = neutronPortCache.getPort(destNeutronRouterInterface.getPortUUID()); String macAddress = neutronPort != null ? neutronPort.getMacAddress() : null; List<Neutron_IPs> ipList = neutronPort != null ? neutronPort.getFixedIPs() : null; final NeutronSubnet subnet = neutronSubnetCache.getSubnet(destNeutronRouterInterface.getSubnetUUID()); final NeutronNetwork neutronNetwork = subnet != null ? neutronNetworkCache.getNetwork(subnet.getNetworkUUID()) : null; final String destinationSegmentationId = neutronNetwork != null ? neutronNetwork.getProviderSegmentationID() : null; final Boolean isExternal = neutronNetwork != null ? neutronNetwork.getRouterExternal() : Boolean.TRUE; final String cidr = subnet != null ? subnet.getCidr() : null; final int mask = getMaskLenFromCidr(cidr); LOG.trace("programFlowsForNeutronRouterInterface called for interface {} isDelete {}", destNeutronRouterInterface, isDelete); // in delete path, mac address as well as ip address are not provided. Being so, let's find them from // the local cache if (neutronNetwork != null) { if (macAddress == null || macAddress.isEmpty()) { macAddress = networkIdToRouterMacCache.get(neutronNetwork.getNetworkUUID()); } if (ipList == null || ipList.isEmpty()) { ipList = networkIdToRouterIpListCache.get(neutronNetwork.getNetworkUUID()); } } if (destinationSegmentationId == null || destinationSegmentationId.isEmpty() || cidr == null || cidr.isEmpty() || macAddress == null || macAddress.isEmpty() || ipList == null || ipList.isEmpty()) { LOG.debug("programFlowsForNeutronRouterInterface is bailing seg:{} cidr:{} mac:{} ip:{}", destinationSegmentationId, cidr, macAddress, ipList); // done: go no further w/out all the info needed... return; } final Action actionForNode = isDelete ? DELETE : ADD; // Keep cache for finding router's mac from network uuid -- add // if (! isDelete) { networkIdToRouterMacCache.put(neutronNetwork.getNetworkUUID(), macAddress); networkIdToRouterIpListCache.put(neutronNetwork.getNetworkUUID(), new ArrayList<>(ipList)); subnetIdToRouterInterfaceCache.put(subnet.getSubnetUUID(), destNeutronRouterInterface); } List<Node> nodes = nodeCacheManager.getBridgeNodes(); if (nodes.isEmpty()) { LOG.trace("programFlowsForNeutronRouterInterface has no nodes to work with"); } for (Node node : nodes) { final Long dpid = getDpidForIntegrationBridge(node); if (dpid == null) { continue; } for (Neutron_IPs neutronIP : ipList) { final String ipStr = neutronIP.getIpAddress(); if (ipStr.isEmpty()) { LOG.debug("programFlowsForNeutronRouterInterface is skipping node {} ip {}", node.getNodeId().getValue(), ipStr); continue; } // Iterate through all other interfaces and add/remove reflexive flows to this interface // for (NeutronRouter_Interface srcNeutronRouterInterface : subnetIdToRouterInterfaceCache.values()) { programFlowsForNeutronRouterInterfacePair(node, dpid, srcNeutronRouterInterface, destNeutronRouterInterface, neutronNetwork, destinationSegmentationId, macAddress, ipStr, mask, actionForNode, true /*isReflexsive*/); } if (! isExternal) { programFlowForNetworkFromExternal(node, dpid, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } // Enable ARP responder by default, because router interface needs to be responded always. distributedArpService.programStaticRuleStage1(dpid, destinationSegmentationId, macAddress, ipStr, actionForNode); programIcmpEcho(dpid, destinationSegmentationId, macAddress, ipStr, actionForNode); } // Compute action to be programmed. In the case of rewrite exclusions, we must never program rules // for the external neutron networks. // { final Action actionForRewriteExclusion = isExternal ? DELETE : actionForNode; programIpRewriteExclusionStage1(node, dpid, destinationSegmentationId, cidr, actionForRewriteExclusion); } } if (isDelete) { networkIdToRouterMacCache.remove(neutronNetwork.getNetworkUUID()); networkIdToRouterIpListCache.remove(neutronNetwork.getNetworkUUID()); subnetIdToRouterInterfaceCache.remove(subnet.getSubnetUUID()); } } private void programFlowForNetworkFromExternal(final Node node, final Long dpid, final String destinationSegmentationId, final String dstMacAddress, final String destIpStr, final int destMask, final Action actionForNode) { programRouterInterfaceStage1(node, dpid, Constants.EXTERNAL_NETWORK, destinationSegmentationId, dstMacAddress, destIpStr, destMask, actionForNode); } private void programFlowsForNeutronRouterInterfacePair(final Node node, final Long dpid, final NeutronRouter_Interface srcNeutronRouterInterface, final NeutronRouter_Interface dstNeutronRouterInterface, final NeutronNetwork dstNeutronNetwork, final String destinationSegmentationId, final String dstMacAddress, final String destIpStr, final int destMask, final Action actionForNode, Boolean isReflexsive) { Preconditions.checkNotNull(srcNeutronRouterInterface); Preconditions.checkNotNull(dstNeutronRouterInterface); final String sourceSubnetId = srcNeutronRouterInterface.getSubnetUUID(); if (sourceSubnetId == null) { LOG.error("Could not get provider Subnet ID from router interface {}", srcNeutronRouterInterface.getID()); return; } final NeutronSubnet sourceSubnet = neutronSubnetCache.getSubnet(sourceSubnetId); final String sourceNetworkId = sourceSubnet == null ? null : sourceSubnet.getNetworkUUID(); if (sourceNetworkId == null) { LOG.error("Could not get provider Network ID from subnet {}", sourceSubnetId); return; } final NeutronNetwork sourceNetwork = neutronNetworkCache.getNetwork(sourceNetworkId); if (sourceNetwork == null) { LOG.error("Could not get provider Network for Network ID {}", sourceNetworkId); return; } if (! sourceNetwork.getTenantID().equals(dstNeutronNetwork.getTenantID())) { // Isolate subnets from different tenants within the same router return; } final String sourceSegmentationId = sourceNetwork.getProviderSegmentationID(); if (sourceSegmentationId == null) { LOG.error("Could not get provider Segmentation ID for Subnet {}", sourceSubnetId); return; } if (sourceSegmentationId.equals(destinationSegmentationId)) { // Skip 'self' return; } programRouterInterfaceStage1(node, dpid, sourceSegmentationId, destinationSegmentationId, dstMacAddress, destIpStr, destMask, actionForNode); // Flip roles src->dst; dst->src if (isReflexsive) { final NeutronPort sourceNeutronPort = neutronPortCache.getPort(srcNeutronRouterInterface.getPortUUID()); final String macAddress2 = sourceNeutronPort != null ? sourceNeutronPort.getMacAddress() : null; final List<Neutron_IPs> ipList2 = sourceNeutronPort != null ? sourceNeutronPort.getFixedIPs() : null; final String cidr2 = sourceSubnet.getCidr(); final int mask2 = getMaskLenFromCidr(cidr2); if (cidr2 == null || cidr2.isEmpty() || macAddress2 == null || macAddress2.isEmpty() || ipList2 == null || ipList2.isEmpty()) { LOG.trace("programFlowsForNeutronRouterInterfacePair reflexive is bailing seg:{} cidr:{} mac:{} ip:{}", sourceSegmentationId, cidr2, macAddress2, ipList2); // done: go no further w/out all the info needed... return; } for (Neutron_IPs neutronIP2 : ipList2) { final String ipStr2 = neutronIP2.getIpAddress(); if (ipStr2.isEmpty()) { continue; } programFlowsForNeutronRouterInterfacePair(node, dpid, dstNeutronRouterInterface, srcNeutronRouterInterface, sourceNetwork, sourceSegmentationId, macAddress2, ipStr2, mask2, actionForNode, false /*isReflexsive*/); } } } private void programRouterInterfaceStage1(Node node, Long dpid, String sourceSegmentationId, String destinationSegmentationId, String macAddress, String ipStr, int mask, Action actionForNode) { if (actionForNode == DELETE) { LOG.trace("Deleting Flow : programRouterInterfaceStage1 for node {} sourceSegId {} destSegId {} mac {} ip {} mask {}" + " action {}", node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } if (actionForNode == ADD) { LOG.trace("Adding Flow : programRouterInterfaceStage1 for node {} sourceSegId {} destSegId {} mac {} ip {} mask {}" + " action {}", node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } this.programRouterInterfaceStage2(node, dpid, sourceSegmentationId, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } private Status programRouterInterfaceStage2(Node node, Long dpid, String sourceSegmentationId, String destinationSegmentationId, String macAddress, String address, int mask, Action actionForNode) { Status status; try { InetAddress inetAddress = InetAddress.getByName(address); status = routingProvider == null ? new Status(StatusCode.SUCCESS) : routingProvider.programRouterInterface(dpid, sourceSegmentationId, destinationSegmentationId, macAddress, inetAddress, mask, actionForNode); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { LOG.debug("programRouterInterfaceStage2 {} for mac:{} addr:{}/{} node:{} srcTunId:{} destTunId:{} action:{}", routingProvider == null ? "skipped" : "programmed", macAddress, address, mask, node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, actionForNode); } else { LOG.error("programRouterInterfaceStage2 failed for mac:{} addr:{}/{} node:{} srcTunId:{} destTunId:{} action:{} status:{}", macAddress, address, mask, node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, actionForNode, status); } return status; } private boolean programIcmpEcho(Long dpid, String segOrOfPort, String macAddress, String ipStr, Action action) { if (action == DELETE ) { LOG.trace("Deleting Flow : programIcmpEcho dpid {} segOrOfPort {} mac {} ip {} action {}", dpid, segOrOfPort, macAddress, ipStr, action); } if (action == ADD) { LOG.trace("Adding Flow : programIcmpEcho dpid {} segOrOfPort {} mac {} ip {} action {}", dpid, segOrOfPort, macAddress, ipStr, action); } Status status = new Status(StatusCode.UNSUPPORTED); if (icmpEchoProvider != null){ try { InetAddress inetAddress = InetAddress.getByName(ipStr); status = icmpEchoProvider.programIcmpEchoEntry(dpid, segOrOfPort, macAddress, inetAddress, action); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } } if (status.isSuccess()) { LOG.debug("programIcmpEcho {} for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{}", icmpEchoProvider == null ? "skipped" : "programmed", macAddress, ipStr, dpid, segOrOfPort, action); } else { LOG.error("programIcmpEcho failed for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{} status:{}", macAddress, ipStr, dpid, segOrOfPort, action, status); } return status.isSuccess(); } private boolean programInboundIpRewriteStage1(Long dpid, Long inboundOFPort, String providerSegmentationId, String matchAddress, String rewriteAddress, Action action) { if (action == DELETE ) { LOG.trace("Deleting Flow : programInboundIpRewriteStage1 dpid {} OFPort {} seg {} matchAddress {} rewriteAddress {}" + " action {}", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); } if (action == ADD ) { LOG.trace("Adding Flow : programInboundIpRewriteStage1 dpid {} OFPort {} seg {} matchAddress {} rewriteAddress {}" + " action {}", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); } Status status = programInboundIpRewriteStage2(dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); return status.isSuccess(); } private Status programInboundIpRewriteStage2(Long dpid, Long inboundOFPort, String providerSegmentationId, String matchAddress, String rewriteAddress, Action action) { Status status; try { InetAddress inetMatchAddress = InetAddress.getByName(matchAddress); InetAddress inetRewriteAddress = InetAddress.getByName(rewriteAddress); status = inboundNatProvider == null ? new Status(StatusCode.SUCCESS) : inboundNatProvider.programIpRewriteRule(dpid, inboundOFPort, providerSegmentationId, inetMatchAddress, inetRewriteAddress, action); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { final boolean isSkipped = inboundNatProvider == null; LOG.debug("programInboundIpRewriteStage2 {} for dpid:{} ofPort:{} seg:{} match:{} rewrite:{} action:{}", isSkipped ? "skipped" : "programmed", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); } else { LOG.error("programInboundIpRewriteStage2 failed for dpid:{} ofPort:{} seg:{} match:{} rewrite:{} action:{}" + " status:{}", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action, status); } return status; } private void programIpRewriteExclusionStage1(Node node, Long dpid, String providerSegmentationId, String cidr, Action actionForRewriteExclusion) { if (actionForRewriteExclusion == DELETE ) { LOG.trace("Deleting Flow : programIpRewriteExclusionStage1 node {} providerId {} cidr {} action {}", node.getNodeId().getValue(), providerSegmentationId, cidr, actionForRewriteExclusion); } if (actionForRewriteExclusion == ADD) { LOG.trace("Adding Flow : programIpRewriteExclusionStage1 node {} providerId {} cidr {} action {}", node.getNodeId().getValue(), providerSegmentationId, cidr, actionForRewriteExclusion); } this.programIpRewriteExclusionStage2(node, dpid, providerSegmentationId, cidr,actionForRewriteExclusion); } private Status programIpRewriteExclusionStage2(Node node, Long dpid, String providerSegmentationId, String cidr, Action actionForNode) { final Status status = outboundNatProvider == null ? new Status(StatusCode.SUCCESS) : outboundNatProvider.programIpRewriteExclusion(dpid, providerSegmentationId, cidr, actionForNode); if (status.isSuccess()) { final boolean isSkipped = outboundNatProvider == null; LOG.debug("IpRewriteExclusion {} for cidr:{} node:{} action:{}", isSkipped ? "skipped" : "programmed", cidr, node.getNodeId().getValue(), actionForNode); } else { LOG.error("IpRewriteExclusion failed for cidr:{} node:{} action:{} status:{}", cidr, node.getNodeId().getValue(), actionForNode, status); } return status; } private void programOutboundIpRewriteStage1(FloatIpData fid, Action action) { if (action == DELETE) { LOG.trace("Deleting Flow : programOutboundIpRewriteStage1 dpid {} seg {} fixedIpAddress {} floatIp {} action {} ", fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action); } if (action == ADD) { LOG.trace("Adding Flow : programOutboundIpRewriteStage1 dpid {} seg {} fixedIpAddress {} floatIp {} action {} " , fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action); } this.programOutboundIpRewriteStage2(fid, action); } private Status programOutboundIpRewriteStage2(FloatIpData fid, Action action) { Status status; try { InetAddress matchSrcAddress = InetAddress.getByName(fid.fixedIpAddress); InetAddress rewriteSrcAddress = InetAddress.getByName(fid.floatingIpAddress); status = outboundNatProvider == null ? new Status(StatusCode.SUCCESS) : outboundNatProvider.programIpRewriteRule( fid.dpid, fid.segId, fid.neutronRouterMac, matchSrcAddress, fid.macAddress, this.externalRouterMac, rewriteSrcAddress, fid.ofPort, action); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { final boolean isSkipped = outboundNatProvider == null; LOG.debug("programOutboundIpRewriteStage2 {} for dpid {} seg {} fixedIpAddress {} floatIp {}" + " action {}", isSkipped ? "skipped" : "programmed", fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action); } else { LOG.error("programOutboundIpRewriteStage2 failed for dpid {} seg {} fixedIpAddress {} floatIp {}" + " action {} status:{}", fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action, status); } return status; } private int getMaskLenFromCidr(String cidr) { if (cidr == null) { return 0; } String[] splits = cidr.split("/"); if (splits.length != 2) { return 0; } int result; try { result = Integer.parseInt(splits[1].trim()); } catch (NumberFormatException nfe) { result = 0; } return result; } private Long getDpidForIntegrationBridge(Node node) { // Check if node is integration bridge; and only then return its dpid if (southbound.getBridge(node, configurationService.getIntegrationBridgeName()) != null) { return southbound.getDataPathId(node); } return null; } private Long getDpidForExternalBridge(Node node) { // Check if node is external bridge; and only then return its dpid if (southbound.getBridge(node, configurationService.getExternalBridgeName()) != null) { return southbound.getDataPathId(node); } return null; } private Node getExternalBridgeNode(){ //Pickup the first node that has external bridge (br-ex). //NOTE: We are assuming that all the br-ex are serving one external network and gateway ip of //the external network is reachable from every br-ex // TODO: Consider other deployment scenario, and thing of better solution. List<Node> allBridges = nodeCacheManager.getBridgeNodes(); for(Node node : allBridges){ if (southbound.getBridge(node, configurationService.getExternalBridgeName()) != null) { return node; } } return null; } private NeutronSubnet getExternalNetworkSubnet(NeutronPort gatewayPort){ if (gatewayPort.getFixedIPs() == null) { return null; } for (Neutron_IPs neutronIPs : gatewayPort.getFixedIPs()) { String subnetUUID = neutronIPs.getSubnetUUID(); NeutronSubnet extSubnet = neutronSubnetCache.getSubnet(subnetUUID); if (extSubnet != null && extSubnet.getGatewayIP() != null) { return extSubnet; } if (extSubnet == null) { // TODO: when subnet is created, try again. LOG.debug("subnet {} in not found", subnetUUID); } } return null; } private void cleanupFloatingIPRules(final NeutronPort neutronPort) { List<NeutronFloatingIP> neutronFloatingIps = neutronFloatingIpCache.getAllFloatingIPs(); if (neutronFloatingIps != null && !neutronFloatingIps.isEmpty()) { for (NeutronFloatingIP neutronFloatingIP : neutronFloatingIps) { // Neutron floating Ip's port uuid cannot be null (Bug#5894) if (neutronFloatingIP.getPortUUID() != null && (neutronFloatingIP.getPortUUID().equals(neutronPort.getPortUUID()))) { handleNeutronFloatingIPEvent(neutronFloatingIP, DELETE); } } } } private void updateFloatingIPRules(final NeutronPort neutronPort) { List<NeutronFloatingIP> neutronFloatingIps = neutronFloatingIpCache.getAllFloatingIPs(); if (neutronFloatingIps != null) { for (NeutronFloatingIP neutronFloatingIP : neutronFloatingIps) { if (neutronFloatingIP.getPortUUID().equals(neutronPort.getPortUUID())) { handleNeutronFloatingIPEvent(neutronFloatingIP, UPDATE); } } } } private void triggerGatewayMacResolver(final NeutronPort gatewayPort){ Preconditions.checkNotNull(gatewayPort); NeutronNetwork externalNetwork = neutronNetworkCache.getNetwork(gatewayPort.getNetworkUUID()); if(externalNetwork != null){ if(externalNetwork.isRouterExternal()){ final NeutronSubnet externalSubnet = getExternalNetworkSubnet(gatewayPort); // TODO: address IPv6 case. if (externalSubnet != null && externalSubnet.getIpVersion() == 4 && gatewayPort.getFixedIPs() != null) { LOG.info("Trigger MAC resolution for gateway ip {}", externalSubnet.getGatewayIP()); Neutron_IPs neutronIP = null; for (Neutron_IPs nIP : gatewayPort.getFixedIPs()) { InetAddress ipAddress; try { ipAddress = InetAddress.getByName(nIP.getIpAddress()); } catch (UnknownHostException e) { LOG.warn("unknown host exception {}", e); continue; } if (ipAddress instanceof Inet4Address) { neutronIP = nIP; break; } } if (neutronIP == null) { // TODO IPv6 neighbor discovery LOG.debug("Ignoring gateway ports with IPv6 only fixed ip {}", gatewayPort.getFixedIPs()); } else { gatewayMacResolver.resolveMacAddress( this, /* gatewayMacResolverListener */ null, /* externalNetworkBridgeDpid */ true, /* refreshExternalNetworkBridgeDpidIfNeeded */ new Ipv4Address(externalSubnet.getGatewayIP()), new Ipv4Address(neutronIP.getIpAddress()), new MacAddress(gatewayPort.getMacAddress()), true /* periodicRefresh */); } } else { LOG.warn("No gateway IP address found for external network {}", externalNetwork); } } }else{ LOG.warn("Neutron network not found for router interface {}", gatewayPort); } } private void storePortInCleanupCache(NeutronPort port) { this.portCleanupCache.put(port.getPortUUID(),port); } private void updatePortInCleanupCache(NeutronPort updatedPort,NeutronPort originalPort) { removePortFromCleanupCache(originalPort); storePortInCleanupCache(updatedPort); } public void removePortFromCleanupCache(NeutronPort port) { if(port != null) { this.portCleanupCache.remove(port.getPortUUID()); } } public Map<String, NeutronPort> getPortCleanupCache() { return this.portCleanupCache; } public NeutronPort getPortFromCleanupCache(String portid) { for (String neutronPortUuid : this.portCleanupCache.keySet()) { if (neutronPortUuid.equals(portid)) { LOG.info("getPortFromCleanupCache: Matching NeutronPort found {}", portid); return this.portCleanupCache.get(neutronPortUuid); } } return null; } private void storeNetworkInCleanupCache(NeutronNetwork network) { this.networkCleanupCache.put(network.getNetworkUUID(), network); } private void updateNetworkInCleanupCache(NeutronNetwork network) { for (String neutronNetworkUuid:this.networkCleanupCache.keySet()) { if (neutronNetworkUuid.equals(network.getNetworkUUID())) { this.networkCleanupCache.remove(neutronNetworkUuid); } } this.networkCleanupCache.put(network.getNetworkUUID(), network); } public void removeNetworkFromCleanupCache(String networkid) { NeutronNetwork network = null; for (String neutronNetworkUuid:this.networkCleanupCache.keySet()) { if (neutronNetworkUuid.equals(networkid)) { network = networkCleanupCache.get(neutronNetworkUuid); break; } } if (network != null) { for (String neutronPortUuid:this.portCleanupCache.keySet()) { if (this.portCleanupCache.get(neutronPortUuid).getNetworkUUID().equals(network.getNetworkUUID())) { LOG.info("This network is used by another port", network); return; } } this.networkCleanupCache.remove(network.getNetworkUUID()); } } public Map<String, NeutronNetwork> getNetworkCleanupCache() { return this.networkCleanupCache; } public NeutronNetwork getNetworkFromCleanupCache(String networkid) { for (String neutronNetworkUuid:this.networkCleanupCache.keySet()) { if (neutronNetworkUuid.equals(networkid)) { LOG.info("getPortFromCleanupCache: Matching NeutronPort found {}", networkid); return networkCleanupCache.get(neutronNetworkUuid); } } return null; } /** * Return String that represents OF port with marker explicitly provided (reverse of MatchUtils:parseExplicitOFPort) * * @param ofPort the OF port number * @return the string with encoded OF port (example format "OFPort|999") */ public static String encodeExcplicitOFPort(Long ofPort) { return "OFPort|" + ofPort.toString(); } private void initNetworkCleanUpCache() { if (this.neutronNetworkCache != null) { for (NeutronNetwork neutronNetwork : neutronNetworkCache.getAllNetworks()) { networkCleanupCache.put(neutronNetwork.getNetworkUUID(), neutronNetwork); } } } private void initPortCleanUpCache() { if (this.neutronPortCache != null) { for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) { portCleanupCache.put(neutronPort.getPortUUID(), neutronPort); } } } @Override public void setDependencies(ServiceReference serviceReference) { eventDispatcher = (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this); eventDispatcher.eventHandlerAdded(serviceReference, this); tenantNetworkManager = (TenantNetworkManager) ServiceHelper.getGlobalInstance(TenantNetworkManager.class, this); configurationService = (ConfigurationService) ServiceHelper.getGlobalInstance(ConfigurationService.class, this); arpProvider = (ArpProvider) ServiceHelper.getGlobalInstance(ArpProvider.class, this); inboundNatProvider = (InboundNatProvider) ServiceHelper.getGlobalInstance(InboundNatProvider.class, this); outboundNatProvider = (OutboundNatProvider) ServiceHelper.getGlobalInstance(OutboundNatProvider.class, this); routingProvider = (RoutingProvider) ServiceHelper.getGlobalInstance(RoutingProvider.class, this); l3ForwardingProvider = (L3ForwardingProvider) ServiceHelper.getGlobalInstance(L3ForwardingProvider.class, this); distributedArpService = (DistributedArpService) ServiceHelper.getGlobalInstance(DistributedArpService.class, this); nodeCacheManager = (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this); southbound = (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this); gatewayMacResolver = (GatewayMacResolver) ServiceHelper.getGlobalInstance(GatewayMacResolver.class, this); securityServicesManager = (SecurityServicesManager) ServiceHelper.getGlobalInstance(SecurityServicesManager.class, this); initL3AdapterMembers(); } @Override public void setDependencies(Object impl) { if (impl instanceof INeutronNetworkCRUD) { neutronNetworkCache = (INeutronNetworkCRUD)impl; initNetworkCleanUpCache(); } else if (impl instanceof INeutronPortCRUD) { neutronPortCache = (INeutronPortCRUD)impl; initPortCleanUpCache(); } else if (impl instanceof INeutronSubnetCRUD) { neutronSubnetCache = (INeutronSubnetCRUD)impl; } else if (impl instanceof INeutronFloatingIPCRUD) { neutronFloatingIpCache = (INeutronFloatingIPCRUD)impl; } else if (impl instanceof ArpProvider) { arpProvider = (ArpProvider)impl; } else if (impl instanceof InboundNatProvider) { inboundNatProvider = (InboundNatProvider)impl; } else if (impl instanceof OutboundNatProvider) { outboundNatProvider = (OutboundNatProvider)impl; } else if (impl instanceof RoutingProvider) { routingProvider = (RoutingProvider)impl; } else if (impl instanceof L3ForwardingProvider) { l3ForwardingProvider = (L3ForwardingProvider)impl; }else if (impl instanceof GatewayMacResolver) { gatewayMacResolver = (GatewayMacResolver)impl; }else if (impl instanceof IcmpEchoProvider) { icmpEchoProvider = (IcmpEchoProvider)impl; } populateL3ForwardingCaches(); } }
openstack/net-virt/src/main/java/org/opendaylight/netvirt/openstack/netvirt/impl/NeutronL3Adapter.java
/* * Copyright (c) 2014 - 2016 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.netvirt.openstack.netvirt.impl; import static org.opendaylight.netvirt.openstack.netvirt.api.Action.ADD; import static org.opendaylight.netvirt.openstack.netvirt.api.Action.DELETE; import static org.opendaylight.netvirt.openstack.netvirt.api.Action.UPDATE; import com.google.common.base.Preconditions; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.opendaylight.netvirt.openstack.netvirt.AbstractEvent; import org.opendaylight.netvirt.openstack.netvirt.AbstractHandler; import org.opendaylight.netvirt.openstack.netvirt.ConfigInterface; import org.opendaylight.netvirt.openstack.netvirt.NeutronL3AdapterEvent; import org.opendaylight.netvirt.openstack.netvirt.api.Action; import org.opendaylight.netvirt.openstack.netvirt.api.ArpProvider; import org.opendaylight.netvirt.openstack.netvirt.api.ConfigurationService; import org.opendaylight.netvirt.openstack.netvirt.api.Constants; import org.opendaylight.netvirt.openstack.netvirt.api.EventDispatcher; import org.opendaylight.netvirt.openstack.netvirt.api.GatewayMacResolver; import org.opendaylight.netvirt.openstack.netvirt.api.GatewayMacResolverListener; import org.opendaylight.netvirt.openstack.netvirt.api.IcmpEchoProvider; import org.opendaylight.netvirt.openstack.netvirt.api.InboundNatProvider; import org.opendaylight.netvirt.openstack.netvirt.api.L3ForwardingProvider; import org.opendaylight.netvirt.openstack.netvirt.api.NodeCacheManager; import org.opendaylight.netvirt.openstack.netvirt.api.OutboundNatProvider; import org.opendaylight.netvirt.openstack.netvirt.api.RoutingProvider; import org.opendaylight.netvirt.openstack.netvirt.api.SecurityServicesManager; import org.opendaylight.netvirt.openstack.netvirt.api.Southbound; import org.opendaylight.netvirt.openstack.netvirt.api.Status; import org.opendaylight.netvirt.openstack.netvirt.api.StatusCode; import org.opendaylight.netvirt.openstack.netvirt.api.TenantNetworkManager; import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronFloatingIP; import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronNetwork; import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter; import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronRouter_Interface; import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSecurityGroup; import org.opendaylight.netvirt.openstack.netvirt.translator.Neutron_IPs; import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronFloatingIPCRUD; import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronNetworkCRUD; import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronPortCRUD; import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronPort; import org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet; import org.opendaylight.netvirt.openstack.netvirt.translator.crud.INeutronSubnetCRUD; import org.opendaylight.netvirt.openstack.netvirt.translator.iaware.impl.NeutronIAwareUtil; import org.opendaylight.netvirt.utils.neutron.utils.NeutronModelsDataStoreHelper; import org.opendaylight.netvirt.utils.servicehelper.ServiceHelper; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.Routers; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Neutron L3 Adapter implements a hub-like adapter for the various Neutron events. Based on * these events, the abstract router callbacks can be generated to the multi-tenant aware router, * as well as the multi-tenant router forwarding provider. */ public class NeutronL3Adapter extends AbstractHandler implements GatewayMacResolverListener, ConfigInterface { private static final Logger LOG = LoggerFactory.getLogger(NeutronL3Adapter.class); // The implementation for each of these services is resolved by the OSGi Service Manager private volatile ConfigurationService configurationService; private volatile TenantNetworkManager tenantNetworkManager; private volatile NodeCacheManager nodeCacheManager; private volatile INeutronNetworkCRUD neutronNetworkCache; private volatile INeutronSubnetCRUD neutronSubnetCache; private volatile INeutronPortCRUD neutronPortCache; private volatile INeutronFloatingIPCRUD neutronFloatingIpCache; private volatile L3ForwardingProvider l3ForwardingProvider; private volatile InboundNatProvider inboundNatProvider; private volatile OutboundNatProvider outboundNatProvider; private volatile ArpProvider arpProvider; private volatile RoutingProvider routingProvider; private volatile GatewayMacResolver gatewayMacResolver; private volatile SecurityServicesManager securityServicesManager; private volatile IcmpEchoProvider icmpEchoProvider; private class FloatIpData { // br-int of node where floating ip is associated with tenant port private final Long dpid; // patch port in br-int used to reach br-ex private final Long ofPort; // segmentation id of the net where fixed ip is instantiated private final String segId; // mac address assigned to neutron port of floating ip private final String macAddress; private final String floatingIpAddress; // ip address given to tenant vm private final String fixedIpAddress; private final String neutronRouterMac; FloatIpData(final Long dpid, final Long ofPort, final String segId, final String macAddress, final String floatingIpAddress, final String fixedIpAddress, final String neutronRouterMac) { this.dpid = dpid; this.ofPort = ofPort; this.segId = segId; this.macAddress = macAddress; this.floatingIpAddress = floatingIpAddress; this.fixedIpAddress = fixedIpAddress; this.neutronRouterMac = neutronRouterMac; } } private Map<String, String> networkIdToRouterMacCache; private Map<String, List<Neutron_IPs>> networkIdToRouterIpListCache; private Map<String, NeutronRouter_Interface> subnetIdToRouterInterfaceCache; private Map<String, Pair<Long, Uuid>> neutronPortToDpIdCache; private Map<String, FloatIpData> floatIpDataMapCache; private String externalRouterMac; private Boolean enabled = false; private Boolean isCachePopulationDone = false; private Map<String, NeutronPort> portCleanupCache; private Map<String, NeutronNetwork> networkCleanupCache; private Southbound southbound; private DistributedArpService distributedArpService; private NeutronModelsDataStoreHelper neutronModelsDataStoreHelper; private static final String OWNER_ROUTER_INTERFACE = "network:router_interface"; private static final String OWNER_ROUTER_INTERFACE_DISTRIBUTED = "network:router_interface_distributed"; private static final String OWNER_ROUTER_GATEWAY = "network:router_gateway"; private static final String OWNER_FLOATING_IP = "network:floatingip"; private static final String DEFAULT_EXT_RTR_MAC = "00:00:5E:00:01:01"; public NeutronL3Adapter(NeutronModelsDataStoreHelper neutronHelper) { LOG.info(">>>>>> NeutronL3Adapter constructor {}", this.getClass()); this.neutronModelsDataStoreHelper = neutronHelper; } private void initL3AdapterMembers() { Preconditions.checkNotNull(configurationService); if (configurationService.isL3ForwardingEnabled()) { this.networkIdToRouterMacCache = new HashMap<>(); this.networkIdToRouterIpListCache = new HashMap<>(); this.subnetIdToRouterInterfaceCache = new HashMap<>(); this.neutronPortToDpIdCache = new HashMap<>(); this.floatIpDataMapCache = new HashMap<>(); this.externalRouterMac = configurationService.getDefaultGatewayMacAddress(null); if (this.externalRouterMac == null) { this.externalRouterMac = DEFAULT_EXT_RTR_MAC; } this.enabled = true; LOG.info("OVSDB L3 forwarding is enabled"); } else { LOG.debug("OVSDB L3 forwarding is disabled"); } this.portCleanupCache = new HashMap<>(); this.networkCleanupCache = new HashMap<>(); } // // Callbacks from AbstractHandler // @Override public void processEvent(AbstractEvent abstractEvent) { if (!(abstractEvent instanceof NeutronL3AdapterEvent)) { LOG.error("Unable to process abstract event " + abstractEvent); return; } if (!this.enabled) { return; } NeutronL3AdapterEvent ev = (NeutronL3AdapterEvent) abstractEvent; switch (ev.getAction()) { case UPDATE: if (ev.getSubType() == NeutronL3AdapterEvent.SubType.SUBTYPE_EXTERNAL_MAC_UPDATE) { updateExternalRouterMac( ev.getMacAddress().getValue() ); } else { LOG.warn("Received update for an unexpected event " + ev); } break; case ADD: // fall through... // break; case DELETE: // fall through... // break; default: LOG.warn("Unable to process event " + ev); break; } } // // Callbacks from GatewayMacResolverListener // @Override public void gatewayMacResolved(Long externalNetworkBridgeDpid, IpAddress gatewayIpAddress, MacAddress macAddress) { LOG.info("got gatewayMacResolved callback for ip {} on dpid {} to mac {}", gatewayIpAddress, externalNetworkBridgeDpid, macAddress); if (!this.enabled) { return; } if (macAddress == null || macAddress.getValue() == null) { // TODO: handle cases when mac is null return; } // // Enqueue event so update is handled by adapter's thread // enqueueEvent( new NeutronL3AdapterEvent(externalNetworkBridgeDpid, gatewayIpAddress, macAddress) ); } private void populateL3ForwardingCaches() { if (!this.enabled) { return; } if(this.isCachePopulationDone || this.neutronFloatingIpCache == null || this.neutronPortCache == null ||this.neutronNetworkCache == null) { return; } this.isCachePopulationDone = true; LOG.debug("Populating NetVirt L3 caches from data store configuration"); Routers routers = this.neutronModelsDataStoreHelper.readAllNeutronRouters(); Ports ports = this.neutronModelsDataStoreHelper.readAllNeutronPorts(); if(routers != null && routers.getRouter() != null && ports != null) { LOG.debug("L3 Cache Population : {} Neutron router present in data store",routers.getRouter().size()); for( Router router : routers.getRouter()) { LOG.debug("L3 Cache Population : Populate caches for router {}",router); if(!ports.getPort().isEmpty()) { for( Port port : ports.getPort()) { if (port.getDeviceId().equals(router.getUuid().getValue()) && port.getDeviceOwner().equals(OWNER_ROUTER_INTERFACE)) { LOG.debug("L3 Cache Population : Router interface {} found.",port); networkIdToRouterMacCache.put(port.getNetworkId().getValue() , port.getMacAddress()); networkIdToRouterIpListCache.put(port.getNetworkId().getValue(), NeutronIAwareUtil.convertMDSalIpToNeutronIp(port.getFixedIps())); subnetIdToRouterInterfaceCache.put(port.getFixedIps().get(0).getSubnetId().getValue(), NeutronIAwareUtil.convertMDSalInterfaceToNeutronRouterInterface(port)); } } }else { LOG.warn("L3 Cache Population :Did not find any port information " + "in config Data Store for router {}",router); } } } LOG.debug("NetVirt L3 caches population is done"); } private Pair<Long, Uuid> getDpIdOfNeutronPort(String neutronTenantPortUuid) { if(neutronPortToDpIdCache.get(neutronTenantPortUuid) == null) { List<Node> bridges = this.southbound.readOvsdbTopologyBridgeNodes(); LOG.debug("getDpIdOfNeutronPort : {} bridges present in ovsdb topology",bridges.size()); for(Node bridge : bridges) { List<OvsdbTerminationPointAugmentation> interfaces = southbound.extractTerminationPointAugmentations(bridge); if(interfaces != null && !interfaces.isEmpty()) { LOG.debug("getDpIdOfNeutronPort : {} termination point present on bridge {}", interfaces.size(), bridge.getNodeId()); for (OvsdbTerminationPointAugmentation intf : interfaces) { NeutronPort neutronPort = tenantNetworkManager.getTenantPort(intf); if(neutronPort != null && neutronPort.getID().equals(neutronTenantPortUuid)) { Long dpId = getDpidForIntegrationBridge(bridge); Uuid interfaceUuid = intf.getInterfaceUuid(); LOG.debug("getDpIdOfNeutronPort : Found bridge {} and interface {} for the tenant neutron" + " port {}",dpId,interfaceUuid,neutronTenantPortUuid); handleInterfaceEventAdd(neutronPort.getPortUUID(), dpId, interfaceUuid); break; } } } } } return neutronPortToDpIdCache.get(neutronTenantPortUuid); } private Collection<FloatIpData> getAllFloatingIPsWithMetadata() { LOG.debug("getAllFloatingIPsWithMetadata : Fechting all floating Ips and it's metadata"); List<NeutronFloatingIP> neutronFloatingIps = neutronFloatingIpCache.getAllFloatingIPs(); if(neutronFloatingIps != null && !neutronFloatingIps.isEmpty()) { for (NeutronFloatingIP neutronFloatingIP : neutronFloatingIps) { if(!floatIpDataMapCache.containsKey(neutronFloatingIP.getID())){ LOG.debug("Metadata for floating ip {} is not present in the cache. " + "Fetching from data store.",neutronFloatingIP.getID()); this.getFloatingIPWithMetadata(neutronFloatingIP.getID()); } } } LOG.debug("getAllFloatingIPsWithMetadata : {} floating points found in data store",floatIpDataMapCache.size()); return floatIpDataMapCache.values(); } private FloatIpData getFloatingIPWithMetadata(String neutronFloatingId) { LOG.debug("getFloatingIPWithMetadata : Get Floating ip and it's meta data for neutron " + "floating id {} ",neutronFloatingId); if(floatIpDataMapCache.get(neutronFloatingId) == null) { NeutronFloatingIP neutronFloatingIP = neutronFloatingIpCache.getFloatingIP(neutronFloatingId); if (neutronFloatingIP == null) { LOG.error("getFloatingIPWithMetadata : Floating ip {} is missing from data store, that should not happen",neutronFloatingId); return null; } List<NeutronPort> neutronPorts = neutronPortCache.getAllPorts(); NeutronPort neutronPortForFloatIp = null; for (NeutronPort neutronPort : neutronPorts) { if (neutronPort.getDeviceOwner().equals(OWNER_FLOATING_IP) && neutronPort.getDeviceID().equals(neutronFloatingIP.getID())) { neutronPortForFloatIp = neutronPort; break; } } String neutronTenantPortUuid = neutronFloatingIP.getPortUUID(); if(neutronTenantPortUuid == null) { return null; } Pair<Long, Uuid> nodeIfPair = this.getDpIdOfNeutronPort(neutronTenantPortUuid); String floatingIpMac = neutronPortForFloatIp == null ? null : neutronPortForFloatIp.getMacAddress(); String fixedIpAddress = neutronFloatingIP.getFixedIPAddress(); String floatingIpAddress = neutronFloatingIP.getFloatingIPAddress(); NeutronPort tenantNeutronPort = neutronPortCache.getPort(neutronTenantPortUuid); NeutronNetwork tenantNeutronNetwork = tenantNeutronPort != null ? neutronNetworkCache.getNetwork(tenantNeutronPort.getNetworkUUID()) : null; String providerSegmentationId = tenantNeutronNetwork != null ? tenantNeutronNetwork.getProviderSegmentationID() : null; String neutronRouterMac = tenantNeutronNetwork != null ? networkIdToRouterMacCache.get(tenantNeutronNetwork.getID()) : null; if (nodeIfPair == null || neutronTenantPortUuid == null || providerSegmentationId == null || providerSegmentationId.isEmpty() || floatingIpMac == null || floatingIpMac.isEmpty() || neutronRouterMac == null || neutronRouterMac.isEmpty()) { LOG.debug("getFloatingIPWithMetadata :Floating IP {}<->{}, incomplete floatPort {} tenantPortUuid {} " + "seg {} mac {} rtrMac {}", fixedIpAddress, floatingIpAddress, neutronPortForFloatIp, neutronTenantPortUuid, providerSegmentationId, floatingIpMac, neutronRouterMac); return null; } // get ofport for patch port in br-int final Long dpId = nodeIfPair.getLeft(); final Long ofPort = findOFPortForExtPatch(dpId); if (ofPort == null) { LOG.warn("getFloatingIPWithMetadata : Unable to locate OF port of patch port " + "to connect floating ip to external bridge. dpid {}", dpId); return null; } final FloatIpData floatIpData = new FloatIpData(dpId, ofPort, providerSegmentationId, floatingIpMac, floatingIpAddress, fixedIpAddress, neutronRouterMac); floatIpDataMapCache.put(neutronFloatingIP.getID(), floatIpData); } return floatIpDataMapCache.get(neutronFloatingId); } /** * Invoked to configure the mac address for the external gateway in br-ex. ovsdb netvirt needs help in getting * mac for given ip in br-ex (bug 3378). For example, since ovsdb has no real arp, it needs a service in can * subscribe so that the mac address associated to the gateway ip address is available. * * @param externalRouterMacUpdate The mac address to be associated to the gateway. */ public void updateExternalRouterMac(final String externalRouterMacUpdate) { Preconditions.checkNotNull(externalRouterMacUpdate); flushExistingIpRewrite(); this.externalRouterMac = externalRouterMacUpdate; rebuildExistingIpRewrite(); } /** * Process the event. * * @param action the {@link Action} action to be handled. * @param subnet An instance of NeutronSubnet object. */ public void handleNeutronSubnetEvent(final NeutronSubnet subnet, Action action) { LOG.debug("Neutron subnet {} event : {}", action, subnet.toString()); if (action == ADD) { this.storeNetworkInCleanupCache(neutronNetworkCache.getNetwork(subnet.getNetworkUUID())); } } /** * Process the port event as a router interface event. * For a not delete action, since a port is only create when the tennat uses the subnet, it is required to * verify if all routers across all nodes have the interface for the port's subnet(s) configured. * * @param action the {@link Action} action to be handled. * @param neutronPort An instance of NeutronPort object. */ public void handleNeutronPortEvent(final NeutronPort neutronPort, Action action) { LOG.debug("Neutron port {} event : {}", action, neutronPort.toString()); if (action == UPDATE) { // FIXME: Bug 4971 Move cleanup cache to SG Impl this.updatePortInCleanupCache(neutronPort, neutronPort.getOriginalPort()); if (neutronPort.getPortSecurityEnabled()) { this.processSecurityGroupUpdate(neutronPort); } if (isPortSecurityEnableUpdated(neutronPort)) { this.processPortSecurityEnableUpdated(neutronPort); } } if (!this.enabled) { return; } final boolean isDelete = action == DELETE; if (action == DELETE) { // Bug 5164: Cleanup Floating IP OpenFlow Rules when port is deleted. this.cleanupFloatingIPRules(neutronPort); } else if (action == UPDATE){ // Bug 5353: VM restart cause floatingIp flows to be removed this.updateFloatingIPRules(neutronPort); } if (neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_GATEWAY)){ if (!isDelete) { LOG.info("Port {} is network router gateway interface, " + "triggering gateway resolution for the attached external network", neutronPort); this.triggerGatewayMacResolver(neutronPort); }else{ NeutronNetwork externalNetwork = neutronNetworkCache.getNetwork(neutronPort.getNetworkUUID()); if (null == externalNetwork) { externalNetwork = this.getNetworkFromCleanupCache(neutronPort.getNetworkUUID()); } if (externalNetwork != null && externalNetwork.isRouterExternal()) { final NeutronSubnet externalSubnet = getExternalNetworkSubnet(neutronPort); // TODO support IPv6 if (externalSubnet != null && externalSubnet.getIpVersion() == 4) { gatewayMacResolver.stopPeriodicRefresh(new Ipv4Address(externalSubnet.getGatewayIP())); } } } } // Treat the port event as a router interface event if the port belongs to router. This is a // helper for handling cases when handleNeutronRouterInterfaceEvent is not available // if (neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_INTERFACE) || neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_INTERFACE_DISTRIBUTED)) { if (neutronPort.getFixedIPs() != null) { for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { NeutronRouter_Interface neutronRouterInterface = new NeutronRouter_Interface(neutronIP.getSubnetUUID(), neutronPort.getPortUUID()); // id of router interface to be same as subnet neutronRouterInterface.setID(neutronIP.getSubnetUUID()); neutronRouterInterface.setTenantID(neutronPort.getTenantID()); this.handleNeutronRouterInterfaceEvent(null /*neutronRouter*/, neutronRouterInterface, action); } } } else { // We made it here, port is not used as a router interface. If this is not a delete action, make sure that // all nodes that are supposed to have a router interface for the port's subnet(s), have it configured. We // need to do this check here because a router interface is not added to a node until tenant becomes needed // there. // if (!isDelete && neutronPort.getFixedIPs() != null) { for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { NeutronRouter_Interface neutronRouterInterface = subnetIdToRouterInterfaceCache.get(neutronIP.getSubnetUUID()); if (neutronRouterInterface != null) { this.handleNeutronRouterInterfaceEvent(null /*neutronRouter*/, neutronRouterInterface, action); } } } this.updateL3ForNeutronPort(neutronPort, isDelete); } } /** * Process the event. * * @param action the {@link Action} action to be handled. * @param neutronRouter An instance of NeutronRouter object. */ public void handleNeutronRouterEvent(final NeutronRouter neutronRouter, Action action) { LOG.debug("Neutron router {} event : {}", action, neutronRouter.toString()); } /** * Process the event enforcing actions and verifying dependencies between all router's interface. For example, * delete the ports on the same subnet. * * @param action the {@link Action} action to be handled. * @param neutronRouter An instance of NeutronRouter object. * @param neutronRouterInterface An instance of NeutronRouter_Interface object. */ public void handleNeutronRouterInterfaceEvent(final NeutronRouter neutronRouter, final NeutronRouter_Interface neutronRouterInterface, Action action) { LOG.debug("Router interface {} got event {}. Subnet {}", neutronRouterInterface.getPortUUID(), action, neutronRouterInterface.getSubnetUUID()); if (!this.enabled) { return; } final boolean isDelete = action == DELETE; this.programFlowsForNeutronRouterInterface(neutronRouterInterface, isDelete); // As neutron router interface is added/removed, we need to iterate through all the neutron ports and // see if they are affected by l3 // for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) { boolean currPortShouldBeDeleted = false; // Note: delete in this case only applies to 1)router interface delete and 2)ports on the same subnet if (isDelete) { if (neutronPort.getFixedIPs() != null) { for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { if (neutronRouterInterface.getSubnetUUID().equalsIgnoreCase(neutronIP.getSubnetUUID())) { currPortShouldBeDeleted = true; break; } } } } this.updateL3ForNeutronPort(neutronPort, currPortShouldBeDeleted); } } /** * Invoked when a neutron message regarding the floating ip association is sent to odl via ml2. If the action is * a creation, it will first add ARP rules for the given floating ip and then configure the DNAT (rewrite the * packets from the floating IP address to the internal fixed ip) rules on OpenFlow Table 30 and SNAT rules (other * way around) on OpenFlow Table 100. * * @param actionIn the {@link Action} action to be handled. * @param neutronFloatingIP An {@link NeutronFloatingIP} instance of NeutronFloatingIP object. */ public void handleNeutronFloatingIPEvent(final NeutronFloatingIP neutronFloatingIP, Action actionIn) { Preconditions.checkNotNull(neutronFloatingIP); LOG.debug(" Floating IP {} {}<->{}, network uuid {}", actionIn, neutronFloatingIP.getFixedIPAddress(), neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getFloatingNetworkUUID()); if (!this.enabled) { return; } Action action; // Consider action to be delete if getFixedIPAddress is null // if (neutronFloatingIP.getFixedIPAddress() == null) { action = DELETE; } else { action = actionIn; } // this.programFlowsForFloatingIP(neutronFloatingIP, action == Action.DELETE); if (action != DELETE) { // must be first, as it updates floatIpDataMapCache programFlowsForFloatingIPArpAdd(neutronFloatingIP); programFlowsForFloatingIPInbound(neutronFloatingIP, ADD); programFlowsForFloatingIPOutbound(neutronFloatingIP, ADD); } else { programFlowsForFloatingIPOutbound(neutronFloatingIP, DELETE); programFlowsForFloatingIPInbound(neutronFloatingIP, DELETE); // must be last, as it updates floatIpDataMapCache programFlowsForFloatingIPArpDelete(neutronFloatingIP.getID()); } } /** * This method performs creation or deletion of in-bound rules into Table 30 for a existing available floating * ip, otherwise for newer one. */ private void programFlowsForFloatingIPInbound(final NeutronFloatingIP neutronFloatingIP, final Action action) { Preconditions.checkNotNull(neutronFloatingIP); final FloatIpData fid = getFloatingIPWithMetadata(neutronFloatingIP.getID()); if (fid == null) { LOG.trace("programFlowsForFloatingIPInboundAdd {} for {} uuid {} not in local cache", action, neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getID()); return; } programInboundIpRewriteStage1(fid.dpid, fid.ofPort, fid.segId, fid.floatingIpAddress, fid.fixedIpAddress, action); } /** * This method performs creation or deletion of out-bound rules into Table 100 for a existing available floating * ip, otherwise for newer one. */ private void programFlowsForFloatingIPOutbound(final NeutronFloatingIP neutronFloatingIP, final Action action) { Preconditions.checkNotNull(neutronFloatingIP); final FloatIpData fid = getFloatingIPWithMetadata(neutronFloatingIP.getID()); if (fid == null) { LOG.trace("programFlowsForFloatingIPOutbound {} for {} uuid {} not in local cache", action, neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getID()); return; } programOutboundIpRewriteStage1(fid, action); } private void flushExistingIpRewrite() { for (FloatIpData fid : getAllFloatingIPsWithMetadata()) { programOutboundIpRewriteStage1(fid, DELETE); } } private void rebuildExistingIpRewrite() { for (FloatIpData fid : getAllFloatingIPsWithMetadata()) { programOutboundIpRewriteStage1(fid, ADD); } } /** * This method creates ARP response rules into OpenFlow Table 30 for a given floating ip. In order to connect * to br-ex from br-int, a patch-port is used. Thus, the patch-port will be responsible to respond the ARP * requests. */ private void programFlowsForFloatingIPArpAdd(final NeutronFloatingIP neutronFloatingIP) { Preconditions.checkNotNull(neutronFloatingIP); Preconditions.checkNotNull(neutronFloatingIP.getFixedIPAddress()); Preconditions.checkNotNull(neutronFloatingIP.getFloatingIPAddress()); // find bridge Node where floating ip is configured by looking up cache for its port final NeutronPort neutronPortForFloatIp = findNeutronPortForFloatingIp(neutronFloatingIP.getID()); final String neutronTenantPortUuid = neutronFloatingIP.getPortUUID(); final Pair<Long, Uuid> nodeIfPair = this.getDpIdOfNeutronPort(neutronTenantPortUuid); final String floatingIpMac = neutronPortForFloatIp == null ? null : neutronPortForFloatIp.getMacAddress(); final String fixedIpAddress = neutronFloatingIP.getFixedIPAddress(); final String floatingIpAddress = neutronFloatingIP.getFloatingIPAddress(); final NeutronPort tenantNeutronPort = neutronPortCache.getPort(neutronTenantPortUuid); final NeutronNetwork tenantNeutronNetwork = tenantNeutronPort != null ? neutronNetworkCache.getNetwork(tenantNeutronPort.getNetworkUUID()) : null; final String providerSegmentationId = tenantNeutronNetwork != null ? tenantNeutronNetwork.getProviderSegmentationID() : null; final String neutronRouterMac = tenantNeutronNetwork != null ? networkIdToRouterMacCache.get(tenantNeutronNetwork.getID()) : null; if (nodeIfPair == null || neutronTenantPortUuid == null || providerSegmentationId == null || providerSegmentationId.isEmpty() || floatingIpMac == null || floatingIpMac.isEmpty() || neutronRouterMac == null || neutronRouterMac.isEmpty()) { LOG.trace("Floating IP {}<->{}, incomplete floatPort {} tenantPortUuid {} seg {} mac {} rtrMac {}", fixedIpAddress, floatingIpAddress, neutronPortForFloatIp, neutronTenantPortUuid, providerSegmentationId, floatingIpMac, neutronRouterMac); return; } // get ofport for patch port in br-int final Long dpId = nodeIfPair.getLeft(); final Long ofPort = findOFPortForExtPatch(dpId); if (ofPort == null) { LOG.warn("Unable to locate OF port of patch port to connect floating ip to external bridge. dpid {}", dpId); return; } // Respond to ARPs for the floating ip address by default, via the patch port that connects br-int to br-ex // if (distributedArpService.programStaticRuleStage1(dpId, encodeExcplicitOFPort(ofPort), floatingIpMac, floatingIpAddress, ADD)) { final FloatIpData floatIpData = new FloatIpData(dpId, ofPort, providerSegmentationId, floatingIpMac, floatingIpAddress, fixedIpAddress, neutronRouterMac); floatIpDataMapCache.put(neutronFloatingIP.getID(), floatIpData); LOG.info("Floating IP {}<->{} programmed ARP mac {} on OFport {} seg {} dpid {}", neutronFloatingIP.getFixedIPAddress(), neutronFloatingIP.getFloatingIPAddress(), floatingIpMac, ofPort, providerSegmentationId, dpId); } } private void programFlowsForFloatingIPArpDelete(final String neutronFloatingIPUuid) { final FloatIpData floatIpData = getFloatingIPWithMetadata(neutronFloatingIPUuid); if (floatIpData == null) { LOG.trace("programFlowsForFloatingIPArpDelete for uuid {} is not needed", neutronFloatingIPUuid); return; } if (distributedArpService.programStaticRuleStage1(floatIpData.dpid, encodeExcplicitOFPort(floatIpData.ofPort), floatIpData.macAddress, floatIpData.floatingIpAddress, DELETE)) { floatIpDataMapCache.remove(neutronFloatingIPUuid); LOG.info("Floating IP {} un-programmed ARP mac {} on {} dpid {}", floatIpData.floatingIpAddress, floatIpData.macAddress, floatIpData.ofPort, floatIpData.dpid); } } private NeutronPort findNeutronPortForFloatingIp(final String floatingIpUuid) { for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) { if (neutronPort.getDeviceOwner().equals(OWNER_FLOATING_IP) && neutronPort.getDeviceID().equals(floatingIpUuid)) { return neutronPort; } } return null; } private Long findOFPortForExtPatch(Long dpId) { final String brInt = configurationService.getIntegrationBridgeName(); final String brExt = configurationService.getExternalBridgeName(); final String portNameInt = configurationService.getPatchPortName(new ImmutablePair<>(brInt, brExt)); Preconditions.checkNotNull(dpId); Preconditions.checkNotNull(portNameInt); final long dpidPrimitive = dpId; for (Node node : nodeCacheManager.getBridgeNodes()) { if (dpidPrimitive == southbound.getDataPathId(node)) { final OvsdbTerminationPointAugmentation terminationPointOfBridge = southbound.getTerminationPointOfBridge(node, portNameInt); return terminationPointOfBridge == null ? null : terminationPointOfBridge.getOfport(); } } return null; } /** * Process the event. * * @param action the {@link Action} action to be handled. * @param neutronNetwork An {@link NeutronNetwork} instance of NeutronFloatingIP object. */ public void handleNeutronNetworkEvent(final NeutronNetwork neutronNetwork, Action action) { LOG.debug("neutronNetwork {}: network: {}", action, neutronNetwork); if (action == UPDATE) { this.updateNetworkInCleanupCache(neutronNetwork); } } // // Callbacks from OVSDB's southbound handler // /** * Process the event. * * @param bridgeNode An instance of Node object. * @param intf An {@link org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105 * .OvsdbTerminationPointAugmentation} instance of OvsdbTerminationPointAugmentation object. * @param neutronNetwork An {@link NeutronNetwork} instance of NeutronNetwork * object. * @param action the {@link Action} action to be handled. */ public void handleInterfaceEvent(final Node bridgeNode, final OvsdbTerminationPointAugmentation intf, final NeutronNetwork neutronNetwork, Action action) { LOG.debug("southbound interface {} node:{} interface:{}, neutronNetwork:{}", action, bridgeNode.getNodeId().getValue(), intf.getName(), neutronNetwork); final NeutronPort neutronPort = tenantNetworkManager.getTenantPort(intf); if (action != DELETE && neutronPort != null) { // FIXME: Bug 4971 Move cleanup cache to SG Impl storePortInCleanupCache(neutronPort); } if (!this.enabled) { return; } final Long dpId = getDpidForIntegrationBridge(bridgeNode); final Uuid interfaceUuid = intf.getInterfaceUuid(); LOG.trace("southbound interface {} node:{} interface:{}, neutronNetwork:{} port:{} dpid:{} intfUuid:{}", action, bridgeNode.getNodeId().getValue(), intf.getName(), neutronNetwork, neutronPort, dpId, interfaceUuid); if (neutronPort != null) { final String neutronPortUuid = neutronPort.getPortUUID(); if (action != DELETE && dpId != null && interfaceUuid != null) { handleInterfaceEventAdd(neutronPortUuid, dpId, interfaceUuid); } handleNeutronPortEvent(neutronPort, action); } if (action == DELETE && interfaceUuid != null) { handleInterfaceEventDelete(intf, dpId); } } private void handleInterfaceEventAdd(final String neutronPortUuid, Long dpId, final Uuid interfaceUuid) { neutronPortToDpIdCache.put(neutronPortUuid, new ImmutablePair<>(dpId, interfaceUuid)); LOG.debug("handleInterfaceEvent add cache entry NeutronPortUuid {} : dpid {}, ifUuid {}", neutronPortUuid, dpId, interfaceUuid.getValue()); } private void handleInterfaceEventDelete(final OvsdbTerminationPointAugmentation intf, final Long dpId) { // Remove entry from neutronPortToDpIdCache based on interface uuid for (Map.Entry<String, Pair<Long, Uuid>> entry : neutronPortToDpIdCache.entrySet()) { final String currPortUuid = entry.getKey(); if (intf.getInterfaceUuid().equals(entry.getValue().getRight())) { LOG.debug("handleInterfaceEventDelete remove cache entry NeutronPortUuid {} : dpid {}, ifUuid {}", currPortUuid, dpId, intf.getInterfaceUuid().getValue()); neutronPortToDpIdCache.remove(currPortUuid); break; } } } // // Internal helpers // private void updateL3ForNeutronPort(final NeutronPort neutronPort, final boolean isDelete) { final String networkUUID = neutronPort.getNetworkUUID(); final String routerMacAddress = networkIdToRouterMacCache.get(networkUUID); if(!isDelete) { // If there is no router interface handling the networkUUID, we are done if (routerMacAddress == null || routerMacAddress.isEmpty()) { return; } // If this is the neutron port for the router interface itself, ignore it as well. Ports that represent the // router interface are handled via handleNeutronRouterInterfaceEvent. if (routerMacAddress.equalsIgnoreCase(neutronPort.getMacAddress())) { return; } } final NeutronNetwork neutronNetwork = neutronNetworkCache.getNetwork(networkUUID); final String providerSegmentationId = neutronNetwork != null ? neutronNetwork.getProviderSegmentationID() : null; final String tenantMac = neutronPort.getMacAddress(); if (providerSegmentationId == null || providerSegmentationId.isEmpty() || tenantMac == null || tenantMac.isEmpty()) { // done: go no further w/out all the info needed... return; } final Action action = isDelete ? DELETE : ADD; List<Node> nodes = nodeCacheManager.getBridgeNodes(); if (nodes.isEmpty()) { LOG.trace("updateL3ForNeutronPort has no nodes to work with"); } for (Node node : nodes) { final Long dpid = getDpidForIntegrationBridge(node); if (dpid == null) { continue; } if (neutronPort.getFixedIPs() == null) { continue; } for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { final String tenantIpStr = neutronIP.getIpAddress(); if (tenantIpStr.isEmpty()) { continue; } // Configure L3 fwd. We do that regardless of tenant network present, because these rules are // still needed when routing to subnets non-local to node (bug 2076). programL3ForwardingStage1(node, dpid, providerSegmentationId, tenantMac, tenantIpStr, action); } } } private void processSecurityGroupUpdate(NeutronPort neutronPort) { LOG.trace("processSecurityGroupUpdate:" + neutronPort); /** * Get updated data and original data for the the changed. Identify the security groups that got * added and removed and call the appropriate providers for updating the flows. */ try { List<NeutronSecurityGroup> addedGroup = getsecurityGroupChanged(neutronPort, neutronPort.getOriginalPort()); List<NeutronSecurityGroup> deletedGroup = getsecurityGroupChanged(neutronPort.getOriginalPort(), neutronPort); if (null != addedGroup && !addedGroup.isEmpty()) { securityServicesManager.syncSecurityGroup(neutronPort,addedGroup,true); } if (null != deletedGroup && !deletedGroup.isEmpty()) { securityServicesManager.syncSecurityGroup(neutronPort,deletedGroup,false); } } catch (Exception e) { LOG.error("Exception in processSecurityGroupUpdate", e); } } private void processPortSecurityEnableUpdated(NeutronPort neutronPort) { LOG.trace("processPortSecurityEnableUpdated:" + neutronPort); securityServicesManager.syncFixedSecurityGroup(neutronPort, neutronPort.getPortSecurityEnabled()); } private boolean isPortSecurityEnableUpdated(NeutronPort neutronPort) { LOG.trace("isPortSecuirtyEnableUpdated:" + neutronPort); if (neutronPort.getOriginalPort().getPortSecurityEnabled() != neutronPort.getPortSecurityEnabled()) { return true; } return false; } private List<NeutronSecurityGroup> getsecurityGroupChanged(NeutronPort port1, NeutronPort port2) { LOG.trace("getsecurityGroupChanged:" + "Port1:" + port1 + "Port2" + port2); if (port1 == null) { return null; } List<NeutronSecurityGroup> list1 = new ArrayList<>(port1.getSecurityGroups()); if (port2 == null) { return list1; } List<NeutronSecurityGroup> list2 = new ArrayList<>(port2.getSecurityGroups()); for (Iterator<NeutronSecurityGroup> iterator = list1.iterator(); iterator.hasNext();) { NeutronSecurityGroup securityGroup1 = iterator.next(); for (NeutronSecurityGroup securityGroup2 :list2) { if (securityGroup1.getID().equals(securityGroup2.getID())) { iterator.remove(); } } } return list1; } private void programL3ForwardingStage1(Node node, Long dpid, String providerSegmentationId, String macAddress, String ipStr, Action actionForNode) { if (actionForNode == DELETE) { LOG.trace("Deleting Flow : programL3ForwardingStage1 for node {} providerId {} mac {} ip {} action {}", node.getNodeId().getValue(), providerSegmentationId, macAddress, ipStr, actionForNode); } if (actionForNode == ADD) { LOG.trace("Adding Flow : programL3ForwardingStage1 for node {} providerId {} mac {} ip {} action {}", node.getNodeId().getValue(), providerSegmentationId, macAddress, ipStr, actionForNode); } this.programL3ForwardingStage2(node, dpid, providerSegmentationId, macAddress, ipStr, actionForNode); } private Status programL3ForwardingStage2(Node node, Long dpid, String providerSegmentationId, String macAddress, String address, Action actionForNode) { Status status; try { InetAddress inetAddress = InetAddress.getByName(address); status = l3ForwardingProvider == null ? new Status(StatusCode.SUCCESS) : l3ForwardingProvider.programForwardingTableEntry(dpid, providerSegmentationId, inetAddress, macAddress, actionForNode); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { LOG.debug("ProgramL3Forwarding {} for mac:{} addr:{} node:{} action:{}", l3ForwardingProvider == null ? "skipped" : "programmed", macAddress, address, node.getNodeId().getValue(), actionForNode); } else { LOG.error("ProgramL3Forwarding failed for mac:{} addr:{} node:{} action:{} status:{}", macAddress, address, node.getNodeId().getValue(), actionForNode, status); } return status; } // -- private void programFlowsForNeutronRouterInterface(final NeutronRouter_Interface destNeutronRouterInterface, Boolean isDelete) { Preconditions.checkNotNull(destNeutronRouterInterface); final NeutronPort neutronPort = neutronPortCache.getPort(destNeutronRouterInterface.getPortUUID()); String macAddress = neutronPort != null ? neutronPort.getMacAddress() : null; List<Neutron_IPs> ipList = neutronPort != null ? neutronPort.getFixedIPs() : null; final NeutronSubnet subnet = neutronSubnetCache.getSubnet(destNeutronRouterInterface.getSubnetUUID()); final NeutronNetwork neutronNetwork = subnet != null ? neutronNetworkCache.getNetwork(subnet.getNetworkUUID()) : null; final String destinationSegmentationId = neutronNetwork != null ? neutronNetwork.getProviderSegmentationID() : null; final Boolean isExternal = neutronNetwork != null ? neutronNetwork.getRouterExternal() : Boolean.TRUE; final String cidr = subnet != null ? subnet.getCidr() : null; final int mask = getMaskLenFromCidr(cidr); LOG.trace("programFlowsForNeutronRouterInterface called for interface {} isDelete {}", destNeutronRouterInterface, isDelete); // in delete path, mac address as well as ip address are not provided. Being so, let's find them from // the local cache if (neutronNetwork != null) { if (macAddress == null || macAddress.isEmpty()) { macAddress = networkIdToRouterMacCache.get(neutronNetwork.getNetworkUUID()); } if (ipList == null || ipList.isEmpty()) { ipList = networkIdToRouterIpListCache.get(neutronNetwork.getNetworkUUID()); } } if (destinationSegmentationId == null || destinationSegmentationId.isEmpty() || cidr == null || cidr.isEmpty() || macAddress == null || macAddress.isEmpty() || ipList == null || ipList.isEmpty()) { LOG.debug("programFlowsForNeutronRouterInterface is bailing seg:{} cidr:{} mac:{} ip:{}", destinationSegmentationId, cidr, macAddress, ipList); // done: go no further w/out all the info needed... return; } final Action actionForNode = isDelete ? DELETE : ADD; // Keep cache for finding router's mac from network uuid -- add // if (! isDelete) { networkIdToRouterMacCache.put(neutronNetwork.getNetworkUUID(), macAddress); networkIdToRouterIpListCache.put(neutronNetwork.getNetworkUUID(), new ArrayList<>(ipList)); subnetIdToRouterInterfaceCache.put(subnet.getSubnetUUID(), destNeutronRouterInterface); } List<Node> nodes = nodeCacheManager.getBridgeNodes(); if (nodes.isEmpty()) { LOG.trace("programFlowsForNeutronRouterInterface has no nodes to work with"); } for (Node node : nodes) { final Long dpid = getDpidForIntegrationBridge(node); if (dpid == null) { continue; } for (Neutron_IPs neutronIP : ipList) { final String ipStr = neutronIP.getIpAddress(); if (ipStr.isEmpty()) { LOG.debug("programFlowsForNeutronRouterInterface is skipping node {} ip {}", node.getNodeId().getValue(), ipStr); continue; } // Iterate through all other interfaces and add/remove reflexive flows to this interface // for (NeutronRouter_Interface srcNeutronRouterInterface : subnetIdToRouterInterfaceCache.values()) { programFlowsForNeutronRouterInterfacePair(node, dpid, srcNeutronRouterInterface, destNeutronRouterInterface, neutronNetwork, destinationSegmentationId, macAddress, ipStr, mask, actionForNode, true /*isReflexsive*/); } if (! isExternal) { programFlowForNetworkFromExternal(node, dpid, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } // Enable ARP responder by default, because router interface needs to be responded always. distributedArpService.programStaticRuleStage1(dpid, destinationSegmentationId, macAddress, ipStr, actionForNode); programIcmpEcho(dpid, destinationSegmentationId, macAddress, ipStr, actionForNode); } // Compute action to be programmed. In the case of rewrite exclusions, we must never program rules // for the external neutron networks. // { final Action actionForRewriteExclusion = isExternal ? DELETE : actionForNode; programIpRewriteExclusionStage1(node, dpid, destinationSegmentationId, cidr, actionForRewriteExclusion); } } if (isDelete) { networkIdToRouterMacCache.remove(neutronNetwork.getNetworkUUID()); networkIdToRouterIpListCache.remove(neutronNetwork.getNetworkUUID()); subnetIdToRouterInterfaceCache.remove(subnet.getSubnetUUID()); } } private void programFlowForNetworkFromExternal(final Node node, final Long dpid, final String destinationSegmentationId, final String dstMacAddress, final String destIpStr, final int destMask, final Action actionForNode) { programRouterInterfaceStage1(node, dpid, Constants.EXTERNAL_NETWORK, destinationSegmentationId, dstMacAddress, destIpStr, destMask, actionForNode); } private void programFlowsForNeutronRouterInterfacePair(final Node node, final Long dpid, final NeutronRouter_Interface srcNeutronRouterInterface, final NeutronRouter_Interface dstNeutronRouterInterface, final NeutronNetwork dstNeutronNetwork, final String destinationSegmentationId, final String dstMacAddress, final String destIpStr, final int destMask, final Action actionForNode, Boolean isReflexsive) { Preconditions.checkNotNull(srcNeutronRouterInterface); Preconditions.checkNotNull(dstNeutronRouterInterface); final String sourceSubnetId = srcNeutronRouterInterface.getSubnetUUID(); if (sourceSubnetId == null) { LOG.error("Could not get provider Subnet ID from router interface {}", srcNeutronRouterInterface.getID()); return; } final NeutronSubnet sourceSubnet = neutronSubnetCache.getSubnet(sourceSubnetId); final String sourceNetworkId = sourceSubnet == null ? null : sourceSubnet.getNetworkUUID(); if (sourceNetworkId == null) { LOG.error("Could not get provider Network ID from subnet {}", sourceSubnetId); return; } final NeutronNetwork sourceNetwork = neutronNetworkCache.getNetwork(sourceNetworkId); if (sourceNetwork == null) { LOG.error("Could not get provider Network for Network ID {}", sourceNetworkId); return; } if (! sourceNetwork.getTenantID().equals(dstNeutronNetwork.getTenantID())) { // Isolate subnets from different tenants within the same router return; } final String sourceSegmentationId = sourceNetwork.getProviderSegmentationID(); if (sourceSegmentationId == null) { LOG.error("Could not get provider Segmentation ID for Subnet {}", sourceSubnetId); return; } if (sourceSegmentationId.equals(destinationSegmentationId)) { // Skip 'self' return; } programRouterInterfaceStage1(node, dpid, sourceSegmentationId, destinationSegmentationId, dstMacAddress, destIpStr, destMask, actionForNode); // Flip roles src->dst; dst->src if (isReflexsive) { final NeutronPort sourceNeutronPort = neutronPortCache.getPort(srcNeutronRouterInterface.getPortUUID()); final String macAddress2 = sourceNeutronPort != null ? sourceNeutronPort.getMacAddress() : null; final List<Neutron_IPs> ipList2 = sourceNeutronPort != null ? sourceNeutronPort.getFixedIPs() : null; final String cidr2 = sourceSubnet.getCidr(); final int mask2 = getMaskLenFromCidr(cidr2); if (cidr2 == null || cidr2.isEmpty() || macAddress2 == null || macAddress2.isEmpty() || ipList2 == null || ipList2.isEmpty()) { LOG.trace("programFlowsForNeutronRouterInterfacePair reflexive is bailing seg:{} cidr:{} mac:{} ip:{}", sourceSegmentationId, cidr2, macAddress2, ipList2); // done: go no further w/out all the info needed... return; } for (Neutron_IPs neutronIP2 : ipList2) { final String ipStr2 = neutronIP2.getIpAddress(); if (ipStr2.isEmpty()) { continue; } programFlowsForNeutronRouterInterfacePair(node, dpid, dstNeutronRouterInterface, srcNeutronRouterInterface, sourceNetwork, sourceSegmentationId, macAddress2, ipStr2, mask2, actionForNode, false /*isReflexsive*/); } } } private void programRouterInterfaceStage1(Node node, Long dpid, String sourceSegmentationId, String destinationSegmentationId, String macAddress, String ipStr, int mask, Action actionForNode) { if (actionForNode == DELETE) { LOG.trace("Deleting Flow : programRouterInterfaceStage1 for node {} sourceSegId {} destSegId {} mac {} ip {} mask {}" + " action {}", node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } if (actionForNode == ADD) { LOG.trace("Adding Flow : programRouterInterfaceStage1 for node {} sourceSegId {} destSegId {} mac {} ip {} mask {}" + " action {}", node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } this.programRouterInterfaceStage2(node, dpid, sourceSegmentationId, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } private Status programRouterInterfaceStage2(Node node, Long dpid, String sourceSegmentationId, String destinationSegmentationId, String macAddress, String address, int mask, Action actionForNode) { Status status; try { InetAddress inetAddress = InetAddress.getByName(address); status = routingProvider == null ? new Status(StatusCode.SUCCESS) : routingProvider.programRouterInterface(dpid, sourceSegmentationId, destinationSegmentationId, macAddress, inetAddress, mask, actionForNode); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { LOG.debug("programRouterInterfaceStage2 {} for mac:{} addr:{}/{} node:{} srcTunId:{} destTunId:{} action:{}", routingProvider == null ? "skipped" : "programmed", macAddress, address, mask, node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, actionForNode); } else { LOG.error("programRouterInterfaceStage2 failed for mac:{} addr:{}/{} node:{} srcTunId:{} destTunId:{} action:{} status:{}", macAddress, address, mask, node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, actionForNode, status); } return status; } private boolean programIcmpEcho(Long dpid, String segOrOfPort, String macAddress, String ipStr, Action action) { if (action == DELETE ) { LOG.trace("Deleting Flow : programIcmpEcho dpid {} segOrOfPort {} mac {} ip {} action {}", dpid, segOrOfPort, macAddress, ipStr, action); } if (action == ADD) { LOG.trace("Adding Flow : programIcmpEcho dpid {} segOrOfPort {} mac {} ip {} action {}", dpid, segOrOfPort, macAddress, ipStr, action); } Status status = new Status(StatusCode.UNSUPPORTED); if (icmpEchoProvider != null){ try { InetAddress inetAddress = InetAddress.getByName(ipStr); status = icmpEchoProvider.programIcmpEchoEntry(dpid, segOrOfPort, macAddress, inetAddress, action); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } } if (status.isSuccess()) { LOG.debug("programIcmpEcho {} for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{}", icmpEchoProvider == null ? "skipped" : "programmed", macAddress, ipStr, dpid, segOrOfPort, action); } else { LOG.error("programIcmpEcho failed for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{} status:{}", macAddress, ipStr, dpid, segOrOfPort, action, status); } return status.isSuccess(); } private boolean programInboundIpRewriteStage1(Long dpid, Long inboundOFPort, String providerSegmentationId, String matchAddress, String rewriteAddress, Action action) { if (action == DELETE ) { LOG.trace("Deleting Flow : programInboundIpRewriteStage1 dpid {} OFPort {} seg {} matchAddress {} rewriteAddress {}" + " action {}", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); } if (action == ADD ) { LOG.trace("Adding Flow : programInboundIpRewriteStage1 dpid {} OFPort {} seg {} matchAddress {} rewriteAddress {}" + " action {}", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); } Status status = programInboundIpRewriteStage2(dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); return status.isSuccess(); } private Status programInboundIpRewriteStage2(Long dpid, Long inboundOFPort, String providerSegmentationId, String matchAddress, String rewriteAddress, Action action) { Status status; try { InetAddress inetMatchAddress = InetAddress.getByName(matchAddress); InetAddress inetRewriteAddress = InetAddress.getByName(rewriteAddress); status = inboundNatProvider == null ? new Status(StatusCode.SUCCESS) : inboundNatProvider.programIpRewriteRule(dpid, inboundOFPort, providerSegmentationId, inetMatchAddress, inetRewriteAddress, action); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { final boolean isSkipped = inboundNatProvider == null; LOG.debug("programInboundIpRewriteStage2 {} for dpid:{} ofPort:{} seg:{} match:{} rewrite:{} action:{}", isSkipped ? "skipped" : "programmed", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); } else { LOG.error("programInboundIpRewriteStage2 failed for dpid:{} ofPort:{} seg:{} match:{} rewrite:{} action:{}" + " status:{}", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action, status); } return status; } private void programIpRewriteExclusionStage1(Node node, Long dpid, String providerSegmentationId, String cidr, Action actionForRewriteExclusion) { if (actionForRewriteExclusion == DELETE ) { LOG.trace("Deleting Flow : programIpRewriteExclusionStage1 node {} providerId {} cidr {} action {}", node.getNodeId().getValue(), providerSegmentationId, cidr, actionForRewriteExclusion); } if (actionForRewriteExclusion == ADD) { LOG.trace("Adding Flow : programIpRewriteExclusionStage1 node {} providerId {} cidr {} action {}", node.getNodeId().getValue(), providerSegmentationId, cidr, actionForRewriteExclusion); } this.programIpRewriteExclusionStage2(node, dpid, providerSegmentationId, cidr,actionForRewriteExclusion); } private Status programIpRewriteExclusionStage2(Node node, Long dpid, String providerSegmentationId, String cidr, Action actionForNode) { final Status status = outboundNatProvider == null ? new Status(StatusCode.SUCCESS) : outboundNatProvider.programIpRewriteExclusion(dpid, providerSegmentationId, cidr, actionForNode); if (status.isSuccess()) { final boolean isSkipped = outboundNatProvider == null; LOG.debug("IpRewriteExclusion {} for cidr:{} node:{} action:{}", isSkipped ? "skipped" : "programmed", cidr, node.getNodeId().getValue(), actionForNode); } else { LOG.error("IpRewriteExclusion failed for cidr:{} node:{} action:{} status:{}", cidr, node.getNodeId().getValue(), actionForNode, status); } return status; } private void programOutboundIpRewriteStage1(FloatIpData fid, Action action) { if (action == DELETE) { LOG.trace("Deleting Flow : programOutboundIpRewriteStage1 dpid {} seg {} fixedIpAddress {} floatIp {} action {} ", fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action); } if (action == ADD) { LOG.trace("Adding Flow : programOutboundIpRewriteStage1 dpid {} seg {} fixedIpAddress {} floatIp {} action {} " , fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action); } this.programOutboundIpRewriteStage2(fid, action); } private Status programOutboundIpRewriteStage2(FloatIpData fid, Action action) { Status status; try { InetAddress matchSrcAddress = InetAddress.getByName(fid.fixedIpAddress); InetAddress rewriteSrcAddress = InetAddress.getByName(fid.floatingIpAddress); status = outboundNatProvider == null ? new Status(StatusCode.SUCCESS) : outboundNatProvider.programIpRewriteRule( fid.dpid, fid.segId, fid.neutronRouterMac, matchSrcAddress, fid.macAddress, this.externalRouterMac, rewriteSrcAddress, fid.ofPort, action); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { final boolean isSkipped = outboundNatProvider == null; LOG.debug("programOutboundIpRewriteStage2 {} for dpid {} seg {} fixedIpAddress {} floatIp {}" + " action {}", isSkipped ? "skipped" : "programmed", fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action); } else { LOG.error("programOutboundIpRewriteStage2 failed for dpid {} seg {} fixedIpAddress {} floatIp {}" + " action {} status:{}", fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action, status); } return status; } private int getMaskLenFromCidr(String cidr) { if (cidr == null) { return 0; } String[] splits = cidr.split("/"); if (splits.length != 2) { return 0; } int result; try { result = Integer.parseInt(splits[1].trim()); } catch (NumberFormatException nfe) { result = 0; } return result; } private Long getDpidForIntegrationBridge(Node node) { // Check if node is integration bridge; and only then return its dpid if (southbound.getBridge(node, configurationService.getIntegrationBridgeName()) != null) { return southbound.getDataPathId(node); } return null; } private Long getDpidForExternalBridge(Node node) { // Check if node is external bridge; and only then return its dpid if (southbound.getBridge(node, configurationService.getExternalBridgeName()) != null) { return southbound.getDataPathId(node); } return null; } private Node getExternalBridgeNode(){ //Pickup the first node that has external bridge (br-ex). //NOTE: We are assuming that all the br-ex are serving one external network and gateway ip of //the external network is reachable from every br-ex // TODO: Consider other deployment scenario, and thing of better solution. List<Node> allBridges = nodeCacheManager.getBridgeNodes(); for(Node node : allBridges){ if (southbound.getBridge(node, configurationService.getExternalBridgeName()) != null) { return node; } } return null; } private NeutronSubnet getExternalNetworkSubnet(NeutronPort gatewayPort){ if (gatewayPort.getFixedIPs() == null) { return null; } for (Neutron_IPs neutronIPs : gatewayPort.getFixedIPs()) { String subnetUUID = neutronIPs.getSubnetUUID(); NeutronSubnet extSubnet = neutronSubnetCache.getSubnet(subnetUUID); if (extSubnet != null && extSubnet.getGatewayIP() != null) { return extSubnet; } if (extSubnet == null) { // TODO: when subnet is created, try again. LOG.debug("subnet {} in not found", subnetUUID); } } return null; } private void cleanupFloatingIPRules(final NeutronPort neutronPort) { List<NeutronFloatingIP> neutronFloatingIps = neutronFloatingIpCache.getAllFloatingIPs(); if (neutronFloatingIps != null && !neutronFloatingIps.isEmpty()) { for (NeutronFloatingIP neutronFloatingIP : neutronFloatingIps) { if (neutronFloatingIP.getPortUUID().equals(neutronPort.getPortUUID())) { handleNeutronFloatingIPEvent(neutronFloatingIP, DELETE); } } } } private void updateFloatingIPRules(final NeutronPort neutronPort) { List<NeutronFloatingIP> neutronFloatingIps = neutronFloatingIpCache.getAllFloatingIPs(); if (neutronFloatingIps != null) { for (NeutronFloatingIP neutronFloatingIP : neutronFloatingIps) { if (neutronFloatingIP.getPortUUID().equals(neutronPort.getPortUUID())) { handleNeutronFloatingIPEvent(neutronFloatingIP, UPDATE); } } } } private void triggerGatewayMacResolver(final NeutronPort gatewayPort){ Preconditions.checkNotNull(gatewayPort); NeutronNetwork externalNetwork = neutronNetworkCache.getNetwork(gatewayPort.getNetworkUUID()); if(externalNetwork != null){ if(externalNetwork.isRouterExternal()){ final NeutronSubnet externalSubnet = getExternalNetworkSubnet(gatewayPort); // TODO: address IPv6 case. if (externalSubnet != null && externalSubnet.getIpVersion() == 4 && gatewayPort.getFixedIPs() != null) { LOG.info("Trigger MAC resolution for gateway ip {}", externalSubnet.getGatewayIP()); Neutron_IPs neutronIP = null; for (Neutron_IPs nIP : gatewayPort.getFixedIPs()) { InetAddress ipAddress; try { ipAddress = InetAddress.getByName(nIP.getIpAddress()); } catch (UnknownHostException e) { LOG.warn("unknown host exception {}", e); continue; } if (ipAddress instanceof Inet4Address) { neutronIP = nIP; break; } } if (neutronIP == null) { // TODO IPv6 neighbor discovery LOG.debug("Ignoring gateway ports with IPv6 only fixed ip {}", gatewayPort.getFixedIPs()); } else { gatewayMacResolver.resolveMacAddress( this, /* gatewayMacResolverListener */ null, /* externalNetworkBridgeDpid */ true, /* refreshExternalNetworkBridgeDpidIfNeeded */ new Ipv4Address(externalSubnet.getGatewayIP()), new Ipv4Address(neutronIP.getIpAddress()), new MacAddress(gatewayPort.getMacAddress()), true /* periodicRefresh */); } } else { LOG.warn("No gateway IP address found for external network {}", externalNetwork); } } }else{ LOG.warn("Neutron network not found for router interface {}", gatewayPort); } } private void storePortInCleanupCache(NeutronPort port) { this.portCleanupCache.put(port.getPortUUID(),port); } private void updatePortInCleanupCache(NeutronPort updatedPort,NeutronPort originalPort) { removePortFromCleanupCache(originalPort); storePortInCleanupCache(updatedPort); } public void removePortFromCleanupCache(NeutronPort port) { if(port != null) { this.portCleanupCache.remove(port.getPortUUID()); } } public Map<String, NeutronPort> getPortCleanupCache() { return this.portCleanupCache; } public NeutronPort getPortFromCleanupCache(String portid) { for (String neutronPortUuid : this.portCleanupCache.keySet()) { if (neutronPortUuid.equals(portid)) { LOG.info("getPortFromCleanupCache: Matching NeutronPort found {}", portid); return this.portCleanupCache.get(neutronPortUuid); } } return null; } private void storeNetworkInCleanupCache(NeutronNetwork network) { this.networkCleanupCache.put(network.getNetworkUUID(), network); } private void updateNetworkInCleanupCache(NeutronNetwork network) { for (String neutronNetworkUuid:this.networkCleanupCache.keySet()) { if (neutronNetworkUuid.equals(network.getNetworkUUID())) { this.networkCleanupCache.remove(neutronNetworkUuid); } } this.networkCleanupCache.put(network.getNetworkUUID(), network); } public void removeNetworkFromCleanupCache(String networkid) { NeutronNetwork network = null; for (String neutronNetworkUuid:this.networkCleanupCache.keySet()) { if (neutronNetworkUuid.equals(networkid)) { network = networkCleanupCache.get(neutronNetworkUuid); break; } } if (network != null) { for (String neutronPortUuid:this.portCleanupCache.keySet()) { if (this.portCleanupCache.get(neutronPortUuid).getNetworkUUID().equals(network.getNetworkUUID())) { LOG.info("This network is used by another port", network); return; } } this.networkCleanupCache.remove(network.getNetworkUUID()); } } public Map<String, NeutronNetwork> getNetworkCleanupCache() { return this.networkCleanupCache; } public NeutronNetwork getNetworkFromCleanupCache(String networkid) { for (String neutronNetworkUuid:this.networkCleanupCache.keySet()) { if (neutronNetworkUuid.equals(networkid)) { LOG.info("getPortFromCleanupCache: Matching NeutronPort found {}", networkid); return networkCleanupCache.get(neutronNetworkUuid); } } return null; } /** * Return String that represents OF port with marker explicitly provided (reverse of MatchUtils:parseExplicitOFPort) * * @param ofPort the OF port number * @return the string with encoded OF port (example format "OFPort|999") */ public static String encodeExcplicitOFPort(Long ofPort) { return "OFPort|" + ofPort.toString(); } private void initNetworkCleanUpCache() { if (this.neutronNetworkCache != null) { for (NeutronNetwork neutronNetwork : neutronNetworkCache.getAllNetworks()) { networkCleanupCache.put(neutronNetwork.getNetworkUUID(), neutronNetwork); } } } private void initPortCleanUpCache() { if (this.neutronPortCache != null) { for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) { portCleanupCache.put(neutronPort.getPortUUID(), neutronPort); } } } @Override public void setDependencies(ServiceReference serviceReference) { eventDispatcher = (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this); eventDispatcher.eventHandlerAdded(serviceReference, this); tenantNetworkManager = (TenantNetworkManager) ServiceHelper.getGlobalInstance(TenantNetworkManager.class, this); configurationService = (ConfigurationService) ServiceHelper.getGlobalInstance(ConfigurationService.class, this); arpProvider = (ArpProvider) ServiceHelper.getGlobalInstance(ArpProvider.class, this); inboundNatProvider = (InboundNatProvider) ServiceHelper.getGlobalInstance(InboundNatProvider.class, this); outboundNatProvider = (OutboundNatProvider) ServiceHelper.getGlobalInstance(OutboundNatProvider.class, this); routingProvider = (RoutingProvider) ServiceHelper.getGlobalInstance(RoutingProvider.class, this); l3ForwardingProvider = (L3ForwardingProvider) ServiceHelper.getGlobalInstance(L3ForwardingProvider.class, this); distributedArpService = (DistributedArpService) ServiceHelper.getGlobalInstance(DistributedArpService.class, this); nodeCacheManager = (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this); southbound = (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this); gatewayMacResolver = (GatewayMacResolver) ServiceHelper.getGlobalInstance(GatewayMacResolver.class, this); securityServicesManager = (SecurityServicesManager) ServiceHelper.getGlobalInstance(SecurityServicesManager.class, this); initL3AdapterMembers(); } @Override public void setDependencies(Object impl) { if (impl instanceof INeutronNetworkCRUD) { neutronNetworkCache = (INeutronNetworkCRUD)impl; initNetworkCleanUpCache(); } else if (impl instanceof INeutronPortCRUD) { neutronPortCache = (INeutronPortCRUD)impl; initPortCleanUpCache(); } else if (impl instanceof INeutronSubnetCRUD) { neutronSubnetCache = (INeutronSubnetCRUD)impl; } else if (impl instanceof INeutronFloatingIPCRUD) { neutronFloatingIpCache = (INeutronFloatingIPCRUD)impl; } else if (impl instanceof ArpProvider) { arpProvider = (ArpProvider)impl; } else if (impl instanceof InboundNatProvider) { inboundNatProvider = (InboundNatProvider)impl; } else if (impl instanceof OutboundNatProvider) { outboundNatProvider = (OutboundNatProvider)impl; } else if (impl instanceof RoutingProvider) { routingProvider = (RoutingProvider)impl; } else if (impl instanceof L3ForwardingProvider) { l3ForwardingProvider = (L3ForwardingProvider)impl; }else if (impl instanceof GatewayMacResolver) { gatewayMacResolver = (GatewayMacResolver)impl; }else if (impl instanceof IcmpEchoProvider) { icmpEchoProvider = (IcmpEchoProvider)impl; } populateL3ForwardingCaches(); } }
BUG-5894 NullPointerException while deleting the interface from router. * While deleting the interface from router, checking the floatingIp's port uuid is null else delete the respective floating Ip. Change-Id: I36ed6c25716cc1993de1cb110edf3a0ba47816e7 Signed-off-by: arthi.b <[email protected]>
openstack/net-virt/src/main/java/org/opendaylight/netvirt/openstack/netvirt/impl/NeutronL3Adapter.java
BUG-5894 NullPointerException while deleting the interface from router. * While deleting the interface from router, checking the floatingIp's port uuid is null else delete the respective floating Ip.
Java
epl-1.0
4cc8846ba8916f1270bf03b25d07410184b81a23
0
Yakindu/statecharts,Yakindu/statecharts,Yakindu/statecharts,Yakindu/statecharts,Yakindu/statecharts,Yakindu/statecharts,Yakindu/statecharts
/** * Copyright (c) 2011 committers of YAKINDU and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * Contributors: * committers of YAKINDU - initial API and implementation * */ package org.yakindu.sct.ui.editor.propertysheets; import java.util.List; import org.eclipse.core.databinding.UpdateValueStrategy; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.emf.databinding.EMFDataBindingContext; import org.eclipse.emf.databinding.IEMFValueProperty; import org.eclipse.emf.databinding.edit.EMFEditProperties; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.transaction.util.TransactionUtil; import org.eclipse.jface.databinding.swt.ISWTObservableValue; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.jface.databinding.viewers.IViewerObservableValue; import org.eclipse.jface.databinding.viewers.ViewersObservables; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.Text; import org.yakindu.base.base.BasePackage; import org.yakindu.sct.domain.extension.DomainRegistry; import org.yakindu.sct.domain.extension.IDomain; import org.yakindu.sct.model.sgraph.SGraphPackage; import org.yakindu.sct.model.sgraph.Statechart; import org.yakindu.sct.ui.editor.propertysheets.OrderElementControl.ISourceObjectCallback; import org.yakindu.sct.ui.editor.utils.HelpContextIds; import com.google.inject.Injector; /** * * @author andreas muelder - Initial contribution and API * */ public class StatechartPropertySection extends AbstractTwoColumnEditorPropertySection implements ISourceObjectCallback { private Control textControl; private Text txtName; private OrderElementControl orderElementControl; private Text documentation; private ComboViewer domainCombo; @Override protected Layout createLeftColumnLayout() { return new GridLayout(2, false); } @Override protected void createLeftColumnControls(Composite leftColumn) { createNameControl(leftColumn); createDomainCombo(leftColumn); createSpecificationControl(leftColumn); } protected void createDomainCombo(Composite leftColumn) { Label label = getToolkit().createLabel(leftColumn, "Statechart domain"); GridDataFactory.fillDefaults().span(2, 1).align(SWT.FILL, SWT.CENTER).applyTo(label); domainCombo = new ComboViewer(leftColumn); GridDataFactory.fillDefaults().span(1, 1).align(SWT.FILL, SWT.CENTER).applyTo(domainCombo.getCombo()); Label spacer = getToolkit().createLabel(leftColumn, ""); GridDataFactory.fillDefaults().applyTo(spacer); domainCombo.setContentProvider(new ArrayContentProvider()); domainCombo.setLabelProvider(new LabelProvider() { @Override public String getText(Object element) { return ((IDomain) element).getName(); } }); List<IDomain> domains = DomainRegistry.getDomains(); for (IDomain domainDescriptor : domains) { domainCombo.add(domainDescriptor); } if (domains.size() <= 1) { domainCombo.getControl().setEnabled(false); } } @Override protected void createRightColumnControls(Composite rightColumn) { createDocumentationControl(rightColumn); createRegionsControl(rightColumn); } protected void createNameControl(Composite parent) { Label lblName = getToolkit().createLabel(parent, "Statechart Name: "); txtName = getToolkit().createText(parent, ""); GridDataFactory.fillDefaults().span(2, 1).applyTo(lblName); new Label(parent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).applyTo(txtName); } protected void createRegionsControl(Composite rightColumn) { Label label = getToolkit().createLabel(rightColumn, "Region Priority:"); GridDataFactory.fillDefaults().applyTo(label); orderElementControl = new OrderElementControl(rightColumn, SGraphPackage.Literals.COMPOSITE_ELEMENT__REGIONS, this, "Statechart contains no regions"); GridDataFactory.fillDefaults().span(2, 0).grab(true, false).applyTo(orderElementControl); } protected void createDocumentationControl(Composite parent) { Label lblDocumentation = getToolkit().createLabel(parent, "Documentation: "); documentation = getToolkit().createText(parent, "", SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.WRAP); GridDataFactory.fillDefaults().applyTo(lblDocumentation); GridDataFactory.fillDefaults().grab(true, true).hint(parent.getSize()).applyTo(documentation); } protected void createSpecificationControl(final Composite parent) { Label lblDocumentation = getToolkit().createLabel(parent, "Statechart Behavior: "); Injector injector = getInjector(Statechart.class.getName()); if (injector != null) { textControl = new StyledText(parent, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.WRAP); ((StyledText) textControl).setAlwaysShowScrollBars(false); enableXtext(textControl, injector); createHelpWidget(parent, textControl, HelpContextIds.SC_PROPERTIES_STATECHART_EXPRESSION); } else { textControl = getToolkit().createText(parent, "", SWT.MULTI); } GridDataFactory.fillDefaults().span(2, 1).applyTo(lblDocumentation); GridDataFactory.fillDefaults().grab(true, true).hint(parent.getSize()).applyTo(textControl); } @Override public void bindModel(EMFDataBindingContext context) { bindNameControl(context); bindDomainCombo(context); bindSpecificationControl(context); bindDocumentationControl(context); orderElementControl.refreshInput(); } private void bindDomainCombo(EMFDataBindingContext context) { IEMFValueProperty property = EMFEditProperties.value(TransactionUtil.getEditingDomain(eObject), BasePackage.Literals.DOMAIN_ELEMENT__DOMAIN_ID); IViewerObservableValue observeSingleSelection = ViewersObservables.observeSingleSelection(domainCombo); UpdateValueStrategy modelToTarget = new UpdateValueStrategy() { @Override public Object convert(Object value) { return ((IDomain) value).getDomainID(); } }; UpdateValueStrategy targetToModel = new UpdateValueStrategy() { @Override public Object convert(Object value) { return DomainRegistry.getDomain((String) value); } }; context.bindValue(observeSingleSelection, property.observe(eObject), modelToTarget, targetToModel); } private void bindDocumentationControl(EMFDataBindingContext context) { IEMFValueProperty property = EMFEditProperties.value(TransactionUtil.getEditingDomain(eObject), BasePackage.Literals.DOCUMENTED_ELEMENT__DOCUMENTATION); ISWTObservableValue observe = WidgetProperties.text(new int[]{SWT.FocusOut, SWT.DefaultSelection}) .observe(documentation); context.bindValue(observe, property.observe(eObject)); } protected void bindSpecificationControl(EMFDataBindingContext context) { IEMFValueProperty modelProperty = EMFEditProperties.value(TransactionUtil.getEditingDomain(eObject), SGraphPackage.Literals.SPECIFICATION_ELEMENT__SPECIFICATION); ISWTObservableValue uiProperty = WidgetProperties.text(SWT.FocusOut).observe(textControl); context.bindValue(uiProperty, modelProperty.observe(eObject), null, new UpdateValueStrategy() { @Override protected IStatus doSet(IObservableValue observableValue, Object value) { if (getCompletionProposalAdapter() != null && !getCompletionProposalAdapter().isProposalPopupOpen()) return super.doSet(observableValue, value); return Status.OK_STATUS; } }); } protected void bindNameControl(EMFDataBindingContext context) { IEMFValueProperty property = EMFEditProperties.value(TransactionUtil.getEditingDomain(eObject), BasePackage.Literals.NAMED_ELEMENT__NAME); ISWTObservableValue observe = WidgetProperties.text(new int[]{SWT.FocusOut, SWT.DefaultSelection}) .observe(txtName); context.bindValue(observe, property.observe(eObject)); } @Override public EObject getEObject() { return super.getEObject(); } @Override public void dispose() { if (orderElementControl != null) { orderElementControl.dispose(); } super.dispose(); } }
plugins/org.yakindu.sct.ui.editor/src/org/yakindu/sct/ui/editor/propertysheets/StatechartPropertySection.java
/** * Copyright (c) 2011 committers of YAKINDU and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * Contributors: * committers of YAKINDU - initial API and implementation * */ package org.yakindu.sct.ui.editor.propertysheets; import java.util.List; import org.eclipse.core.databinding.UpdateValueStrategy; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.emf.databinding.EMFDataBindingContext; import org.eclipse.emf.databinding.IEMFValueProperty; import org.eclipse.emf.databinding.edit.EMFEditProperties; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.transaction.util.TransactionUtil; import org.eclipse.jface.databinding.swt.ISWTObservableValue; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.jface.databinding.viewers.IViewerObservableValue; import org.eclipse.jface.databinding.viewers.ViewersObservables; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.Text; import org.yakindu.base.base.BasePackage; import org.yakindu.sct.domain.extension.DomainRegistry; import org.yakindu.sct.domain.extension.IDomain; import org.yakindu.sct.model.sgraph.SGraphPackage; import org.yakindu.sct.model.sgraph.Statechart; import org.yakindu.sct.ui.editor.propertysheets.OrderElementControl.ISourceObjectCallback; import org.yakindu.sct.ui.editor.utils.HelpContextIds; import com.google.inject.Injector; /** * * @author andreas muelder - Initial contribution and API * */ public class StatechartPropertySection extends AbstractTwoColumnEditorPropertySection implements ISourceObjectCallback { private Control textControl; private Text txtName; private OrderElementControl orderElementControl; private Text documentation; private ComboViewer domainCombo; @Override protected Layout createLeftColumnLayout() { return new GridLayout(2, false); } @Override protected void createLeftColumnControls(Composite leftColumn) { createNameControl(leftColumn); createDomainCombo(leftColumn); createSpecificationControl(leftColumn); } protected void createDomainCombo(Composite leftColumn) { Label label = getToolkit().createLabel(leftColumn, "Statechart domain"); GridDataFactory.fillDefaults().span(2, 1).align(SWT.FILL, SWT.CENTER).applyTo(label); domainCombo = new ComboViewer(leftColumn); GridDataFactory.fillDefaults().span(1, 1).align(SWT.FILL, SWT.CENTER).applyTo(domainCombo.getCombo()); Label spacer = getToolkit().createLabel(leftColumn, ""); GridDataFactory.fillDefaults().applyTo(spacer); domainCombo.setContentProvider(new ArrayContentProvider()); domainCombo.setLabelProvider(new LabelProvider() { @Override public String getText(Object element) { return ((IDomain) element).getName(); } }); List<IDomain> domains = DomainRegistry.getDomains(); for (IDomain domainDescriptor : domains) { domainCombo.add(domainDescriptor); } if (domains.size() <= 1) { domainCombo.getControl().setVisible(false); } } @Override protected void createRightColumnControls(Composite rightColumn) { createDocumentationControl(rightColumn); createRegionsControl(rightColumn); } protected void createNameControl(Composite parent) { Label lblName = getToolkit().createLabel(parent, "Statechart Name: "); txtName = getToolkit().createText(parent, ""); GridDataFactory.fillDefaults().span(2, 1).applyTo(lblName); new Label(parent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).applyTo(txtName); } protected void createRegionsControl(Composite rightColumn) { Label label = getToolkit().createLabel(rightColumn, "Region Priority:"); GridDataFactory.fillDefaults().applyTo(label); orderElementControl = new OrderElementControl(rightColumn, SGraphPackage.Literals.COMPOSITE_ELEMENT__REGIONS, this, "Statechart contains no regions"); GridDataFactory.fillDefaults().span(2, 0).grab(true, false).applyTo(orderElementControl); } protected void createDocumentationControl(Composite parent) { Label lblDocumentation = getToolkit().createLabel(parent, "Documentation: "); documentation = getToolkit().createText(parent, "", SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.WRAP); GridDataFactory.fillDefaults().applyTo(lblDocumentation); GridDataFactory.fillDefaults().grab(true, true).hint(parent.getSize()).applyTo(documentation); } protected void createSpecificationControl(final Composite parent) { Label lblDocumentation = getToolkit().createLabel(parent, "Statechart Behavior: "); Injector injector = getInjector(Statechart.class.getName()); if (injector != null) { textControl = new StyledText(parent, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.WRAP); ((StyledText) textControl).setAlwaysShowScrollBars(false); enableXtext(textControl, injector); createHelpWidget(parent, textControl, HelpContextIds.SC_PROPERTIES_STATECHART_EXPRESSION); } else { textControl = getToolkit().createText(parent, "", SWT.MULTI); } GridDataFactory.fillDefaults().span(2, 1).applyTo(lblDocumentation); GridDataFactory.fillDefaults().grab(true, true).hint(parent.getSize()).applyTo(textControl); } @Override public void bindModel(EMFDataBindingContext context) { bindNameControl(context); bindDomainCombo(context); bindSpecificationControl(context); bindDocumentationControl(context); orderElementControl.refreshInput(); } private void bindDomainCombo(EMFDataBindingContext context) { IEMFValueProperty property = EMFEditProperties.value(TransactionUtil.getEditingDomain(eObject), BasePackage.Literals.DOMAIN_ELEMENT__DOMAIN_ID); IViewerObservableValue observeSingleSelection = ViewersObservables.observeSingleSelection(domainCombo); UpdateValueStrategy modelToTarget = new UpdateValueStrategy() { @Override public Object convert(Object value) { return ((IDomain) value).getDomainID(); } }; UpdateValueStrategy targetToModel = new UpdateValueStrategy() { @Override public Object convert(Object value) { return DomainRegistry.getDomain((String) value); } }; context.bindValue(observeSingleSelection, property.observe(eObject), modelToTarget, targetToModel); } private void bindDocumentationControl(EMFDataBindingContext context) { IEMFValueProperty property = EMFEditProperties.value(TransactionUtil.getEditingDomain(eObject), BasePackage.Literals.DOCUMENTED_ELEMENT__DOCUMENTATION); ISWTObservableValue observe = WidgetProperties.text(new int[]{SWT.FocusOut, SWT.DefaultSelection}) .observe(documentation); context.bindValue(observe, property.observe(eObject)); } protected void bindSpecificationControl(EMFDataBindingContext context) { IEMFValueProperty modelProperty = EMFEditProperties.value(TransactionUtil.getEditingDomain(eObject), SGraphPackage.Literals.SPECIFICATION_ELEMENT__SPECIFICATION); ISWTObservableValue uiProperty = WidgetProperties.text(SWT.FocusOut).observe(textControl); context.bindValue(uiProperty, modelProperty.observe(eObject), null, new UpdateValueStrategy() { @Override protected IStatus doSet(IObservableValue observableValue, Object value) { if (getCompletionProposalAdapter() != null && !getCompletionProposalAdapter().isProposalPopupOpen()) return super.doSet(observableValue, value); return Status.OK_STATUS; } }); } protected void bindNameControl(EMFDataBindingContext context) { IEMFValueProperty property = EMFEditProperties.value(TransactionUtil.getEditingDomain(eObject), BasePackage.Literals.NAMED_ELEMENT__NAME); ISWTObservableValue observe = WidgetProperties.text(new int[]{SWT.FocusOut, SWT.DefaultSelection}) .observe(txtName); context.bindValue(observe, property.observe(eObject)); } @Override public EObject getEObject() { return super.getEObject(); } @Override public void dispose() { if (orderElementControl != null) { orderElementControl.dispose(); } super.dispose(); } }
#1042 : disbale domain label if just one domain is available (#1058) * #1042 : hide domain label if just one domain is available * #1042 : disable domain combo instead of hide it
plugins/org.yakindu.sct.ui.editor/src/org/yakindu/sct/ui/editor/propertysheets/StatechartPropertySection.java
#1042 : disbale domain label if just one domain is available (#1058)
Java
agpl-3.0
5ab7636e461d22db1f39158f8de46e89923471c0
0
Treeptik/cloudunit,Treeptik/cloudunit,Treeptik/cloudunit,Treeptik/cloudunit,Treeptik/cloudunit,Treeptik/cloudunit
/* * LICENCE : CloudUnit is available under the Affero Gnu Public License GPL V3 : https://www.gnu.org/licenses/agpl-3.0.html * but CloudUnit is licensed too under a standard commercial license. * Please contact our sales team if you would like to discuss the specifics of our Enterprise license. * If you are not sure whether the GPL is right for you, * you can always test our software under the GPL and inspect the source code before you contact us * about purchasing a commercial license. * * LEGAL TERMS : "CloudUnit" is a registered trademark of Treeptik and can't be used to endorse * or promote products derived from this project without prior written permission from Treeptik. * Products or services derived from this software may not be called "CloudUnit" * nor may "Treeptik" or similar confusing terms appear in their names without prior written permission. * For any questions, contact us : [email protected] */ package fr.treeptik.cloudunit.servers; import fr.treeptik.cloudunit.exception.ServiceException; import fr.treeptik.cloudunit.initializer.CloudUnitApplicationContext; import fr.treeptik.cloudunit.model.User; import fr.treeptik.cloudunit.service.UserService; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpSession; import org.springframework.mock.web.MockServletContext; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import javax.inject.Inject; import javax.servlet.Filter; import java.util.Random; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Created by nicolas on 08/09/15. */ @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = {CloudUnitApplicationContext.class, MockServletContext.class}) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @ActiveProfiles("integration") public abstract class AbstractApplicationControllerTestIT { protected String release; private final Logger logger = LoggerFactory.getLogger(AbstractApplicationControllerTestIT.class); @Autowired private WebApplicationContext context; private MockMvc mockMvc; @Inject private AuthenticationManager authenticationManager; @Autowired private Filter springSecurityFilterChain; @Inject private UserService userService; private Authentication authentication; private MockHttpSession session; private static String applicationName; @BeforeClass public static void initEnv() { applicationName = "App" + new Random().nextInt(1000); } @Before public void setup() { logger.info("setup"); this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); User user = null; try { user = userService.findByLogin("johndoe"); } catch (ServiceException e) { logger.error(e.getLocalizedMessage()); } Authentication authentication = new UsernamePasswordAuthenticationToken(user.getLogin(), user.getPassword()); Authentication result = authenticationManager.authenticate(authentication); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(result); session = new MockHttpSession(); session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext); } @Test public void test010_CreateApplication() throws Exception { logger.info("Create Tomcat server"); final String jsonString = "{\"applicationName\":\"" + applicationName + "\", \"serverName\":\"" + release + "\"}"; ResultActions resultats = mockMvc.perform(post("/application").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); resultats = mockMvc.perform(get("/application/" + applicationName).session(session).contentType(MediaType.APPLICATION_JSON)); resultats.andExpect(jsonPath("name").value(applicationName.toLowerCase())); } @After public void teardown() { logger.info("teardown"); SecurityContextHolder.clearContext(); session.invalidate(); } /** * We cannot create an application with an empty name. * * @throws Exception */ @Test public void test011_FailCreateEmptyNameApplication() throws Exception { logger.info("Create application with an empty name"); final String jsonString = "{\"applicationName\":\"" + "" + "\", \"serverName\":\"" + release + "\"}"; ResultActions resultats = this.mockMvc.perform(post("/application") .session(session) .contentType(MediaType.APPLICATION_JSON) .content(jsonString)); resultats.andExpect(status().is4xxClientError()); } /** * We cannot create an application with an wrong syntax name. * * @throws Exception */ @Test(timeout = 30000) public void test012_FailCreateWrongNameApplication() throws Exception { logger.info("Create application with a wrong syntax name"); final String jsonString = "{\"applicationName\":\"" + "WRONG-NAME" + "\", \"serverName\":\"" + release + "\"}"; ResultActions resultats = this.mockMvc.perform(post("/application").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().is4xxClientError()); } @Test(timeout = 30000) public void test013_CreateAccentNameApplication() throws Exception { String accentName = "àéèîôù"; String deAccentName = "aeeiou"; logger.info("**************************************"); logger.info("Create application with accent name " + accentName); logger.info("**************************************"); final String jsonString = "{\"applicationName\":\"" + accentName + "\", \"serverName\":\"" + release + "\"}"; ResultActions resultats = this.mockMvc.perform(post("/application").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); logger.info("**************************************"); logger.info("Delete application : " + deAccentName); logger.info("**************************************"); resultats = mockMvc.perform(delete("/application/" + deAccentName).session(session).contentType(MediaType.APPLICATION_JSON)); resultats.andExpect(status().isOk()); } @Test(timeout = 30000) public void test020_StopApplicationTest() throws Exception { logger.info("Stop the application : " + applicationName); final String jsonString = "{\"applicationName\":\"" + applicationName + "\"}"; ResultActions resultats = this.mockMvc.perform(post("/application/stop").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); } @Test(timeout = 30000) public void test021_StopApplicationTestFailsBecauseAlreadyStopped() throws Exception { logger.info("Stop the application : " + applicationName); final String jsonString = "{\"applicationName\":\"" + applicationName + "\"}"; ResultActions resultats = this.mockMvc.perform(post("/application/stop").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); } @Test() public void test030_StartApplicationTest() throws Exception { logger.info("Start the application : " + applicationName); final String jsonString = "{\"applicationName\":\"" + applicationName + "\"}"; ResultActions resultats = this.mockMvc.perform(post("/application/start").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); } @Test() public void test040_ChangeJvmMemorySizeApplicationTest() throws Exception { logger.info("Change JVM Memory !"); final String jsonString = "{\"applicationName\":\"" + applicationName + "\",\"jvmMemory\":\"512\",\"jvmOptions\":\"\",\"jvmRelease\":\"jdk1.8.0_25\",\"location\":\"webui\"}"; ResultActions resultats = this.mockMvc.perform(put("/server/configuration/jvm").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); } @Test(timeout = 30000) public void test041_ChangeInvalidJvmMemorySizeApplicationTest() throws Exception { logger.info("Change JVM Memory size with an incorrect value : number not allowed"); final String jsonString = "{\"applicationName\":\"" + applicationName + "\",\"jvmMemory\":\"666\",\"jvmOptions\":\"\",\"jvmRelease\":\"\"}"; ResultActions resultats = mockMvc.perform(put("/server/configuration/jvm").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().is4xxClientError()); } @Test(timeout = 30000) public void test043_ChangeEmptyJvmMemorySizeApplicationTest() throws Exception { logger.info("Change JVM Memory size with an empty value"); final String jsonString = "{\"applicationName\":\"" + applicationName + "\",\"jvmMemory\":\"\",\"jvmOptions\":\"\",\"jvmRelease\":\"jdk1.8.0_25\"}"; ResultActions resultats = mockMvc.perform(put("/server/configuration/jvm").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().is4xxClientError()); } @Test(timeout = 60000) public void test050_ChangeJvmOptionsApplicationTest() throws Exception { logger.info("Change JVM Options !"); final String jsonString = "{\"applicationName\":\"" + applicationName + "\",\"jvmMemory\":\"512\",\"jvmOptions\":\"-Dkey1=value1\",\"jvmRelease\":\"jdk1.8.0_25\"}"; ResultActions resultats = mockMvc.perform(put("/server/configuration/jvm").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); resultats = mockMvc.perform(get("/application/" + applicationName).session(session).contentType(MediaType.APPLICATION_JSON)); resultats.andExpect(jsonPath("$.servers[0].jvmMemory").value(512)).andExpect(jsonPath( "$.servers[0].jvmRelease").value("jdk1.8.0_25")).andExpect(jsonPath( "$.servers[0].jvmOptions").value("-Dkey1=value1")); } @Test(timeout = 30000) public void test051_ChangeFailWithXmsJvmOptionsApplicationTest() throws Exception { logger.info("Change JVM With Xms : not allowed"); final String jsonString = "{\"applicationName\":\"" + applicationName + "\",\"jvmMemory\":\"512\",\"jvmOptions\":\"-Xms=512m\",\"jvmRelease\":\"jdk1.8.0_25\"}"; ResultActions resultats = mockMvc.perform(put("/server/configuration/jvm").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().is4xxClientError()); } @Test() public void test050_OpenAPort() throws Exception { logger.info("Open custom ports !"); final String jsonString = "{\"applicationName\":\"" + applicationName + "\",\"portToOpen\":\"6115\",\"alias\":\"access6115\"}"; ResultActions resultats = this.mockMvc.perform(post("/server/ports/open").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); } @Test() public void test051_CloseAPort() throws Exception { logger.info("Open custom ports !"); final String jsonString = "{\"applicationName\":\"" + applicationName + "\",\"portToOpen\":\"6115\",\"alias\":\"access6115\"}"; ResultActions resultats = this.mockMvc.perform(post("/server/ports/close").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); } @Test(timeout = 30000) public void test09_DeleteApplication() throws Exception { logger.info("Delete application : " + applicationName); ResultActions resultats = mockMvc.perform(delete("/application/" + applicationName).session(session).contentType(MediaType.APPLICATION_JSON)); resultats.andExpect(status().isOk()); } }
cu-manager/src/test/java/fr/treeptik/cloudunit/servers/AbstractApplicationControllerTestIT.java
/* * LICENCE : CloudUnit is available under the Affero Gnu Public License GPL V3 : https://www.gnu.org/licenses/agpl-3.0.html * but CloudUnit is licensed too under a standard commercial license. * Please contact our sales team if you would like to discuss the specifics of our Enterprise license. * If you are not sure whether the GPL is right for you, * you can always test our software under the GPL and inspect the source code before you contact us * about purchasing a commercial license. * * LEGAL TERMS : "CloudUnit" is a registered trademark of Treeptik and can't be used to endorse * or promote products derived from this project without prior written permission from Treeptik. * Products or services derived from this software may not be called "CloudUnit" * nor may "Treeptik" or similar confusing terms appear in their names without prior written permission. * For any questions, contact us : [email protected] */ package fr.treeptik.cloudunit.servers; import fr.treeptik.cloudunit.exception.ServiceException; import fr.treeptik.cloudunit.initializer.CloudUnitApplicationContext; import fr.treeptik.cloudunit.model.User; import fr.treeptik.cloudunit.service.UserService; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpSession; import org.springframework.mock.web.MockServletContext; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import javax.inject.Inject; import javax.servlet.Filter; import java.util.Random; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Created by nicolas on 08/09/15. */ @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = {CloudUnitApplicationContext.class, MockServletContext.class}) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @ActiveProfiles("integration") public abstract class AbstractApplicationControllerTestIT { protected String release; private final Logger logger = LoggerFactory.getLogger(AbstractApplicationControllerTestIT.class); @Autowired private WebApplicationContext context; private MockMvc mockMvc; @Inject private AuthenticationManager authenticationManager; @Autowired private Filter springSecurityFilterChain; @Inject private UserService userService; private Authentication authentication; private MockHttpSession session; private static String applicationName; @BeforeClass public static void initEnv() { applicationName = "App" + new Random().nextInt(1000); } @Before public void setup() { logger.info("setup"); this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); User user = null; try { user = userService.findByLogin("johndoe"); } catch (ServiceException e) { logger.error(e.getLocalizedMessage()); } Authentication authentication = new UsernamePasswordAuthenticationToken(user.getLogin(), user.getPassword()); Authentication result = authenticationManager.authenticate(authentication); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(result); session = new MockHttpSession(); session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext); } @Test public void test010_CreateApplication() throws Exception { logger.info("Create Tomcat server"); final String jsonString = "{\"applicationName\":\"" + applicationName + "\", \"serverName\":\"" + release + "\"}"; ResultActions resultats = mockMvc.perform(post("/application").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); resultats = mockMvc.perform(get("/application/" + applicationName).session(session).contentType(MediaType.APPLICATION_JSON)); resultats.andExpect(jsonPath("name").value(applicationName.toLowerCase())); } @After public void teardown() { logger.info("teardown"); SecurityContextHolder.clearContext(); session.invalidate(); } /** * We cannot create an application with an empty name. * * @throws Exception */ @Test public void test011_FailCreateEmptyNameApplication() throws Exception { logger.info("Create application with an empty name"); final String jsonString = "{\"applicationName\":\"" + "" + "\", \"serverName\":\"" + release + "\"}"; ResultActions resultats = this.mockMvc.perform(post("/application") .session(session) .contentType(MediaType.APPLICATION_JSON) .content(jsonString)); resultats.andExpect(status().is4xxClientError()); } /** * We cannot create an application with an wrong syntax name. * * @throws Exception */ @Test(timeout = 30000) public void test012_FailCreateWrongNameApplication() throws Exception { logger.info("Create application with a wrong syntax name"); final String jsonString = "{\"applicationName\":\"" + "WRONG-NAME" + "\", \"serverName\":\"" + release + "\"}"; ResultActions resultats = this.mockMvc.perform(post("/application").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().is4xxClientError()); } @Test(timeout = 30000) public void test013_CreateAccentNameApplication() throws Exception { String accentName = "àéèîôù"; String deAccentName = "aeeiou"; logger.info("**************************************"); logger.info("Create application with accent name " + accentName); logger.info("**************************************"); final String jsonString = "{\"applicationName\":\"" + accentName + "\", \"serverName\":\"" + release + "\"}"; ResultActions resultats = this.mockMvc.perform(post("/application").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); logger.info("**************************************"); logger.info("List the applications"); logger.info("**************************************"); resultats = mockMvc.perform(get("/application").session(session)).andDo(print()); resultats.andExpect(status().isOk()).andExpect(jsonPath("$[0].name").value(deAccentName.toLowerCase())); logger.info("**************************************"); logger.info("Delete application : " + deAccentName); logger.info("**************************************"); resultats = mockMvc.perform(delete("/application/" + deAccentName).session(session).contentType(MediaType.APPLICATION_JSON)); resultats.andExpect(status().isOk()); } @Test(timeout = 30000) public void test020_StopApplicationTest() throws Exception { logger.info("Stop the application : " + applicationName); final String jsonString = "{\"applicationName\":\"" + applicationName + "\"}"; ResultActions resultats = this.mockMvc.perform(post("/application/stop").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); } @Test(timeout = 30000) public void test021_StopApplicationTestFailsBecauseAlreadyStopped() throws Exception { logger.info("Stop the application : " + applicationName); final String jsonString = "{\"applicationName\":\"" + applicationName + "\"}"; ResultActions resultats = this.mockMvc.perform(post("/application/stop").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); } @Test() public void test030_StartApplicationTest() throws Exception { logger.info("Start the application : " + applicationName); final String jsonString = "{\"applicationName\":\"" + applicationName + "\"}"; ResultActions resultats = this.mockMvc.perform(post("/application/start").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); } @Test() public void test040_ChangeJvmMemorySizeApplicationTest() throws Exception { logger.info("Change JVM Memory !"); final String jsonString = "{\"applicationName\":\"" + applicationName + "\",\"jvmMemory\":\"512\",\"jvmOptions\":\"\",\"jvmRelease\":\"jdk1.8.0_25\",\"location\":\"webui\"}"; ResultActions resultats = this.mockMvc.perform(put("/server/configuration/jvm").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); } @Test(timeout = 30000) public void test041_ChangeInvalidJvmMemorySizeApplicationTest() throws Exception { logger.info("Change JVM Memory size with an incorrect value : number not allowed"); final String jsonString = "{\"applicationName\":\"" + applicationName + "\",\"jvmMemory\":\"666\",\"jvmOptions\":\"\",\"jvmRelease\":\"\"}"; ResultActions resultats = mockMvc.perform(put("/server/configuration/jvm").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().is4xxClientError()); } @Test(timeout = 30000) public void test043_ChangeEmptyJvmMemorySizeApplicationTest() throws Exception { logger.info("Change JVM Memory size with an empty value"); final String jsonString = "{\"applicationName\":\"" + applicationName + "\",\"jvmMemory\":\"\",\"jvmOptions\":\"\",\"jvmRelease\":\"jdk1.8.0_25\"}"; ResultActions resultats = mockMvc.perform(put("/server/configuration/jvm").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().is4xxClientError()); } @Test(timeout = 60000) public void test050_ChangeJvmOptionsApplicationTest() throws Exception { logger.info("Change JVM Options !"); final String jsonString = "{\"applicationName\":\"" + applicationName + "\",\"jvmMemory\":\"512\",\"jvmOptions\":\"-Dkey1=value1\",\"jvmRelease\":\"jdk1.8.0_25\"}"; ResultActions resultats = mockMvc.perform(put("/server/configuration/jvm").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); resultats = mockMvc.perform(get("/application/" + applicationName).session(session).contentType(MediaType.APPLICATION_JSON)); resultats.andExpect(jsonPath("$.servers[0].jvmMemory").value(512)).andExpect(jsonPath( "$.servers[0].jvmRelease").value("jdk1.8.0_25")).andExpect(jsonPath( "$.servers[0].jvmOptions").value("-Dkey1=value1")); } @Test(timeout = 30000) public void test051_ChangeFailWithXmsJvmOptionsApplicationTest() throws Exception { logger.info("Change JVM With Xms : not allowed"); final String jsonString = "{\"applicationName\":\"" + applicationName + "\",\"jvmMemory\":\"512\",\"jvmOptions\":\"-Xms=512m\",\"jvmRelease\":\"jdk1.8.0_25\"}"; ResultActions resultats = mockMvc.perform(put("/server/configuration/jvm").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().is4xxClientError()); } @Test() public void test050_OpenAPort() throws Exception { logger.info("Open custom ports !"); final String jsonString = "{\"applicationName\":\"" + applicationName + "\",\"portToOpen\":\"6115\",\"alias\":\"access6115\"}"; ResultActions resultats = this.mockMvc.perform(post("/server/ports/open").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); } @Test() public void test051_CloseAPort() throws Exception { logger.info("Open custom ports !"); final String jsonString = "{\"applicationName\":\"" + applicationName + "\",\"portToOpen\":\"6115\",\"alias\":\"access6115\"}"; ResultActions resultats = this.mockMvc.perform(post("/server/ports/close").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString)); resultats.andExpect(status().isOk()); } @Test(timeout = 30000) public void test09_DeleteApplication() throws Exception { logger.info("Delete application : " + applicationName); ResultActions resultats = mockMvc.perform(delete("/application/" + applicationName).session(session).contentType(MediaType.APPLICATION_JSON)); resultats.andExpect(status().isOk()); } }
FIX - TEST application with accent name
cu-manager/src/test/java/fr/treeptik/cloudunit/servers/AbstractApplicationControllerTestIT.java
FIX - TEST application with accent name
Java
agpl-3.0
520dee49e84d88fb78ce22b17accf0722e474259
0
ua-eas/kfs-devops-automation-fork,ua-eas/kfs,kkronenb/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,kuali/kfs,smith750/kfs,kkronenb/kfs,ua-eas/kfs,bhutchinson/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork,bhutchinson/kfs,kuali/kfs,ua-eas/kfs,kkronenb/kfs,smith750/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,smith750/kfs,kuali/kfs,UniversityOfHawaii/kfs,UniversityOfHawaii/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,kuali/kfs,kuali/kfs,kkronenb/kfs,smith750/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials
/* * Copyright 2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.module.cam; /** * Holds error key constants. */ public class CamsKeyConstants { public static final String CONTINUE_QUESTION = "document.question.continue.text"; public static final String ERROR_INVALID_BUILDING_CODE = "error.invalid.building.code"; public static final String ERROR_INVALID_ROOM_NUMBER = "error.invalid.room.number"; public static final String ERROR_NO_DETAIL_LINE = "error.invalid.no.detail.line"; public static final String ERROR_INVALID_IN_SERVICE_DATE = "error.invalid.in.service.date"; public static final String MESSAGE_BATCH_UPLOAD_TITLE_PRE_ASSET_TAGGING = "message.batchUpload.title.pre.asset.tagging"; public static final String ERROR_INVALID_ASSET_WARRANTY_NO = "error.invalid.asset.warranty.no"; public static final String ERROR_CAPITAL_ASSET_VENDOR_NAME_REQUIRED = "error.capital.asset.vendor.name.required"; public static final String ERROR_TAG_NUMBER_DUPLICATE = "error.tag.number.duplicate"; public static final String ERROR_ASSET_RETIRED_CAPITAL = "error.asset.retired.capital"; public static final String ERROR_ASSET_RETIRED_NON_CAPITAL_ACTIVE = "error.asset.retired.non.capital.active"; public static final String ERROR_ASSET_RETIRED_ACT_NON_CAPITAL_2003 = "error.asset.retired.act.non.capital.2003"; public static final String ERROR_FABRICATION_ESTIMATED_TOTAL_AMOUNT_REQUIRED = "error.asset.fabrication.totalAmount.required"; public static final String ERROR_ESTIMATED_FABRICATION_COMPLETION_DATE_REQUIRED = "error.asset.fabrication.completionDate.required"; public static final String ERROR_ESTIMATED_FABRICATION_LIFE_LIMIT_REQUIRED = "error.asset.fabrication.lifeLimit.required"; public static final String ERROR_FABRICATION_ESTIMATED_TOTAL_AMOUNT_NEGATIVE = "error.asset.fabrication.totalAmount.negative"; public static final String ERROR_ESTIMATED_FABRICATION_LIFE_LIMIT_NEGATIVE = "error.asset.fabrication.lifeLimit.negative"; public static final String ORGANIZATION_OWNER_ACCOUNT_INACTIVE = "error.asset.org.owner.account.inactive"; public static final String ERROR_ESTIMATED_FABRICATION_COMPLETION_DATE_PAST = "error.asset.fabrication.completionDate.past"; public static class Depreciation { public static final String NO_ELIGIBLE_FOR_DEPRECIATION_ASSETS_FOUND = "error.batch.depreciation.assetsNotFound"; public static final String ERROR_WHEN_CALCULATING_BASE_AMOUNT = "error.batch.depreciation.baseAmountCalculationError"; public static final String ERROR_WHEN_CALCULATING_DEPRECIATION = "error.batch.depreciation.calculationError"; public static final String ERROR_WHEN_UPDATING_GL_PENDING_ENTRY_TABLE = "error.batch.depreciation.glpeUpdateError"; public static final String DEPRECIATION_DATE_PARAMETER_NOT_FOUND = "error.batch.depreciation.depreciationDateNotFound"; public static final String INVALID_DEPRECIATION_DATE_FORMAT = "error.batch.depreciation.invalidDepreciationDateFormat"; public static final String DEPRECIATION_ALREADY_RAN_MSG = "error.batch.depreciation.alreadyRan"; public static final String MSG_REPORT_DEPRECIATION_HEADING1 = "message.batch.report.depreciation.heading.description"; public static final String MSG_REPORT_DEPRECIATION_HEADING2 = "message.batch.report.depreciation.heading.figures"; } public static class Payment { public static final String ERROR_INVALID_DOC_POST_DATE = "error.payment.invalid.document.postdate"; public static final String ERROR_INVALID_OBJECT_SUBTYPE = "error.asset.payment.invalidObjectSubtypeCode"; public static final String WARNING_NOT_SAME_OBJECT_SUB_TYPES = "warning.payment.object.subtype.not_the_same"; public static final String ERROR_NON_CAPITAL_ASSET = "error.non.capital.asset.payment"; public static final String ERROR_ASSET_EXISTS_IN_DOCUMENT = "error.asset.exists.in.payment.document"; public static final String ERROR_NON_ASSETS_IN_DOCUMENT = "error.payment.document.noAssetsInDocumentFound"; public static final String ERROR_NON_ZERO_COST_ASSETS_ALLOWED = "error.payment.document.noZeroValueAssetsAllowed"; public static final String ERROR_POSTING_DATE_FUTURE_NOT_ALLOWED = "error.posting.date.future.notallowed"; } public static class Transfer { public static final String ERROR_ASSET_RETIRED_NOTRANSFER = "error.asset.retired.notransfer"; public static final String ERROR_CAMPUS_PLANT_FUND_UNKNOWN = "error.campus.plant.fund.unknown"; public static final String ERROR_ORG_PLANT_FUND_UNKNOWN = "error.org.plant.fund.unknown"; public static final String ERROR_OWNER_ACCT_NOT_ACTIVE = "error.account.notactive"; public static final String ERROR_OWNER_CHART_CODE_INVALID = "error.receiving.org.chart.code.invalid"; public static final String ERROR_OWNER_ACCT_INVALID = "error.receiving.org.acct.invalid"; public static final String ERROR_TRFR_FDOC_INVALID = "error.transfer.fund.financial.doc.invalid"; public static final String ERROR_TRFR_FDOC_REQUIRED = "error.transfer.fund.financial.doc.required"; public static final String ERROR_TRFR_LOANED = "error.transfer.asset.loaned"; public static final String ASSET_LOAN_NOTE = "note.asset.loan.active"; public static final String ERROR_INVALID_USER_AUTH_ID = "error.representative.user.invalid"; public static final String ERROR_PAYMENT_OBJECT_CODE_NOT_FOUND = "error.transfer.document.payment.objectcode.doesnt.exists"; public static final String ERROR_INVALID_USER_GROUP_FOR_TRANSFER_NONMOVABLE_ASSET = "error.invalid.user.group.for.transfer.nonmoveable.asset"; public static final String MESSAGE_NO_LEDGER_ENTRY_REQUIRED_TRANSFER = "message.no.ledger.entry.required.transfer"; } public static class GLPosting { public static final String ERROR_ASSET_OBJECT_CODE_NOT_FOUND = "error.asset.object.code.not.found"; public static final String ERROR_ASSET_OBJECT_CODE_INACTIVE = "error.asset.object.code.inactive"; public static final String ERROR_OBJECT_CODE_FROM_ASSET_OBJECT_CODE_NOT_FOUND = "error.object.code.from.asset.object.code.not.found"; public static final String ERROR_OBJECT_CODE_FROM_ASSET_OBJECT_CODE_INACTIVE = "error.object.code.from.asset.object.code.inactive"; public static final String ERROR_OBJECT_CODE_FROM_ASSET_OBJECT_CODE_INVALID = "error.object.code.from.asset.object.code.invalid"; } public static class AssetLocation { public static final String ERROR_INVALID_BUILDING_CODE = "error.invalid.building.code"; public static final String ERROR_INVALID_CAMPUS_CODE = "error.invalid.campus.code"; public static final String ERROR_INVALID_ROOM_NUMBER = "error.invalid.room.code"; public static final String ERROR_INVALID_OFF_CAMPUS_STATE = "error.invalid.state.code"; public static final String ERROR_INVALID_STATE_ZIP_CODE = "error.invalid.state.zip.code"; public static final String ERROR_INVALID_ZIP_CODE = "error.invalid.zip.code"; public static final String ERROR_LOCATION_INFO_REQUIRED = "error.location.info.required"; public static final String ERROR_ONCAMPUS_BUILDING_CODE_REQUIRED = "error.oncampus.building.value.required"; public static final String ERROR_ONCAMPUS_BUILDING_ROOM_NUMBER_REQUIRED = "error.oncampus.room.number.required"; public static final String ERROR_OFFCAMPUS_ADDRESS_REQUIRED = "error.offcampus.address.required"; public static final String ERROR_OFFCAMPUS_CITY_REQUIRED = "error.offcampus.city.required"; public static final String ERROR_OFFCAMPUS_STATE_REQUIRED = "error.offcampus.state.required"; public static final String ERROR_OFFCAMPUS_ZIP_REQUIRED = "error.offcampus.zip.required"; public static final String ERROR_OFFCAMPUS_CONTACT_REQUIRED = "error.offcampus.contactName.required"; public static final String ERROR_OFFCAMPUS_COUNTRY_REQUIRED = "error.offcampus.country.required"; public static final String ERROR_CHOOSE_LOCATION_INFO = "error.location.choose.right"; public static final String ERROR_LOCATION_OFF_CAMPUS_NOT_PERMITTED = "error.location.offcampus.not.permitted"; public static final String ERROR_LOCATION_ON_CAMPUS_NOT_PERMITTED = "error.location.oncampus.not.permitted"; public static final String ERROR_ONCAMPUS_BUILDING_ROOM_NUMBER_NOT_PERMITTED = "error.oncampus.room.number.not.permitted"; public static final String ERROR_ONCAMPUS_SUB_ROOM_NUMBER_NOT_PERMITTED = "error.oncampus.sub.room.number.not.permitted"; public static final String ERROR_CHOOSE_ASSET_TYPE = "error.choose.asset.type.validate.location"; public static final String ERROR_LOCATION_NOT_PERMITTED_ASSET_TYPE = "error.location.not.permitted.asset.type"; } public static class Retirement { public static final String ERROR_RETIREMENT_DETAIL_INFO_NULL = "error.retirement.detail.info.null"; public static final String ERROR_INVALID_RETIREMENT_DETAIL_INFO = "error.invalid.retirement.detail.info"; public static final String ERROR_INVALID_MERGED_TARGET_ASSET_NUMBER = "error.invalid.merged.target.asset.number"; public static final String ERROR_NON_CAPITAL_ASSET_RETIREMENT = "error.non.capital.asset.retirment"; public static final String ERROR_NON_ACTIVE_ASSET_RETIREMENT = "error.non.active.asset.retirment"; public static final String ERROR_INVALID_CAPITAL_ASSET_NUMBER = "error.invalid.capital.asset.number"; public static final String ERROR_DUPLICATE_CAPITAL_ASSET_NUMBER_WITH_TARGET = "error.duplicate.capital.asset.number.with.target"; public static final String ERROR_INVALID_USER_GROUP_FOR_NON_MOVEABLE_ASSET = "error.invalid.user.group.for.nonmoveable.asset"; public static final String ERROR_BLANK_CAPITAL_ASSET_NUMBER = "error.blank.capital.asset.number"; public static final String ERROR_ASSET_RETIREMENT_GLOBAL_NO_ASSET = "error.asset.retirement.global.no.asset"; public static final String ERROR_DISALLOWED_MERGE_RETIREMENT_REASON_CODE = "error.disallowed.merge.retirement.reason.code"; public static final String ERROR_DISALLOWED_RETIREMENT_REASON_CODE = "error.disallowed.retirement.reason.code"; public static final String ERROR_DISALLOWED_MERGE_SEPARATE_REASON_CODE = "error.disallowed.merge.separate.reason.code"; public static final String ERROR_DISALLOWED_RAZE_REASON_CODE = "error.disallowed.raze.reason.code"; public static final String ERROR_MULTIPLE_ASSET_RETIRED = "error.multiple.asset.retired"; public static final String ERROR_LOANED_ASSET_CANNOT_RETIRED = "error.retirement.asset.loaned"; public static final String MESSAGE_NO_LEDGER_ENTRY_REQUIRED_RETIREMENT = "message.no.ledger.entry.required.retirement"; } public static class AssetLocationGlobal { public static final String ERROR_INVALID_CAPITAL_ASSET_NUMBER = "error.asset.location.invalid.capital.asset.number"; public static final String ERROR_INVALID_CAMPUS_CODE = "error.asset.location.invalid.campus.code"; public static final String ERROR_INVALID_BUILDING_CODE = "error.asset.location.invalid.building.code"; public static final String ERROR_INVALID_ROOM_NUMBER = "error.asset.location.invalid.room.code"; public static final String ERROR_TAG_NUMBER_REQUIRED = "error.asset.location.tag.number.required"; public static final String ERROR_DUPLICATE_TAG_NUMBER_FOUND = "error.asset.location.duplicate.tag.number"; public static final String ERROR_DUPLICATE_TAG_NUMBER_WITHIN_DOCUMENT = "error.asset.location.duplicate.tag.within.document"; public static final String ERROR_ASSET_LOCATION_GLOBAL_NO_ASSET_DETAIL = "error.asset.location.no.asset.location.detail.line"; public static final String ERROR_CAMPUS_CODE_REQUIRED = "error.asset.location.campus.code.required"; public static final String ERROR_BUILDING_CODE_REQUIRED = "error.asset.location.building.code.required"; public static final String ERROR_ROOM_NUMBER_REQUIRED = "error.asset.location.room.number.required"; public static final String ERROR_ASSET_AUTHORIZATION = "error.asset.authorization"; } public static class BarcodeInventory { public static final String TITLE_BAR_CODE_INVENTORY = "message.upload.title.barCodeInventory"; public static final String ERROR_INVALID_FIELD = "error.document.invalid.field"; public static final String ERROR_CAPITAL_ASSET_DOESNT_EXIST = "error.document.capitalAsset.not.found"; public static final String ERROR_CAPITAL_ASSET_IS_RETIRED = "error.document.capitalAsset.retired"; public static final String ERROR_DUPLICATED_TAG_NUMBER = "error.document.duplicated.tagNumber"; public static final String ERROR_ASSET_LOCKED = "error.document.locked.asset"; public static final String ERROR_INVALID_FILE_TYPE = "error.uploadFile.invalid.type"; public static final String ERROR_INACTIVE_FIELD = "error.document.inactive.field"; public static final String ERROR_APPROVE_DOCUMENT_WITH_ERROR_EXIST = "error.approve.document.with.error.exist"; public static final String ERROR_RECORDS_NO_SELECTED = "error.document.records_no_selected"; public static final String ERROR_CHECKBOX_MUST_BE_CHECKED = "error.checkbox.must.be.checked"; public static final String ERROR_GLOBAL_REPLACE_SEARCH_CRITERIA = "error.global.replace.empty.fields"; } public static class EquipmentLoanOrReturn { public static final String ERROR_INVALID_BORROWER_ID = "error.invalid.borrower.id"; public static final String ERROR_INVALID_LOAN_DATE = "error.invalid.loan.date"; public static final String ERROR_INVALID_EXPECTED_RETURN_DATE = "error.invalid.expected.return.date"; public static final String ERROR_INVALID_EXPECTED_MAX_DATE = "error.invalid.expected.max.date"; public static final String ERROR_INVALID_LOAN_RETURN_DATE = "error.invalid.loan.return.date"; public static final String ERROR_INVALID_BORROWER_STATE = "error.invalid.borrower.state.code"; public static final String ERROR_INVALID_BORROWER_STORAGE_STATE = "error.invalid.borrower.storage.state.code"; public static final String ERROR_BORROWER_STORAGE_STATE_REQUIRED = "error.borrower.storage.state.required"; public static final String ERROR_BORROWER_STORAGE_ZIP_REQUIRED = "error.borrower.storage.zip.required"; public static final String ERROR_CAMPUS_TAG_NUMBER_REQUIRED = "error.campus.tag.number.required"; } public static class AssetGlobal { public static final String ERROR_INVENTORY_STATUS_REQUIRED = "error.asset.inventory.status.code.required"; public static final String ERROR_INVENTORY_STATUS_REQUIRED_FOR_PAYMENT = "error.asset.inventory.status.code.required.for.payment"; public static final String ERROR_OWNER_ACCT_NOT_ACTIVE = "error.asset.owner.account.not.active"; public static final String ERROR_PAYMENT_ACCT_NOT_VALID = "error.asset.payment.account.not.valid"; public static final String MIN_ONE_ASSET_REQUIRED = "error.document.min.one.asset.required"; public static final String MIN_ONE_PAYMENT_REQUIRED = "error.document.min.one.payment.required"; public static final String ERROR_VENDOR_NAME_REQUIRED = "error.capital.asset.vendor.name.required"; public static final String ERROR_MFR_NAME_REQUIRED = "error.capital.asset.manufacturer.name.required"; public static final String ERROR_ACQUISITION_TYPE_CODE_REQUIRED = "error.acquisition.code.required"; public static final String ERROR_ACQUISITION_TYPE_CODE_NOT_ALLOWED = "error.acquisition.code.not.allowed"; public static final String ERROR_INACTIVE_ACQUISITION_TYPE_CODE = "error.inactive.acquisition.code"; public static final String ERROR_OWNER_CHART_INVALID = "error.asset.owner.chart.code.invalid"; public static final String ERROR_OWNER_ACCT_NUMBER_INVALID = "error.asset.owner.account.number.invalid"; public static final String ERROR_CAMPUS_TAG_NUMBER_DUPLICATE = "error.asset.campus.tag.number.duplicate"; public static final String ERROR_CAPITAL_OBJECT_CODE_NOT_ALLOWED = "error.capital.object.code.not.allowed"; public static final String ERROR_CAPITAL_OBJECT_CODE_INVALID = "error.capital.object.code.invalid"; public static final String ERROR_DOCUMENT_TYPE_CODE_NOT_ALLOWED = "error.document.type.code.not.allowed"; public static final String ERROR_ASSET_TYPE_REQUIRED = "error.valid.capital.asset.type.required"; public static final String ERROR_ASSET_LOCATION_DEPENDENCY = "error.asset.location.validation.dependecy"; public static final String ERROR_ASSET_PAYMENT_DEPENDENCY = "error.asset.payment.validation.dependecy"; public static final String ERROR_CAPITAL_ASSET_PAYMENT_AMOUNT_MIN = "error.capital.asset.payment.min.limit"; public static final String ERROR_NON_CAPITAL_ASSET_PAYMENT_AMOUNT_MAX = "error.noncapital.asset.payment.max.limit"; public static final String ERROR_DOCUMENT_POSTING_DATE_REQUIRED = "error.document.posting.date.required"; public static final String ERROR_INVALID_PAYMENT_AMOUNT = "error.payment.amount.invalid"; public static final String ERROR_EXPENDITURE_FINANCIAL_DOCUMENT_NUMBER_REQUIRED = "error.expenditure.financial.document.number.required"; public static final String ERROR_EXPENDITURE_FINANCIAL_DOCUMENT_TYPE_CODE_REQUIRED = "error.expenditure.financial.document.type.code.required"; public static final String ERROR_FINANCIAL_DOCUMENT_POSTING_YEAR_REQUIRED = "error.financial.document.posting.year.required"; public static final String ERROR_UNIVERSITY_NOT_DEFINED_FOR_DATE = "error.university.not.defined.for.date"; public static final String ERROR_SEPARATE_ASSET_TOTAL_COST_NOT_MATCH_PAYMENT_TOTAL_COST = "error.separate.asset.total.cost.not.match.payment.total.cost"; public static final String ERROR_SEPARATE_ASSET_ALREADY_SEPARATED = "error.separate.asset.already.separated"; public static final String ERROR_INVALID_ACQUISITION_INCOME_OBJECT_CODE = "error.invalid.acquisition.income.object.code"; public static final String ERROR_CHANGE_ASSET_TOTAL_AMOUNT_DISALLOW = "error.change.asset.total.amount.disallow"; } public static class AssetSeparate { public static final String ERROR_ASSET_SPLIT_MAX_LIMIT = "error.max.payments.limit"; public static final String ERROR_CAPITAL_ASSET_TYPE_CODE_REQUIRED = "error.capital.asset.type.code.required"; public static final String ERROR_ASSET_DESCRIPTION_REQUIRED = "error.asset.description.required"; public static final String ERROR_MANUFACTURER_REQUIRED = "error.manufacturer.required"; public static final String ERROR_NON_CAPITAL_ASSET_SEPARATE_REQUIRED = "error.non.active.capital.asset.required"; public static final String ERROR_TOTAL_SEPARATE_SOURCE_AMOUNT_REQUIRED = "error.total.separate.source.amount.required"; public static final String ERROR_INVALID_TOTAL_SEPARATE_SOURCE_AMOUNT = "error.total.separate.source.amount.invalid"; public static final String ERROR_ZERO_OR_NEGATIVE_DOLLAR_AMOUNT = "error.zero.or.negative.dollar.amount"; public static final String ERROR_ZERO_OR_NEGATIVE_LOCATION_QUANTITY = "error.zero.or.negative.location.quantity"; public static final String ERROR_SEPARATE_ASSET_BELOW_THRESHOLD = "error.separate.asset.below.threshold"; } public static class Asset { public static final String ERROR_INVALID_SALVAGE_AMOUNT = "error.asset.salvage.amount.not.valid"; } public static class AssetRepairHistory { public static final String ERROR_DUPLICATE_INCIDENT_DATE = "error.duplicate.incident.date"; } public static class AssetLock { public static final String ERROR_ASSET_LOCKED = "error.asset.locked"; } public static class PreTag { public static final String ERROR_PRE_TAG_INVALID_REPRESENTATIVE_ID = "error.invalid.representative.id"; public static final String ERROR_PRE_TAG_NUMBER = "error.invalid.pre.tag.number"; public static final String ERROR_PRE_TAG_DETAIL_EXCESS = "error.pre.tag.detail.excess"; } }
work/src/org/kuali/kfs/module/cam/CamsKeyConstants.java
/* * Copyright 2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.module.cam; /** * Holds error key constants. */ public class CamsKeyConstants { public static final String CONTINUE_QUESTION = "document.question.continue.text"; public static final String ERROR_INVALID_BUILDING_CODE = "error.invalid.building.code"; public static final String ERROR_INVALID_ROOM_NUMBER = "error.invalid.room.number"; public static final String ERROR_NO_DETAIL_LINE = "error.invalid.no.detail.line"; public static final String ERROR_INVALID_IN_SERVICE_DATE = "error.invalid.in.service.date"; public static final String MESSAGE_BATCH_UPLOAD_TITLE_PRE_ASSET_TAGGING = "message.batchUpload.title.pre.asset.tagging"; public static final String ERROR_INVALID_ASSET_WARRANTY_NO = "error.invalid.asset.warranty.no"; public static final String ERROR_CAPITAL_ASSET_VENDOR_NAME_REQUIRED = "error.capital.asset.vendor.name.required"; public static final String ERROR_TAG_NUMBER_DUPLICATE = "error.tag.number.duplicate"; public static final String ERROR_ASSET_RETIRED_CAPITAL = "error.asset.retired.capital"; public static final String ERROR_ASSET_RETIRED_NON_CAPITAL_ACTIVE = "error.asset.retired.non.capital.active"; public static final String ERROR_ASSET_RETIRED_ACT_NON_CAPITAL_2003 = "error.asset.retired.act.non.capital.2003"; public static final String ERROR_FABRICATION_ESTIMATED_TOTAL_AMOUNT_REQUIRED = "error.asset.fabrication.totalAmount.required"; public static final String ERROR_ESTIMATED_FABRICATION_COMPLETION_DATE_REQUIRED = "error.asset.fabrication.completionDate.required"; public static final String ERROR_ESTIMATED_FABRICATION_LIFE_LIMIT_REQUIRED = "error.asset.fabrication.lifeLimit.required"; public static final String ERROR_FABRICATION_ESTIMATED_TOTAL_AMOUNT_NEGATIVE = "error.asset.fabrication.totalAmount.negative"; public static final String ERROR_ESTIMATED_FABRICATION_LIFE_LIMIT_NEGATIVE = "error.asset.fabrication.lifeLimit.negative"; public static final String ORGANIZATION_OWNER_ACCOUNT_INACTIVE = "error.asset.org.owner.account.inactive"; public static final String ERROR_ESTIMATED_FABRICATION_COMPLETION_DATE_PAST = "error.asset.fabrication.completionDate.past"; public static class Depreciation { public static final String NO_ELIGIBLE_FOR_DEPRECIATION_ASSETS_FOUND = "error.batch.depreciation.assetsNotFound"; public static final String ERROR_WHEN_CALCULATING_BASE_AMOUNT = "error.batch.depreciation.baseAmountCalculationError"; public static final String ERROR_WHEN_CALCULATING_DEPRECIATION = "error.batch.depreciation.calculationError"; public static final String ERROR_WHEN_UPDATING_GL_PENDING_ENTRY_TABLE = "error.batch.depreciation.glpeUpdateError"; public static final String DEPRECIATION_DATE_PARAMETER_NOT_FOUND = "error.batch.depreciation.depreciationDateNotFound"; public static final String INVALID_DEPRECIATION_DATE_FORMAT = "error.batch.depreciation.invalidDepreciationDateFormat"; public static final String DEPRECIATION_ALREADY_RAN_MSG = "error.batch.depreciation.alreadyRan"; public static final String MSG_REPORT_DEPRECIATION_HEADING1 = "message.batch.report.depreciation.heading.description"; public static final String MSG_REPORT_DEPRECIATION_HEADING2 = "message.batch.report.depreciation.heading.figures"; } public static class Payment { public static final String ERROR_INVALID_DOC_POST_DATE = "error.payment.invalid.document.postdate"; public static final String ERROR_INVALID_OBJECT_SUBTYPE = "error.asset.payment.invalidObjectSubtypeCode"; public static final String WARNING_NOT_SAME_OBJECT_SUB_TYPES = "warning.payment.object.subtype.not_the_same"; public static final String ERROR_NON_CAPITAL_ASSET = "error.non.capital.asset.payment"; public static final String ERROR_ASSET_EXISTS_IN_DOCUMENT = "error.asset.exists.in.payment.document"; public static final String ERROR_NON_ASSETS_IN_DOCUMENT = "error.payment.document.noAssetsInDocumentFound"; public static final String ERROR_NON_ZERO_COST_ASSETS_ALLOWED = "error.payment.document.noZeroValueAssetsAllowed"; public static final String ERROR_POSTING_DATE_FUTURE_NOT_ALLOWED = "error.posting.date.future.notallowed"; } public static class Transfer { public static final String ERROR_ASSET_RETIRED_NOTRANSFER = "error.asset.retired.notransfer"; public static final String ERROR_CAMPUS_PLANT_FUND_UNKNOWN = "error.campus.plant.fund.unknown"; public static final String ERROR_ORG_PLANT_FUND_UNKNOWN = "error.org.plant.fund.unknown"; public static final String ERROR_OWNER_ACCT_NOT_ACTIVE = "error.account.notactive"; public static final String ERROR_OWNER_CHART_CODE_INVALID = "error.receiving.org.chart.code.invalid"; public static final String ERROR_OWNER_ACCT_INVALID = "error.receiving.org.acct.invalid"; public static final String ERROR_TRFR_FDOC_INVALID = "error.transfer.fund.financial.doc.invalid"; public static final String ERROR_TRFR_FDOC_REQUIRED = "error.transfer.fund.financial.doc.required"; public static final String ERROR_TRFR_LOANED = "error.transfer.asset.loaned"; public static final String ASSET_LOAN_NOTE = "note.asset.loan.active"; public static final String ERROR_INVALID_USER_AUTH_ID = "error.representative.user.invalid"; public static final String ERROR_PAYMENT_OBJECT_CODE_NOT_FOUND = "error.transfer.document.payment.objectcode.doesnt.exists"; public static final String ERROR_INVALID_USER_GROUP_FOR_TRANSFER_NONMOVABLE_ASSET = "error.invalid.user.group.for.transfer.nonmoveable.asset"; public static final String MESSAGE_NO_LEDGER_ENTRY_REQUIRED_TRANSFER = "message.no.ledger.entry.required.transfer"; } public static class GLPosting { public static final String ERROR_ASSET_OBJECT_CODE_NOT_FOUND = "error.asset.object.code.not.found"; public static final String ERROR_ASSET_OBJECT_CODE_INACTIVE = "error.asset.object.code.inactive"; public static final String ERROR_OBJECT_CODE_FROM_ASSET_OBJECT_CODE_NOT_FOUND = "error.object.code.from.asset.object.code.not.found"; public static final String ERROR_OBJECT_CODE_FROM_ASSET_OBJECT_CODE_INACTIVE = "error.object.code.from.asset.object.code.inactive"; public static final String ERROR_OBJECT_CODE_FROM_ASSET_OBJECT_CODE_INVALID = "error.object.code.from.asset.object.code.invalid"; } public static class AssetLocation { public static final String ERROR_INVALID_BUILDING_CODE = "error.invalid.building.code"; public static final String ERROR_INVALID_CAMPUS_CODE = "error.invalid.campus.code"; public static final String ERROR_INVALID_ROOM_NUMBER = "error.invalid.room.code"; public static final String ERROR_INVALID_OFF_CAMPUS_STATE = "error.invalid.state.code"; public static final String ERROR_INVALID_STATE_ZIP_CODE = "error.invalid.state.zip.code"; public static final String ERROR_INVALID_ZIP_CODE = "error.invalid.zip.code"; public static final String ERROR_LOCATION_INFO_REQUIRED = "error.location.info.required"; public static final String ERROR_ONCAMPUS_BUILDING_CODE_REQUIRED = "error.oncampus.building.value.required"; public static final String ERROR_ONCAMPUS_BUILDING_ROOM_NUMBER_REQUIRED = "error.oncampus.room.number.required"; public static final String ERROR_OFFCAMPUS_ADDRESS_REQUIRED = "error.offcampus.address.required"; public static final String ERROR_OFFCAMPUS_CITY_REQUIRED = "error.offcampus.city.required"; public static final String ERROR_OFFCAMPUS_STATE_REQUIRED = "error.offcampus.state.required"; public static final String ERROR_OFFCAMPUS_ZIP_REQUIRED = "error.offcampus.zip.required"; public static final String ERROR_OFFCAMPUS_CONTACT_REQUIRED = "error.offcampus.contactName.required"; public static final String ERROR_OFFCAMPUS_COUNTRY_REQUIRED = "error.offcampus.country.required"; public static final String ERROR_CHOOSE_LOCATION_INFO = "error.location.choose.right"; public static final String ERROR_LOCATION_OFF_CAMPUS_NOT_PERMITTED = "error.location.offcampus.not.permitted"; public static final String ERROR_LOCATION_ON_CAMPUS_NOT_PERMITTED = "error.location.oncampus.not.permitted"; public static final String ERROR_ONCAMPUS_BUILDING_ROOM_NUMBER_NOT_PERMITTED = "error.oncampus.room.number.not.permitted"; public static final String ERROR_ONCAMPUS_SUB_ROOM_NUMBER_NOT_PERMITTED = "error.oncampus.sub.room.number.not.permitted"; public static final String ERROR_CHOOSE_ASSET_TYPE = "error.choose.asset.type.validate.location"; public static final String ERROR_LOCATION_NOT_PERMITTED_ASSET_TYPE = "error.location.not.permitted.asset.type"; } public static class Retirement { public static final String ERROR_RETIREMENT_DETAIL_INFO_NULL = "error.retirement.detail.info.null"; public static final String ERROR_INVALID_RETIREMENT_DETAIL_INFO = "error.invalid.retirement.detail.info"; public static final String ERROR_INVALID_MERGED_TARGET_ASSET_NUMBER = "error.invalid.merged.target.asset.number"; public static final String ERROR_NON_CAPITAL_ASSET_RETIREMENT = "error.non.capital.asset.retirment"; public static final String ERROR_NON_ACTIVE_ASSET_RETIREMENT = "error.non.active.asset.retirment"; public static final String ERROR_INVALID_CAPITAL_ASSET_NUMBER = "error.invalid.capital.asset.number"; public static final String ERROR_DUPLICATE_CAPITAL_ASSET_NUMBER_WITH_TARGET = "error.duplicate.capital.asset.number.with.target"; public static final String ERROR_INVALID_USER_GROUP_FOR_NON_MOVEABLE_ASSET = "error.invalid.user.group.for.nonmoveable.asset"; public static final String ERROR_BLANK_CAPITAL_ASSET_NUMBER = "error.blank.capital.asset.number"; public static final String ERROR_ASSET_RETIREMENT_GLOBAL_NO_ASSET = "error.asset.retirement.global.no.asset"; public static final String ERROR_DISALLOWED_MERGE_RETIREMENT_REASON_CODE = "error.disallowed.merge.retirement.reason.code"; public static final String ERROR_DISALLOWED_RETIREMENT_REASON_CODE = "error.disallowed.retirement.reason.code"; public static final String ERROR_DISALLOWED_MERGE_SEPARATE_REASON_CODE = "error.disallowed.merge.separate.reason.code"; public static final String ERROR_DISALLOWED_RAZE_REASON_CODE = "error.disallowed.raze.reason.code"; public static final String ERROR_MULTIPLE_ASSET_RETIRED = "error.multiple.asset.retired"; public static final String ERROR_LOANED_ASSET_CANNOT_RETIRED = "error.retirement.asset.loaned"; public static final String MESSAGE_NO_LEDGER_ENTRY_REQUIRED_RETIREMENT = "message.no.ledger.entry.required.retirement"; } public static class AssetLocationGlobal { public static final String ERROR_INVALID_CAPITAL_ASSET_NUMBER = "error.asset.location.invalid.capital.asset.number"; public static final String ERROR_INVALID_CAMPUS_CODE = "error.asset.location.invalid.campus.code"; public static final String ERROR_INVALID_BUILDING_CODE = "error.asset.location.invalid.building.code"; public static final String ERROR_INVALID_ROOM_NUMBER = "error.asset.location.invalid.room.code"; public static final String ERROR_TAG_NUMBER_REQUIRED = "error.asset.location.tag.number.required"; public static final String ERROR_DUPLICATE_TAG_NUMBER_FOUND = "error.asset.location.duplicate.tag.number"; public static final String ERROR_DUPLICATE_TAG_NUMBER_WITHIN_DOCUMENT = "error.asset.location.duplicate.tag.within.document"; public static final String ERROR_ASSET_LOCATION_GLOBAL_NO_ASSET_DETAIL = "error.asset.location.no.asset.location.detail.line"; public static final String ERROR_CAMPUS_CODE_REQUIRED = "error.asset.location.campus.code.required"; public static final String ERROR_BUILDING_CODE_REQUIRED = "error.asset.location.building.code.required"; public static final String ERROR_ROOM_NUMBER_REQUIRED = "error.asset.location.room.number.required"; public static final String ERROR_ASSET_AUTHORIZATION = "error.asset.authorization"; } public static class BarcodeInventory { public static final String TITLE_BAR_CODE_INVENTORY = "message.upload.title.barCodeInventory"; public static final String ERROR_INVALID_FIELD = "error.document.invalid.field"; public static final String ERROR_CAPITAL_ASSET_DOESNT_EXIST = "error.document.capitalAsset.not.found"; public static final String ERROR_CAPITAL_ASSET_IS_RETIRED = "error.document.capitalAsset.retired"; public static final String ERROR_DUPLICATED_TAG_NUMBER = "error.document.duplicated.tagNumber"; public static final String ERROR_ASSET_LOCKED = "error.document.locked.asset"; public static final String ERROR_INVALID_FILE_TYPE = "error.uploadFile.invalid.type"; public static final String ERROR_INACTIVE_FIELD = "error.document.inactive.field"; public static final String ERROR_APPROVE_DOCUMENT_WITH_ERROR_EXIST = "error.approve.document.with.error.exist"; public static final String ERROR_RECORDS_NO_SELECTED = "error.document.records_no_selected"; public static final String ERROR_CHECKBOX_MUST_BE_CHECKED = "error.checkbox.must.be.checked"; public static final String ERROR_GLOBAL_REPLACE_SEARCH_CRITERIA = "error.global.replace.empty.fields"; } public static class EquipmentLoanOrReturn { public static final String ERROR_INVALID_BORROWER_ID = "error.invalid.borrower.id"; public static final String ERROR_INVALID_LOAN_DATE = "error.invalid.loan.date"; public static final String ERROR_INVALID_EXPECTED_RETURN_DATE = "error.invalid.expected.return.date"; public static final String ERROR_INVALID_EXPECTED_MAX_DATE = "error.invalid.expected.max.date"; public static final String ERROR_INVALID_LOAN_RETURN_DATE = "error.invalid.loan.return.date"; public static final String ERROR_INVALID_BORROWER_STATE = "error.invalid.borrower.state.code"; public static final String ERROR_INVALID_BORROWER_STORAGE_STATE = "error.invalid.borrower.storage.state.code"; public static final String ERROR_CAMPUS_TAG_NUMBER_REQUIRED = "error.campus.tag.number.required"; } public static class AssetGlobal { public static final String ERROR_INVENTORY_STATUS_REQUIRED = "error.asset.inventory.status.code.required"; public static final String ERROR_INVENTORY_STATUS_REQUIRED_FOR_PAYMENT = "error.asset.inventory.status.code.required.for.payment"; public static final String ERROR_OWNER_ACCT_NOT_ACTIVE = "error.asset.owner.account.not.active"; public static final String ERROR_PAYMENT_ACCT_NOT_VALID = "error.asset.payment.account.not.valid"; public static final String MIN_ONE_ASSET_REQUIRED = "error.document.min.one.asset.required"; public static final String MIN_ONE_PAYMENT_REQUIRED = "error.document.min.one.payment.required"; public static final String ERROR_VENDOR_NAME_REQUIRED = "error.capital.asset.vendor.name.required"; public static final String ERROR_MFR_NAME_REQUIRED = "error.capital.asset.manufacturer.name.required"; public static final String ERROR_ACQUISITION_TYPE_CODE_REQUIRED = "error.acquisition.code.required"; public static final String ERROR_ACQUISITION_TYPE_CODE_NOT_ALLOWED = "error.acquisition.code.not.allowed"; public static final String ERROR_INACTIVE_ACQUISITION_TYPE_CODE = "error.inactive.acquisition.code"; public static final String ERROR_OWNER_CHART_INVALID = "error.asset.owner.chart.code.invalid"; public static final String ERROR_OWNER_ACCT_NUMBER_INVALID = "error.asset.owner.account.number.invalid"; public static final String ERROR_CAMPUS_TAG_NUMBER_DUPLICATE = "error.asset.campus.tag.number.duplicate"; public static final String ERROR_CAPITAL_OBJECT_CODE_NOT_ALLOWED = "error.capital.object.code.not.allowed"; public static final String ERROR_CAPITAL_OBJECT_CODE_INVALID = "error.capital.object.code.invalid"; public static final String ERROR_DOCUMENT_TYPE_CODE_NOT_ALLOWED = "error.document.type.code.not.allowed"; public static final String ERROR_ASSET_TYPE_REQUIRED = "error.valid.capital.asset.type.required"; public static final String ERROR_ASSET_LOCATION_DEPENDENCY = "error.asset.location.validation.dependecy"; public static final String ERROR_ASSET_PAYMENT_DEPENDENCY = "error.asset.payment.validation.dependecy"; public static final String ERROR_CAPITAL_ASSET_PAYMENT_AMOUNT_MIN = "error.capital.asset.payment.min.limit"; public static final String ERROR_NON_CAPITAL_ASSET_PAYMENT_AMOUNT_MAX = "error.noncapital.asset.payment.max.limit"; public static final String ERROR_DOCUMENT_POSTING_DATE_REQUIRED = "error.document.posting.date.required"; public static final String ERROR_INVALID_PAYMENT_AMOUNT = "error.payment.amount.invalid"; public static final String ERROR_EXPENDITURE_FINANCIAL_DOCUMENT_NUMBER_REQUIRED = "error.expenditure.financial.document.number.required"; public static final String ERROR_EXPENDITURE_FINANCIAL_DOCUMENT_TYPE_CODE_REQUIRED = "error.expenditure.financial.document.type.code.required"; public static final String ERROR_FINANCIAL_DOCUMENT_POSTING_YEAR_REQUIRED = "error.financial.document.posting.year.required"; public static final String ERROR_UNIVERSITY_NOT_DEFINED_FOR_DATE = "error.university.not.defined.for.date"; public static final String ERROR_SEPARATE_ASSET_TOTAL_COST_NOT_MATCH_PAYMENT_TOTAL_COST = "error.separate.asset.total.cost.not.match.payment.total.cost"; public static final String ERROR_SEPARATE_ASSET_ALREADY_SEPARATED = "error.separate.asset.already.separated"; public static final String ERROR_INVALID_ACQUISITION_INCOME_OBJECT_CODE = "error.invalid.acquisition.income.object.code"; public static final String ERROR_CHANGE_ASSET_TOTAL_AMOUNT_DISALLOW = "error.change.asset.total.amount.disallow"; } public static class AssetSeparate { public static final String ERROR_ASSET_SPLIT_MAX_LIMIT = "error.max.payments.limit"; public static final String ERROR_CAPITAL_ASSET_TYPE_CODE_REQUIRED = "error.capital.asset.type.code.required"; public static final String ERROR_ASSET_DESCRIPTION_REQUIRED = "error.asset.description.required"; public static final String ERROR_MANUFACTURER_REQUIRED = "error.manufacturer.required"; public static final String ERROR_NON_CAPITAL_ASSET_SEPARATE_REQUIRED = "error.non.active.capital.asset.required"; public static final String ERROR_TOTAL_SEPARATE_SOURCE_AMOUNT_REQUIRED = "error.total.separate.source.amount.required"; public static final String ERROR_INVALID_TOTAL_SEPARATE_SOURCE_AMOUNT = "error.total.separate.source.amount.invalid"; public static final String ERROR_ZERO_OR_NEGATIVE_DOLLAR_AMOUNT = "error.zero.or.negative.dollar.amount"; public static final String ERROR_ZERO_OR_NEGATIVE_LOCATION_QUANTITY = "error.zero.or.negative.location.quantity"; public static final String ERROR_SEPARATE_ASSET_BELOW_THRESHOLD = "error.separate.asset.below.threshold"; } public static class Asset { public static final String ERROR_INVALID_SALVAGE_AMOUNT = "error.asset.salvage.amount.not.valid"; } public static class AssetRepairHistory { public static final String ERROR_DUPLICATE_INCIDENT_DATE = "error.duplicate.incident.date"; } public static class AssetLock { public static final String ERROR_ASSET_LOCKED = "error.asset.locked"; } public static class PreTag { public static final String ERROR_PRE_TAG_INVALID_REPRESENTATIVE_ID = "error.invalid.representative.id"; public static final String ERROR_PRE_TAG_NUMBER = "error.invalid.pre.tag.number"; public static final String ERROR_PRE_TAG_DETAIL_EXCESS = "error.pre.tag.detail.excess"; } }
KULCAP-1271 Asset Add Global - 'Location' tab, no existence check run for 'Off Campus Postal Code' when added. Document can be submitted with a non-existing postal code. Inquiry it from doc search, receive exception:
work/src/org/kuali/kfs/module/cam/CamsKeyConstants.java
KULCAP-1271 Asset Add Global - 'Location' tab, no existence check run for 'Off Campus Postal Code' when added. Document can be submitted with a non-existing postal code. Inquiry it from doc search, receive exception:
Java
agpl-3.0
a868298ea6276b1d5b45d812db18d767d3db7b1c
0
akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow
/* * Copyright (C) 2019 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo FLOW. * * Akvo FLOW is free software: you can redistribute it and modify it under the terms of * the GNU Affero General Public License (AGPL) as published by the Free Software Foundation, * either version 3 of the License or any later version. * * Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License included below for more details. * * The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>. */ package org.akvo.flow.xml; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto; import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto.QuestionType; import org.waterforpeople.mapping.app.gwt.client.survey.TranslationDto; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.gallatinsystems.survey.domain.Question; import com.gallatinsystems.survey.domain.Translation; @JsonInclude(JsonInclude.Include.NON_NULL) public class XmlQuestion { private static String FREE_TYPE = "free"; //Used for both FREE_TEXT and NUMBER private static String NUMERIC_VALIDATION_TYPE = "numeric"; @JacksonXmlProperty(localName = "options", isAttribute = false) private XmlOptions options; @JacksonXmlProperty(localName = "validationRule", isAttribute = false) private XmlValidationRule validationRule; //only one @JacksonXmlProperty(localName = "dependency", isAttribute = false) private XmlDependency dependency; //only one @JacksonXmlProperty(localName = "help", isAttribute = false) private XmlHelp help; @JacksonXmlElementWrapper(localName = "altText", useWrapping = false) private List<XmlAltText> altText; @JacksonXmlProperty(localName = "text", isAttribute = false) private String text; @JacksonXmlElementWrapper(localName = "levels", useWrapping = true) private List<XmlLevel> level; @JacksonXmlProperty(localName = "id", isAttribute = true) private long id; @JacksonXmlProperty(localName = "order", isAttribute = true) private int order; @JacksonXmlProperty(localName = "type", isAttribute = true) private String type; @JacksonXmlProperty(localName = "mandatory", isAttribute = true) private boolean mandatory; @JacksonXmlProperty(localName = "requireDoubleEntry", isAttribute = true) private Boolean requireDoubleEntry; @JacksonXmlProperty(localName = "localeNameFlag", isAttribute = true) private boolean localeNameFlag; @JacksonXmlProperty(localName = "locked", isAttribute = true) private Boolean locked; @JacksonXmlProperty(localName = "localeLocationFlag", isAttribute = true) private Boolean localeLocationFlag; @JacksonXmlProperty(localName = "caddisflyResourceUuid", isAttribute = true) private String caddisflyResourceUuid; @JacksonXmlProperty(localName = "cascadeResource", isAttribute = true) private String cascadeResource; @JacksonXmlProperty(localName = "allowPoints", isAttribute = true) private Boolean allowPoints; @JacksonXmlProperty(localName = "allowLine", isAttribute = true) private Boolean allowLine; @JacksonXmlProperty(localName = "allowPolygon", isAttribute = true) private Boolean allowPolygon; public XmlQuestion() { } //Create a jackson object from a domain object public XmlQuestion(Question q) { text = q.getText(); id = q.getKey().getId(); order = q.getOrder(); mandatory = Boolean.TRUE.equals(q.getMandatoryFlag()); localeNameFlag = Boolean.TRUE.equals(q.getLocaleNameFlag()); if (Boolean.TRUE.equals(q.getLocaleLocationFlag())) { localeLocationFlag = Boolean.TRUE; } if (Boolean.TRUE.equals(q.getGeoLocked())) { locked = Boolean.TRUE; } if (q.getTip() != null) { help = new XmlHelp(q.getTip()); } type = q.getType().toString().toLowerCase(); //Things specific to a question type switch (q.getType()) { case NUMBER: type = FREE_TYPE; validationRule = new XmlValidationRule(q); //This signals number if (Boolean.TRUE.equals(q.getRequireDoubleEntry())) { requireDoubleEntry = Boolean.TRUE; } break; //Could have done a fall-through here ;) case FREE_TEXT: type = FREE_TYPE; if (Boolean.TRUE.equals(q.getRequireDoubleEntry())) { requireDoubleEntry = Boolean.TRUE; } break; case GEOSHAPE: allowPoints = Boolean.TRUE.equals(q.getAllowPoints()); allowLine = Boolean.TRUE.equals(q.getAllowLine()); allowPolygon = Boolean.TRUE.equals(q.getAllowPolygon()); break; case CASCADE: cascadeResource = q.getCascadeResourceId().toString(); //level names, if any if (q.getLevelNames() != null) { level = new ArrayList<>(); for (String text: q.getLevelNames()) { level.add(new XmlLevel(text)); } } break; case CADDISFLY: caddisflyResourceUuid = q.getCaddisflyResourceUuid(); break; case OPTION: //Now copy any options into the transfer container if (q.getQuestionOptionMap() != null) { options = new XmlOptions(q); } break; default: break; } if (Boolean.TRUE.equals(q.getDependentFlag())) { dependency = new XmlDependency(q.getDependentQuestionId(), q.getDependentQuestionAnswer()); } //Translations, if any if (q.getTranslationMap() != null) { altText = new ArrayList<>(); for (Translation t: q.getTranslationMap().values()) { altText.add(new XmlAltText(t)); } } } /** * @return a Dto object with relevant fields copied */ public QuestionDto toDto() { QuestionDto dto = new QuestionDto(); dto.setKeyId(id); dto.setText(text); dto.setOrder(order); dto.setMandatoryFlag(mandatory); dto.setLocaleNameFlag(localeNameFlag); dto.setRequireDoubleEntry(requireDoubleEntry); //Type is more complicated: QuestionType t; //FREE_TEXT, OPTION, NUMBER, GEO, PHOTO, VIDEO, SCAN, TRACK, STRENGTH, DATE, CASCADE, GEOSHAPE, SIGNATURE, CADDISFLY if (FREE_TYPE.equalsIgnoreCase(type)) { //Text OR number if (validationRule != null && NUMERIC_VALIDATION_TYPE.equals(validationRule.getValidationType())) { t = QuestionType.NUMBER; } else { t = QuestionType.FREE_TEXT; } } else { try { t = QuestionType.valueOf(type.toUpperCase()); } catch (IllegalArgumentException e) { t = QuestionType.FREE_TEXT; } } dto.setType(t); if (options != null) { dto.setOptionContainerDto(options.toDto()); //exporter code expects these in the QuestionDto: dto.setAllowMultipleFlag(options.getAllowMultiple()); dto.setAllowOtherFlag(options.getAllowOther()); } //Translations if (altText != null) { HashMap<String,TranslationDto> qMap = new HashMap<>(); for (XmlAltText alt : altText) { qMap.put(alt.getLanguage(), alt.toDto()); } dto.setTranslationMap(qMap); } //return cascade levels as a List<String> if (level != null) { List<String> cl = new ArrayList<>(); for (XmlLevel lvl : level) { cl.add(lvl.getText()); } dto.setLevelNames(cl); } if (caddisflyResourceUuid != null) { dto.setCaddisflyResourceUuid(caddisflyResourceUuid); } return dto; } @Override public String toString() { return "question{" + "id='" + id + "',order='" + order + "',type='" + type + "',mandatory='" + mandatory + "',requireDoubleEntry='" + requireDoubleEntry + "',locked='" + locked + "',localeNameFlag='" + localeNameFlag + "',allowPoints='" + allowPoints + "',allowLines='" + allowLine + "',allowPolygon='" + allowPolygon + "',options=" + ((options != null) ? options.toString() : "(null)") + "'}"; } public long getId() { return id; } public void setId(long id) { this.id = id; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean getMandatory() { return mandatory; } public void setMandatory(boolean mandatory) { this.mandatory = mandatory; } public Boolean getLocaleNameFlag() { return localeNameFlag; } public void setLocaleNameFlag(Boolean localeNameFlag) { this.localeNameFlag = localeNameFlag; } public List<XmlAltText> getAltText() { return altText; } public void setAltText(List<XmlAltText> altText) { this.altText = altText; } public XmlOptions getOptions() { return options; } public void setOptions(XmlOptions options) { this.options = options; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Boolean isLocaleLocationFlag() { return localeLocationFlag; } public void setLocaleLocationFlag(Boolean localeLocationFlag) { this.localeLocationFlag = localeLocationFlag; } public String getCaddisflyResourceUuid() { return caddisflyResourceUuid; } public void setCaddisflyResourceUuid(String caddisflyResourceUuid) { this.caddisflyResourceUuid = caddisflyResourceUuid; } public String getCascadeResource() { return cascadeResource; } public void setCascadeResource(String cascadeResource) { this.cascadeResource = cascadeResource; } public XmlValidationRule getValidationRule() { return validationRule; } public void setValidationRule(XmlValidationRule validationRule) { this.validationRule = validationRule; } public Boolean getLocked() { return locked; } public void setLocked(Boolean locked) { this.locked = locked; } public Boolean getAllowPoints() { return allowPoints; } public void setAllowPoints(Boolean allowPoints) { this.allowPoints = allowPoints; } public Boolean getAllowLine() { return allowLine; } public void setAllowLine(Boolean allowLine) { this.allowLine = allowLine; } public Boolean getAllowPolygon() { return allowPolygon; } public void setAllowPolygon(Boolean allowPolygon) { this.allowPolygon = allowPolygon; } public XmlHelp getHelp() { return help; } public void setHelp(XmlHelp help) { this.help = help; } public List<XmlLevel> getLevel() { return level; } public void setLevel(List<XmlLevel> level) { this.level = level; } public Boolean getRequireDoubleEntry() { return requireDoubleEntry; } public void setRequireDoubleEntry(Boolean requireDoubleEntry) { this.requireDoubleEntry = requireDoubleEntry; } }
GAE/src/org/akvo/flow/xml/XmlQuestion.java
/* * Copyright (C) 2019 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo FLOW. * * Akvo FLOW is free software: you can redistribute it and modify it under the terms of * the GNU Affero General Public License (AGPL) as published by the Free Software Foundation, * either version 3 of the License or any later version. * * Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License included below for more details. * * The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>. */ package org.akvo.flow.xml; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto; import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto.QuestionType; import org.waterforpeople.mapping.app.gwt.client.survey.TranslationDto; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.gallatinsystems.survey.domain.Question; import com.gallatinsystems.survey.domain.Translation; @JsonInclude(JsonInclude.Include.NON_NULL) public class XmlQuestion { private static String FREE_TYPE = "free"; //Used for both FREE_TEXT and NUMBER private static String NUMERIC_VALIDATION_TYPE = "numeric"; @JacksonXmlProperty(localName = "options", isAttribute = false) private XmlOptions options; @JacksonXmlProperty(localName = "validationRule", isAttribute = false) private XmlValidationRule validationRule; //only one @JacksonXmlProperty(localName = "dependency", isAttribute = false) private XmlDependency dependency; //only one @JacksonXmlProperty(localName = "help", isAttribute = false) private XmlHelp help; @JacksonXmlElementWrapper(localName = "altText", useWrapping = false) private List<XmlAltText> altText; @JacksonXmlProperty(localName = "text", isAttribute = false) private String text; @JacksonXmlElementWrapper(localName = "levels", useWrapping = true) private List<XmlLevel> level; @JacksonXmlProperty(localName = "id", isAttribute = true) private long id; @JacksonXmlProperty(localName = "order", isAttribute = true) private int order; @JacksonXmlProperty(localName = "type", isAttribute = true) private String type; @JacksonXmlProperty(localName = "mandatory", isAttribute = true) private boolean mandatory; @JacksonXmlProperty(localName = "requireDoubleEntry", isAttribute = true) private Boolean requireDoubleEntry; @JacksonXmlProperty(localName = "localeNameFlag", isAttribute = true) private boolean localeNameFlag; @JacksonXmlProperty(localName = "locked", isAttribute = true) private Boolean locked; @JacksonXmlProperty(localName = "localeLocationFlag", isAttribute = true) private Boolean localeLocationFlag; @JacksonXmlProperty(localName = "caddisflyResourceUuid", isAttribute = true) private String caddisflyResourceUuid; @JacksonXmlProperty(localName = "cascadeResource", isAttribute = true) private String cascadeResource; @JacksonXmlProperty(localName = "allowPoints", isAttribute = true) private Boolean allowPoints; @JacksonXmlProperty(localName = "allowLine", isAttribute = true) private Boolean allowLine; @JacksonXmlProperty(localName = "allowPolygon", isAttribute = true) private Boolean allowPolygon; public XmlQuestion() { } //Create a jackson object from a domain object public XmlQuestion(Question q) { text = q.getText(); id = q.getKey().getId(); order = q.getOrder(); mandatory = Boolean.TRUE.equals(q.getMandatoryFlag()); localeNameFlag = Boolean.TRUE.equals(q.getLocaleNameFlag()); if (Boolean.TRUE.equals(q.getLocaleLocationFlag())) { localeLocationFlag = Boolean.TRUE; } if (Boolean.TRUE.equals(q.getGeoLocked())) { locked = Boolean.TRUE; } if (q.getTip() != null) { help = new XmlHelp(q.getTip()); } type = q.getType().toString().toLowerCase(); //Things specific to a question type switch (q.getType()) { case NUMBER: type = FREE_TYPE; validationRule = new XmlValidationRule(q); //This signals number if (Boolean.TRUE.equals(q.getRequireDoubleEntry())) { requireDoubleEntry = Boolean.TRUE; } break; //Could have done a fall-through here ;) case FREE_TEXT: type = FREE_TYPE; if (Boolean.TRUE.equals(q.getRequireDoubleEntry())) { requireDoubleEntry = Boolean.TRUE; } break; case GEOSHAPE: allowPoints = Boolean.TRUE.equals(q.getAllowPoints()); allowLine = Boolean.TRUE.equals(q.getAllowLine()); allowPolygon = Boolean.TRUE.equals(q.getAllowPolygon()); break; case CASCADE: cascadeResource = q.getCascadeResourceId().toString(); //level names, if any if (q.getLevelNames() != null) { level = new ArrayList<>(); for (String text: q.getLevelNames()) { level.add(new XmlLevel(text)); } } break; case CADDISFLY: caddisflyResourceUuid = q.getCaddisflyResourceUuid(); break; case OPTION: //Now copy any options into the transfer container if (q.getQuestionOptionMap() != null) { options = new XmlOptions(q); } break; default: break; } if (Boolean.TRUE == q.getDependentFlag()) { dependency = new XmlDependency(q.getDependentQuestionId(), q.getDependentQuestionAnswer()); } //Translations, if any if (q.getTranslationMap() != null) { altText = new ArrayList<>(); for (Translation t: q.getTranslationMap().values()) { altText.add(new XmlAltText(t)); } } } /** * @return a Dto object with relevant fields copied */ public QuestionDto toDto() { QuestionDto dto = new QuestionDto(); dto.setKeyId(id); dto.setText(text); dto.setOrder(order); dto.setMandatoryFlag(mandatory); dto.setLocaleNameFlag(localeNameFlag); dto.setRequireDoubleEntry(requireDoubleEntry); //Type is more complicated: QuestionType t; //FREE_TEXT, OPTION, NUMBER, GEO, PHOTO, VIDEO, SCAN, TRACK, STRENGTH, DATE, CASCADE, GEOSHAPE, SIGNATURE, CADDISFLY if (FREE_TYPE.equalsIgnoreCase(type)) { //Text OR number if (validationRule != null && NUMERIC_VALIDATION_TYPE.equals(validationRule.getValidationType())) { t = QuestionType.NUMBER; } else { t = QuestionType.FREE_TEXT; } } else { try { t = QuestionType.valueOf(type.toUpperCase()); } catch (IllegalArgumentException e) { t = QuestionType.FREE_TEXT; } } dto.setType(t); if (options != null) { dto.setOptionContainerDto(options.toDto()); //exporter code expects these in the QuestionDto: dto.setAllowMultipleFlag(options.getAllowMultiple()); dto.setAllowOtherFlag(options.getAllowOther()); } //Translations if (altText != null) { HashMap<String,TranslationDto> qMap = new HashMap<>(); for (XmlAltText alt : altText) { qMap.put(alt.getLanguage(), alt.toDto()); } dto.setTranslationMap(qMap); } //return cascade levels as a List<String> if (level != null) { List<String> cl = new ArrayList<>(); for (XmlLevel lvl : level) { cl.add(lvl.getText()); } dto.setLevelNames(cl); } if (caddisflyResourceUuid != null) { dto.setCaddisflyResourceUuid(caddisflyResourceUuid); } return dto; } @Override public String toString() { return "question{" + "id='" + id + "',order='" + order + "',type='" + type + "',mandatory='" + mandatory + "',requireDoubleEntry='" + requireDoubleEntry + "',locked='" + locked + "',localeNameFlag='" + localeNameFlag + "',allowPoints='" + allowPoints + "',allowLines='" + allowLine + "',allowPolygon='" + allowPolygon + "',options=" + ((options != null) ? options.toString() : "(null)") + "'}"; } public long getId() { return id; } public void setId(long id) { this.id = id; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean getMandatory() { return mandatory; } public void setMandatory(boolean mandatory) { this.mandatory = mandatory; } public Boolean getLocaleNameFlag() { return localeNameFlag; } public void setLocaleNameFlag(Boolean localeNameFlag) { this.localeNameFlag = localeNameFlag; } public List<XmlAltText> getAltText() { return altText; } public void setAltText(List<XmlAltText> altText) { this.altText = altText; } public XmlOptions getOptions() { return options; } public void setOptions(XmlOptions options) { this.options = options; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Boolean isLocaleLocationFlag() { return localeLocationFlag; } public void setLocaleLocationFlag(Boolean localeLocationFlag) { this.localeLocationFlag = localeLocationFlag; } public String getCaddisflyResourceUuid() { return caddisflyResourceUuid; } public void setCaddisflyResourceUuid(String caddisflyResourceUuid) { this.caddisflyResourceUuid = caddisflyResourceUuid; } public String getCascadeResource() { return cascadeResource; } public void setCascadeResource(String cascadeResource) { this.cascadeResource = cascadeResource; } public XmlValidationRule getValidationRule() { return validationRule; } public void setValidationRule(XmlValidationRule validationRule) { this.validationRule = validationRule; } public Boolean getLocked() { return locked; } public void setLocked(Boolean locked) { this.locked = locked; } public Boolean getAllowPoints() { return allowPoints; } public void setAllowPoints(Boolean allowPoints) { this.allowPoints = allowPoints; } public Boolean getAllowLine() { return allowLine; } public void setAllowLine(Boolean allowLine) { this.allowLine = allowLine; } public Boolean getAllowPolygon() { return allowPolygon; } public void setAllowPolygon(Boolean allowPolygon) { this.allowPolygon = allowPolygon; } public XmlHelp getHelp() { return help; } public void setHelp(XmlHelp help) { this.help = help; } public List<XmlLevel> getLevel() { return level; } public void setLevel(List<XmlLevel> level) { this.level = level; } public Boolean getRequireDoubleEntry() { return requireDoubleEntry; } public void setRequireDoubleEntry(Boolean requireDoubleEntry) { this.requireDoubleEntry = requireDoubleEntry; } }
[#3115]One last equals sign
GAE/src/org/akvo/flow/xml/XmlQuestion.java
[#3115]One last equals sign
Java
lgpl-2.1
e964e17574117731711b734bbc78283cbd0c4e1a
0
exedio/copernica,exedio/copernica,exedio/copernica
/* * Copyright (C) 2004-2007 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope.testmodel; import com.exedio.cope.Model; import com.exedio.cope.Type; public class Main { public static final Type[] modelTypes = new Type[] { ItemWithSingleUnique.TYPE, UniqueFinal.TYPE, ItemWithSingleUniqueNotNull.TYPE, ItemWithDoubleUnique.TYPE, EmptyItem.TYPE, EmptyItem2.TYPE, AttributeItem.TYPE, AttributeEmptyItem.TYPE, StringItem.TYPE, MediaServletItem.TYPE, PlusItem.TYPE, QualifiedItem.TYPE, QualifiedSubItem.TYPE, QualifiedEmptyQualifier.TYPE, QualifiedStringQualifier.TYPE, QualifiedIntegerEnumQualifier.TYPE, PointerTargetItem.TYPE, PointerItem.TYPE, FinalItem.TYPE, CollisionItem1.TYPE, CollisionItem2.TYPE, }; public static final Model model = new Model( /*new Migration[]{ new Migration(2, "comment2 a bit longer", "sql"), new Migration(1, "comment1", "sql"), },*/ modelTypes); }
runtime/testmodelsrc/com/exedio/cope/testmodel/Main.java
/* * Copyright (C) 2004-2007 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope.testmodel; import com.exedio.cope.Model; import com.exedio.cope.Type; public class Main { public static final Type[] modelTypes = new Type[] { ItemWithSingleUnique.TYPE, UniqueFinal.TYPE, ItemWithSingleUniqueNotNull.TYPE, ItemWithDoubleUnique.TYPE, EmptyItem.TYPE, EmptyItem2.TYPE, AttributeItem.TYPE, AttributeEmptyItem.TYPE, StringItem.TYPE, MediaServletItem.TYPE, PlusItem.TYPE, QualifiedItem.TYPE, QualifiedSubItem.TYPE, QualifiedEmptyQualifier.TYPE, QualifiedStringQualifier.TYPE, QualifiedIntegerEnumQualifier.TYPE, PointerTargetItem.TYPE, PointerItem.TYPE, FinalItem.TYPE, CollisionItem1.TYPE, CollisionItem2.TYPE, }; public static final Model model = new Model(modelTypes); }
add disabled migrations for testing git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@7333 e7d4fc99-c606-0410-b9bf-843393a9eab7
runtime/testmodelsrc/com/exedio/cope/testmodel/Main.java
add disabled migrations for testing
Java
apache-2.0
8780d249ed96831b196c300c4fc942d5fa9a6640
0
AsuraTeam/dubbos,AsuraTeam/dubbos,AsuraTeam/dubbos
/* * Copyright 1999-2012 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.cluster.configurator; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.rpc.cluster.Configurator; /** * AbstractOverrideConfigurator * * @author william.liangf */ public abstract class AbstractConfigurator implements Configurator { private final URL configuratorUrl; public AbstractConfigurator(URL url) { if (url == null) { throw new IllegalArgumentException("configurator url == null"); } this.configuratorUrl = url; } public URL getUrl() { return configuratorUrl; } public URL configure(URL url) { if (isMatch(getUrl(), url)) { return doConfigure(url); } return url; } public int compareTo(Configurator o) { if (o == null) { return -1; } return getUrl().getHost().compareTo(o.getUrl().getHost()); } private boolean isMatch(URL configuratorUrl, URL providerUrl) { if (configuratorUrl == null || configuratorUrl.getHost() == null || providerUrl == null || providerUrl.getHost() == null) { return false; } /*if (! providerUrl.getServiceKey().equals(configuratorUrl.getServiceKey())) { return false; }*/ if (Constants.ANYHOST_VALUE.equals(configuratorUrl.getHost()) || providerUrl.getHost().equals(configuratorUrl.getHost())) { String configApplication = configuratorUrl.getParameter(Constants.APPLICATION_KEY, configuratorUrl.getUsername()); String providerApplication = providerUrl.getParameter(Constants.APPLICATION_KEY, providerUrl.getUsername()); if (configApplication == null || configApplication.equals(providerApplication)) { if (configuratorUrl.getPort() > 0) { return providerUrl.getPort() == configuratorUrl.getPort(); } else { return true; } } } return false; } protected abstract URL doConfigure(URL url); }
dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/configurator/AbstractConfigurator.java
/* * Copyright 1999-2012 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.cluster.configurator; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.rpc.cluster.Configurator; /** * AbstractOverrideConfigurator * * @author william.liangf */ public abstract class AbstractConfigurator implements Configurator { private final URL configuratorUrl; public AbstractConfigurator(URL url) { if (url == null) { throw new IllegalArgumentException("configurator url == null"); } this.configuratorUrl = url; } public URL getUrl() { return configuratorUrl; } public URL configure(URL url) { if (isMatch(getUrl(), url)) { return doConfigure(url); } return url; } public int compareTo(Configurator o) { if (o == null) { return -1; } return getUrl().getHost().compareTo(o.getUrl().getHost()); } private boolean isMatch(URL configuratorUrl, URL providerUrl) { if (configuratorUrl == null || configuratorUrl.getHost() == null || providerUrl == null || providerUrl.getHost() == null) { return false; } /*if (! providerUrl.getServiceKey().equals(configuratorUrl.getServiceKey())) { return false; }*/ if (Constants.ANYHOST_VALUE.equals(configuratorUrl.getHost()) || providerUrl.getHost().equals(configuratorUrl.getHost())) { String configApplication = configuratorUrl.getParameter(Constants.APPLICATION_KEY, configuratorUrl.getUsername()); String providerApplication = providerUrl.getParameter(Constants.APPLICATION_KEY, providerUrl.getUsername()); if (configApplication == null || configApplication .equals(providerApplication)) { if (configuratorUrl.getPort() > 0) { return providerUrl.getPort() == configuratorUrl.getPort(); } else { return true; } } } return false; } protected abstract URL doConfigure(URL url); }
DUBBO-204 修改应用名常量 git-svn-id: 3d0e7b608a819e97e591a7b753bfd1a27aaeb5ee@1738 1a56cb94-b969-4eaa-88fa-be21384802f2
dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/configurator/AbstractConfigurator.java
DUBBO-204 修改应用名常量
Java
apache-2.0
b4b22d1aa96b878628e286946984c8c9315e81dd
0
mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid
package org.usergrid.rest.applications.collections; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.usergrid.utils.JsonUtils.loadJsonFromResourceFile; import static org.usergrid.utils.JsonUtils.mapToFormattedJsonString; import static org.usergrid.utils.MapUtils.hashMap; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID; import javax.ws.rs.core.MediaType; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.usergrid.rest.AbstractRestTest; import org.usergrid.utils.JsonUtils; import com.fasterxml.jackson.databind.JsonNode; import com.sun.jersey.api.client.UniformInterfaceException; /** * @author zznate * @author tnine */ public class CollectionsResourceTest extends AbstractRestTest { private static Logger logger = LoggerFactory .getLogger(CollectionsResourceTest.class); @Test public void postToBadPath() { Map<String, String> payload = hashMap("name", "Austin").map("state", "TX"); JsonNode node = null; try { node = resource() .path("/test-organization/test-organization/test-app/cities") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).post(JsonNode.class, payload); } catch (UniformInterfaceException e) { assertEquals("Should receive a 400 Not Found", 400, e.getResponse() .getStatus()); } } @Test public void postToEmptyCollection() { Map<String, String> payload = new HashMap<String, String>(); JsonNode node = resource().path("/test-organization/test-app/cities") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).post(JsonNode.class, payload); assertNull(getEntity(node, 0)); assertNull(node.get("count")); } @Test public void stringWithSpaces() { Map<String, String> payload = hashMap("summaryOverview", "My Summary").map( "caltype", "personal"); JsonNode node = resource() .path("/test-organization/test-app/calendarlists") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).post(JsonNode.class, payload); UUID id = getEntityId(node, 0); // post a second entity payload = hashMap("summaryOverview", "Your Summary").map("caltype", "personal"); node = resource().path("/test-organization/test-app/calendarlists") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).post(JsonNode.class, payload); // query for the first entity String query = "summaryOverview = 'My Summary'"; JsonNode queryResponse = resource() .path("/test-organization/test-app/calendarlists") .queryParam("access_token", access_token).queryParam("ql", query) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).get(JsonNode.class); UUID returnedId = getEntityId(queryResponse, 0); assertEquals(id, returnedId); assertEquals(1, queryResponse.get("entities").size()); } @SuppressWarnings("unchecked") @Test public void testCollectionSchema() throws Exception { Map<String, Object> payload = loadJsonFromResourceFile( CollectionsResourceTest.class, Map.class, "cat-schema.json"); assertNotNull(payload); JsonNode node = resource().path("/test-organization/test-app/cats/schema") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).put(JsonNode.class, payload); try { payload = loadJsonFromResourceFile(CollectionsResourceTest.class, Map.class, "bad-schema.json"); assertNotNull(payload); node = resource().path("/test-organization/test-app/cats/schema") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).put(JsonNode.class, payload); Assert.fail(); } catch (UniformInterfaceException iae) { logger.error("\n" + mapToFormattedJsonString(iae.getResponse() .getEntity(JsonNode.class))); // ok } try { payload = new LinkedHashMap<String, Object>(); properties.put("name", "Tom"); node = resource().path("/test-organization/test-app/cats") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).put(JsonNode.class, payload); Assert.fail(); } catch (UniformInterfaceException iae) { logger.error("\n" + mapToFormattedJsonString(iae.getResponse() .getEntity(JsonNode.class))); // ok } payload = new LinkedHashMap<String, Object>(); payload.put("name", "Tom"); payload.put("color", "tabby"); node = resource().path("/test-organization/test-app/cats") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).put(JsonNode.class, payload); assertNotNull(node); node = resource().path("/test-organization/test-app/cats/schema") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).get(JsonNode.class); assertNotNull(node); assertEquals("http://json-schema.org/draft-04/schema#", node.get("data").get("$schema").asText()); assertEquals("object", node.get("data").get("type").asText()); logger.info("\n" + JsonUtils.mapToFormattedJsonString(node)); } }
stack/rest/src/test/java/org/usergrid/rest/applications/collections/CollectionsResourceTest.java
package org.usergrid.rest.applications.collections; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.usergrid.utils.JsonUtils.loadJsonFromResourceFile; import static org.usergrid.utils.JsonUtils.mapToFormattedJsonString; import static org.usergrid.utils.MapUtils.hashMap; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID; import javax.ws.rs.core.MediaType; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.usergrid.rest.AbstractRestTest; import org.usergrid.utils.JsonUtils; import com.fasterxml.jackson.databind.JsonNode; import com.sun.jersey.api.client.UniformInterfaceException; /** * @author zznate * @author tnine */ public class CollectionsResourceTest extends AbstractRestTest { private static Logger logger = LoggerFactory .getLogger(CollectionsResourceTest.class); @Test public void postToBadPath() { Map<String, String> payload = hashMap("name", "Austin").map("state", "TX"); JsonNode node = null; try { node = resource() .path("/test-organization/test-organization/test-app/cities") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).post(JsonNode.class, payload); } catch (UniformInterfaceException e) { assertEquals("Should receive a 400 Not Found", 400, e.getResponse() .getStatus()); } } @Test public void postToEmptyCollection() { Map<String, String> payload = new HashMap<String, String>(); JsonNode node = resource().path("/test-organization/test-app/cities") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).post(JsonNode.class, payload); assertNull(getEntity(node, 0)); assertNull(node.get("count")); } @Test public void stringWithSpaces() { Map<String, String> payload = hashMap("summaryOverview", "My Summary").map( "caltype", "personal"); JsonNode node = resource() .path("/test-organization/test-app/calendarlists") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).post(JsonNode.class, payload); UUID id = getEntityId(node, 0); // post a second entity payload = hashMap("summaryOverview", "Your Summary").map("caltype", "personal"); node = resource().path("/test-organization/test-app/calendarlists") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).post(JsonNode.class, payload); // query for the first entity String query = "summaryOverview = 'My Summary'"; JsonNode queryResponse = resource() .path("/test-organization/test-app/calendarlists") .queryParam("access_token", access_token).queryParam("ql", query) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).get(JsonNode.class); UUID returnedId = getEntityId(queryResponse, 0); assertEquals(id, returnedId); assertEquals(1, queryResponse.get("entities").size()); } @SuppressWarnings("unchecked") @Test public void testCollectionSchema() throws Exception { Map<String, Object> payload = loadJsonFromResourceFile( CollectionsResourceTest.class, Map.class, "cat-schema.json"); assertNotNull(payload); JsonNode node = resource().path("/test-organization/test-app/cats/schema") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).put(JsonNode.class, payload); try { payload = loadJsonFromResourceFile(CollectionsResourceTest.class, Map.class, "bad-schema.json"); assertNotNull(payload); node = resource().path("/test-organization/test-app/cats/schema") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).put(JsonNode.class, payload); Assert.fail(); } catch (UniformInterfaceException iae) { logger.error("\n" + mapToFormattedJsonString(iae.getResponse() .getEntity(JsonNode.class))); // ok } try { payload = new LinkedHashMap<String, Object>(); properties.put("name", "Tom"); node = resource().path("/test-organization/test-app/cats") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).put(JsonNode.class, payload); Assert.fail(); } catch (UniformInterfaceException iae) { logger.error("\n" + mapToFormattedJsonString(iae.getResponse() .getEntity(JsonNode.class))); // ok } payload = new LinkedHashMap<String, Object>(); payload.put("name", "Tom"); payload.put("color", "tabby"); node = resource().path("/test-organization/test-app/cats") .queryParam("access_token", access_token) .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE).put(JsonNode.class, payload); assertNotNull(node); } }
test schema retrieval
stack/rest/src/test/java/org/usergrid/rest/applications/collections/CollectionsResourceTest.java
test schema retrieval
Java
apache-2.0
02fac8c5986fb95db3f24437419f765ef7b384a1
0
opencb/biodata
/* * <!-- * ~ Copyright 2015-2017 OpenCB * ~ * ~ Licensed under the Apache License, Version 2.0 (the "License"); * ~ you may not use this file except in compliance with the License. * ~ You may obtain a copy of the License at * ~ * ~ http://www.apache.org/licenses/LICENSE-2.0 * ~ * ~ Unless required by applicable law or agreed to in writing, software * ~ distributed under the License is distributed on an "AS IS" BASIS, * ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * ~ See the License for the specific language governing permissions and * ~ limitations under the License. * --> * */ package org.opencb.biodata.models.variant.annotation; import org.opencb.biodata.models.variant.annotation.exceptions.SOTermNotAvailableException; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * * @author Cristina Yenyxe Gonzalez Garcia &lt;[email protected]&gt; * * TODO Handle duplicated terms in tmpTermToAccession (synonymous_variant...) * TODO Load using ontology file: http://song.cvs.sourceforge.net/viewvc/song/ontology/so.obo */ public class ConsequenceTypeMappings { public static final Map<String, Integer> termToAccession; public static final Map<Integer, String> accessionToTerm; static { Map<String, Integer> tmpTermToAccession = new HashMap<>(); // Fill the term to accession map tmpTermToAccession.put("transcript_ablation", 1893); tmpTermToAccession.put("copy_number_change", 1563); tmpTermToAccession.put("structural_variant", 1537); tmpTermToAccession.put("terminator_codon_variant", 1590); tmpTermToAccession.put("splice_donor_variant", 1575); tmpTermToAccession.put("splice_acceptor_variant", 1574); tmpTermToAccession.put("stop_gained", 1587); tmpTermToAccession.put("frameshift_variant", 1589); tmpTermToAccession.put("stop_lost", 1578); tmpTermToAccession.put("initiator_codon_variant", 1582); tmpTermToAccession.put("inframe_insertion", 1821); tmpTermToAccession.put("inframe_deletion", 1822); tmpTermToAccession.put("inframe_variant", 1650); tmpTermToAccession.put("missense_variant", 1583); tmpTermToAccession.put("transcript_amplification", 1889); tmpTermToAccession.put("splice_region_variant", 1630); tmpTermToAccession.put("incomplete_terminal_codon_variant", 1626); tmpTermToAccession.put("synonymous_variant", 1819); tmpTermToAccession.put("stop_retained_variant", 1567); tmpTermToAccession.put("start_retained_variant", 2019); tmpTermToAccession.put("coding_sequence_variant", 1580); tmpTermToAccession.put("miRNA", 276); tmpTermToAccession.put("miRNA_target_site", 934); tmpTermToAccession.put("mature_miRNA_variant", 1620); tmpTermToAccession.put("5_prime_UTR_variant", 1623); tmpTermToAccession.put("3_prime_UTR_variant", 1624); tmpTermToAccession.put("exon_variant", 1791); tmpTermToAccession.put("non_coding_transcript_exon_variant", 1792); tmpTermToAccession.put("non_coding_transcript_variant", 1619); tmpTermToAccession.put("intron_variant", 1627); tmpTermToAccession.put("NMD_transcript_variant", 1621); tmpTermToAccession.put("TFBS_ablation", 1895); tmpTermToAccession.put("TFBS_amplification", 1892); tmpTermToAccession.put("TF_binding_site_variant", 1782); tmpTermToAccession.put("regulatory_region_variant", 1566); tmpTermToAccession.put("regulatory_region_ablation", 1894); tmpTermToAccession.put("regulatory_region_amplification", 1891); tmpTermToAccession.put("feature_elongation", 1907); tmpTermToAccession.put("feature_truncation", 1906); tmpTermToAccession.put("feature_variant", 1878); tmpTermToAccession.put("intergenic_variant", 1628); tmpTermToAccession.put("lincRNA", 1463); tmpTermToAccession.put("downstream_gene_variant", 1632); tmpTermToAccession.put("2KB_downstream_variant", 2083); tmpTermToAccession.put("upstream_gene_variant", 1631); tmpTermToAccession.put("2KB_upstream_variant", 1636); tmpTermToAccession.put("SNV", 1483); tmpTermToAccession.put("SNP", 694); tmpTermToAccession.put("RNA_polymerase_promoter", 1203); tmpTermToAccession.put("CpG_island", 307); tmpTermToAccession.put("DNAseI_hypersensitive_site", 685); tmpTermToAccession.put("polypeptide_variation_site", 336); tmpTermToAccession.put("protein_altering_variant", 1818); tmpTermToAccession.put("start_lost", 2012); Map<Integer, String> tmpAccessionToTerm = new HashMap<>(); // Fill the accession to term map for(String key : tmpTermToAccession.keySet()) { tmpAccessionToTerm.put(tmpTermToAccession.get(key), key); } /******************************************************** * ********* DEPRECATED !!!!!!!! ******************* ********************************************************/ tmpTermToAccession.put("downstream_variant", 1632); tmpTermToAccession.put("2KB_downstream_gene_variant", 1632); tmpTermToAccession.put("upstream_variant", 1631); tmpTermToAccession.put("2KB_upstream_gene_variant", 1631); termToAccession = Collections.unmodifiableMap(tmpTermToAccession); accessionToTerm = Collections.unmodifiableMap(tmpAccessionToTerm); } public static String getSoAccessionString(String SOName) throws SOTermNotAvailableException { if (termToAccession.get(SOName) == null) { throw new SOTermNotAvailableException(SOName); }else { String soAccession = Integer.toString(termToAccession.get(SOName)); return String.format("SO:%0" + (7 - soAccession.length()) + "d%s", 0, soAccession); } } }
biodata-models/src/main/java/org/opencb/biodata/models/variant/annotation/ConsequenceTypeMappings.java
/* * <!-- * ~ Copyright 2015-2017 OpenCB * ~ * ~ Licensed under the Apache License, Version 2.0 (the "License"); * ~ you may not use this file except in compliance with the License. * ~ You may obtain a copy of the License at * ~ * ~ http://www.apache.org/licenses/LICENSE-2.0 * ~ * ~ Unless required by applicable law or agreed to in writing, software * ~ distributed under the License is distributed on an "AS IS" BASIS, * ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * ~ See the License for the specific language governing permissions and * ~ limitations under the License. * --> * */ package org.opencb.biodata.models.variant.annotation; import org.opencb.biodata.models.variant.annotation.exceptions.SOTermNotAvailableException; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * * @author Cristina Yenyxe Gonzalez Garcia &lt;[email protected]&gt; * * TODO Handle duplicated terms in tmpTermToAccession (synonymous_variant...) * TODO Load using ontology file: http://song.cvs.sourceforge.net/viewvc/song/ontology/so.obo */ public class ConsequenceTypeMappings { public static final Map<String, Integer> termToAccession; public static final Map<Integer, String> accessionToTerm; static { Map<String, Integer> tmpTermToAccession = new HashMap<>(); // Fill the term to accession map tmpTermToAccession.put("transcript_ablation", 1893); tmpTermToAccession.put("copy_number_change", 1563); tmpTermToAccession.put("structural_variant", 1537); tmpTermToAccession.put("terminator_codon_variant", 1590); tmpTermToAccession.put("splice_donor_variant", 1575); tmpTermToAccession.put("splice_acceptor_variant", 1574); tmpTermToAccession.put("stop_gained", 1587); tmpTermToAccession.put("frameshift_variant", 1589); tmpTermToAccession.put("stop_lost", 1578); tmpTermToAccession.put("initiator_codon_variant", 1582); tmpTermToAccession.put("inframe_insertion", 1821); tmpTermToAccession.put("inframe_deletion", 1822); tmpTermToAccession.put("inframe_variant", 1650); tmpTermToAccession.put("missense_variant", 1583); tmpTermToAccession.put("transcript_amplification", 1889); tmpTermToAccession.put("splice_region_variant", 1630); tmpTermToAccession.put("incomplete_terminal_codon_variant", 1626); tmpTermToAccession.put("synonymous_variant", 1819); tmpTermToAccession.put("stop_retained_variant", 1567); tmpTermToAccession.put("start_retained_variant", 2019); tmpTermToAccession.put("coding_sequence_variant", 1580); tmpTermToAccession.put("miRNA", 276); tmpTermToAccession.put("miRNA_target_site", 934); tmpTermToAccession.put("mature_miRNA_variant", 1620); tmpTermToAccession.put("5_prime_UTR_variant", 1623); tmpTermToAccession.put("3_prime_UTR_variant", 1624); tmpTermToAccession.put("exon_variant", 1791); tmpTermToAccession.put("non_coding_transcript_exon_variant", 1792); tmpTermToAccession.put("non_coding_transcript_variant", 1619); tmpTermToAccession.put("intron_variant", 1627); tmpTermToAccession.put("NMD_transcript_variant", 1621); tmpTermToAccession.put("TFBS_ablation", 1895); tmpTermToAccession.put("TFBS_amplification", 1892); tmpTermToAccession.put("TF_binding_site_variant", 1782); tmpTermToAccession.put("regulatory_region_variant", 1566); tmpTermToAccession.put("regulatory_region_ablation", 1894); tmpTermToAccession.put("regulatory_region_amplification", 1891); tmpTermToAccession.put("feature_elongation", 1907); tmpTermToAccession.put("feature_truncation", 1906); tmpTermToAccession.put("feature_variant", 1878); tmpTermToAccession.put("intergenic_variant", 1628); tmpTermToAccession.put("lincRNA", 1463); tmpTermToAccession.put("downstream_gene_variant", 1632); tmpTermToAccession.put("2KB_downstream_variant", 2083); tmpTermToAccession.put("upstream_gene_variant", 1631); tmpTermToAccession.put("2KB_upstream_variant", 1636); tmpTermToAccession.put("SNV", 1483); tmpTermToAccession.put("SNP", 694); tmpTermToAccession.put("RNA_polymerase_promoter", 1203); tmpTermToAccession.put("CpG_island", 307); tmpTermToAccession.put("DNAseI_hypersensitive_site", 685); tmpTermToAccession.put("polypeptide_variation_site", 336); tmpTermToAccession.put("protein_altering_variant", 1818); tmpTermToAccession.put("start_lost", 2012); Map<Integer, String> tmpAccessionToTerm = new HashMap<>(); // Fill the accession to term map for(String key : tmpTermToAccession.keySet()) { tmpAccessionToTerm.put(tmpTermToAccession.get(key), key); } /******************************************************** * ********* DEPRECATED !!!!!!!! ******************* ********************************************************/ tmpTermToAccession.put("downstream_gene_variant", 1632); tmpTermToAccession.put("2KB_downstream_gene_variant", 1632); tmpTermToAccession.put("upstream_gene_variant", 1631); tmpTermToAccession.put("2KB_upstream_gene_variant", 1631); termToAccession = Collections.unmodifiableMap(tmpTermToAccession); accessionToTerm = Collections.unmodifiableMap(tmpAccessionToTerm); } public static String getSoAccessionString(String SOName) throws SOTermNotAvailableException { if (termToAccession.get(SOName) == null) { throw new SOTermNotAvailableException(SOName); }else { String soAccession = Integer.toString(termToAccession.get(SOName)); return String.format("SO:%0" + (7 - soAccession.length()) + "d%s", 0, soAccession); } } }
models: Synchronize deprecated terms of consequence type mappings
biodata-models/src/main/java/org/opencb/biodata/models/variant/annotation/ConsequenceTypeMappings.java
models: Synchronize deprecated terms of consequence type mappings